INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
List entities attached to the given role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy
def list_attached_role_policies(role_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy '''...
Create SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.create_saml_provider my_saml_provider_name saml_metadata_document
def create_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Create SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.create_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=regi...
Get SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider_arn my_saml_provider_name
def get_saml_provider_arn(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider_arn my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) t...
Delete SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.delete_saml_provider my_saml_provider_name
def delete_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Delete SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.delete_saml_provider my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) ...
List SAML providers. CLI Example: .. code-block:: bash salt myminion boto_iam.list_saml_providers
def list_saml_providers(region=None, key=None, keyid=None, profile=None): ''' List SAML providers. CLI Example: .. code-block:: bash salt myminion boto_iam.list_saml_providers ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: providers = [] ...
Get SAML provider document. CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider arn
def get_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider document. CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider arn ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: prov...
Validate the beacon configuration
def validate(config): ''' Validate the beacon configuration ''' # Configuration for adb beacon should be a dictionary with states array if not isinstance(config, list): log.info('Configuration for adb beacon must be a list.') return False, ('Configuration for adb beacon must be a lis...
Emit the status of all devices returned by adb Specify the device states that should emit an event, there will be an event for each device with the event type and device specified. .. code-block:: yaml beacons: adb: - states: - offline - u...
def beacon(config): ''' Emit the status of all devices returned by adb Specify the device states that should emit an event, there will be an event for each device with the event type and device specified. .. code-block:: yaml beacons: adb: - states: ...
Add a value to the named set USAGE: .. code-block:: yaml foo: reg.set: - add: bar - match: my/custom/event
def set_(name, add, match): ''' Add a value to the named set USAGE: .. code-block:: yaml foo: reg.set: - add: bar - match: my/custom/event ''' ret = {'name': name, 'changes': {}, 'comment': '', 'result': True} if n...
Add the specified values to the named list If ``stamp`` is True, then the timestamp from the event will also be added if ``prune`` is set to an integer higher than ``0``, then only the last ``prune`` values will be kept in the list. USAGE: .. code-block:: yaml foo: reg.list: ...
def list_(name, add, match, stamp=False, prune=0): ''' Add the specified values to the named list If ``stamp`` is True, then the timestamp from the event will also be added if ``prune`` is set to an integer higher than ``0``, then only the last ``prune`` values will be kept in the list. USAGE:...
Accept a numeric value from the matched events and store a running average of the values in the given register. If the specified value is not numeric it will be skipped USAGE: .. code-block:: yaml foo: reg.mean: - add: data_field - match: my/custom/event
def mean(name, add, match): ''' Accept a numeric value from the matched events and store a running average of the values in the given register. If the specified value is not numeric it will be skipped USAGE: .. code-block:: yaml foo: reg.mean: - add: data_field ...
Clear the namespace from the register USAGE: .. code-block:: yaml clearns: reg.clear: - name: myregister
def clear(name): ''' Clear the namespace from the register USAGE: .. code-block:: yaml clearns: reg.clear: - name: myregister ''' ret = {'name': name, 'changes': {}, 'comment': '', 'result': True} if name in __reg__: _...
Delete the namespace from the register USAGE: .. code-block:: yaml deletens: reg.delete: - name: myregister
def delete(name): ''' Delete the namespace from the register USAGE: .. code-block:: yaml deletens: reg.delete: - name: myregister ''' ret = {'name': name, 'changes': {}, 'comment': '', 'result': True} if name in __reg__: ...
Set a key in etcd name The etcd key name, for example: ``/foo/bar/baz``. value The value the key should contain. profile Optional, defaults to ``None``. Sets the etcd profile to use which has been defined in the Salt Master config. .. code-block:: yaml ...
def set_(name, value, profile=None, **kwargs): ''' Set a key in etcd name The etcd key name, for example: ``/foo/bar/baz``. value The value the key should contain. profile Optional, defaults to ``None``. Sets the etcd profile to use which has been defined in the Sal...
Create a directory in etcd. name The etcd directory name, for example: ``/foo/bar/baz``. profile Optional, defaults to ``None``. Sets the etcd profile to use which has been defined in the Salt Master config. .. code-block:: yaml my_etd_config: etcd.ho...
def directory(name, profile=None, **kwargs): ''' Create a directory in etcd. name The etcd directory name, for example: ``/foo/bar/baz``. profile Optional, defaults to ``None``. Sets the etcd profile to use which has been defined in the Salt Master config. .. code-block...
Deletes a key from etcd name The etcd key name to remove, for example ``/foo/bar/baz``. recurse Optional, defaults to ``False``. If ``True`` performs a recursive delete. profile Optional, defaults to ``None``. Sets the etcd profile to use which has been defined in the Salt...
def rm(name, recurse=False, profile=None, **kwargs): ''' Deletes a key from etcd name The etcd key name to remove, for example ``/foo/bar/baz``. recurse Optional, defaults to ``False``. If ``True`` performs a recursive delete. profile Optional, defaults to ``None``. Sets t...
The etcd watcher, called to invoke the watch command. When called, execute a etcd function based on a watch call requisite. .. note:: This state exists to support special handling of the ``watch`` :ref:`requisite <requisites>`. It should not be called directly. Parameters for this func...
def mod_watch(name, **kwargs): ''' The etcd watcher, called to invoke the watch command. When called, execute a etcd function based on a watch call requisite. .. note:: This state exists to support special handling of the ``watch`` :ref:`requisite <requisites>`. It should not be called ...
Determine which packages own the currently running services. By default, excludes files whose full path starts with ``/dev``, ``/home``, ``/media``, ``/proc``, ``/run``, ``/sys``, ``/tmp`` and ``/var``. This can be overridden by passing in a new list to ``exclude``. CLI Example: salt myminion ...
def running_service_owners( exclude=('/dev', '/home', '/media', '/proc', '/run', '/sys/', '/tmp', '/var') ): ''' Determine which packages own the currently running services. By default, excludes files whose full path starts with ``/dev``, ``/home``, ``/media``, ``/proc``, ``...
Return which packages own each of the services that are currently enabled. CLI Example: salt myminion introspect.enabled_service_owners
def enabled_service_owners(): ''' Return which packages own each of the services that are currently enabled. CLI Example: salt myminion introspect.enabled_service_owners ''' error = {} if 'pkg.owner' not in __salt__: error['Unsupported Package Manager'] = ( 'The mod...
Return running and enabled services in a highstate structure. By default also returns package dependencies for those services, which means that package definitions must be created outside this function. To drop the package dependencies, set ``requires`` to False. CLI Example: salt myminion int...
def service_highstate(requires=True): ''' Return running and enabled services in a highstate structure. By default also returns package dependencies for those services, which means that package definitions must be created outside this function. To drop the package dependencies, set ``requires`` to F...
Return the targets
def targets(tgt, tgt_type='glob', **kwargs): ''' Return the targets ''' ret = {} ports = __opts__['ssh_scan_ports'] if not isinstance(ports, list): # Comma-separate list of integers ports = list(map(int, six.text_type(ports).split(','))) hosts = list(NodeSet(tgt)) host_a...
Gather some system data and then calculate buffer space. Result is in bytes.
def _gather_buffer_space(): ''' Gather some system data and then calculate buffer space. Result is in bytes. ''' if HAS_PSUTIL and psutil.version_info >= (0, 6, 0): # Oh good, we have psutil. This will be quick. total_mem = psutil.virtual_memory().total else: # Avoid...
Normalize file or pillar roots.
def _normalize_roots(file_roots): ''' Normalize file or pillar roots. ''' for saltenv, dirs in six.iteritems(file_roots): normalized_saltenv = six.text_type(saltenv) if normalized_saltenv != saltenv: file_roots[normalized_saltenv] = file_roots.pop(saltenv) if not isin...
If the pillar_roots option has a key that is None then we will error out, just replace it with an empty list
def _validate_pillar_roots(pillar_roots): ''' If the pillar_roots option has a key that is None then we will error out, just replace it with an empty list ''' if not isinstance(pillar_roots, dict): log.warning('The pillar_roots parameter is not properly formatted,' ' usin...
If the file_roots option has a key that is None then we will error out, just replace it with an empty list
def _validate_file_roots(file_roots): ''' If the file_roots option has a key that is None then we will error out, just replace it with an empty list ''' if not isinstance(file_roots, dict): log.warning('The file_roots parameter is not properly formatted,' ' using defaults...
Applies shell globbing to a set of directories and returns the expanded paths
def _expand_glob_path(file_roots): ''' Applies shell globbing to a set of directories and returns the expanded paths ''' unglobbed_path = [] for path in file_roots: try: if glob.has_magic(path): unglobbed_path.extend(glob.glob(path)) else: ...
Check that all of the types of values passed into the config are of the right types
def _validate_opts(opts): ''' Check that all of the types of values passed into the config are of the right types ''' def format_multi_opt(valid_type): try: num_types = len(valid_type) except TypeError: # Bare type name won't have a length, return the name of ...
Ensure we're not using any invalid ssh_minion_opts. We want to make sure that the ssh_minion_opts does not override any pillar or fileserver options inherited from the master config. To add other items, modify the if statement in the for loop below.
def _validate_ssh_minion_opts(opts): ''' Ensure we're not using any invalid ssh_minion_opts. We want to make sure that the ssh_minion_opts does not override any pillar or fileserver options inherited from the master config. To add other items, modify the if statement in the for loop below. ''' ...
Append a domain to the existing id if it doesn't already exist
def _append_domain(opts): ''' Append a domain to the existing id if it doesn't already exist ''' # Domain already exists if opts['id'].endswith(opts['append_domain']): return opts['id'] # Trailing dot should mean an FQDN that is terminated, leave it alone. if opts['id'].endswith('.')...
Read in a config file from a given path and process it into a dictionary
def _read_conf_file(path): ''' Read in a config file from a given path and process it into a dictionary ''' log.debug('Reading configuration from %s', path) with salt.utils.files.fopen(path, 'r') as conf_file: try: conf_opts = salt.utils.yaml.safe_load(conf_file) or {} ex...
Return an absolute path. In case ``relative_to`` is passed and ``path`` is not an absolute path, we try to prepend ``relative_to`` to ``path``and if that path exists, return that one
def _absolute_path(path, relative_to=None): ''' Return an absolute path. In case ``relative_to`` is passed and ``path`` is not an absolute path, we try to prepend ``relative_to`` to ``path``and if that path exists, return that one ''' if path and os.path.isabs(path): return path if ...
Returns configuration dict from parsing either the file described by ``path`` or the environment variable described by ``env_var`` as YAML.
def load_config(path, env_var, default_path=None, exit_on_config_errors=True): ''' Returns configuration dict from parsing either the file described by ``path`` or the environment variable described by ``env_var`` as YAML. ''' if path is None: # When the passed path is None, we just want the...
Parses extra configuration file(s) specified in an include list in the main config file.
def include_config(include, orig_path, verbose, exit_on_config_errors=False): ''' Parses extra configuration file(s) specified in an include list in the main config file. ''' # Protect against empty option if not include: return {} if orig_path is None: # When the passed pat...
Prepends the options that represent filesystem paths with value of the 'root_dir' option.
def prepend_root_dir(opts, path_options): ''' Prepends the options that represent filesystem paths with value of the 'root_dir' option. ''' root_dir = os.path.abspath(opts['root_dir']) def_root_dir = salt.syspaths.ROOT_DIR.rstrip(os.sep) for path_option in path_options: if path_optio...
Inserts path into python path taking into consideration 'root_dir' option.
def insert_system_path(opts, paths): ''' Inserts path into python path taking into consideration 'root_dir' option. ''' if isinstance(paths, six.string_types): paths = [paths] for path in paths: path_options = {'path': path, 'root_dir': opts['root_dir']} prepend_root_dir(path...
Reads in the minion configuration file and sets up special options This is useful for Minion-side operations, such as the :py:class:`~salt.client.Caller` class, and manually running the loader interface. .. code-block:: python import salt.config minion_opts = salt.config.minion_config...
def minion_config(path, env_var='SALT_MINION_CONFIG', defaults=None, cache_minion_id=False, ignore_config_errors=True, minion_id=None, role='minion'): ''' Reads in the minion configuration file and sets u...
Recurse for sdb:// links for opts
def apply_sdb(opts, sdb_opts=None): ''' Recurse for sdb:// links for opts ''' # Late load of SDB to keep CLI light import salt.utils.sdb if sdb_opts is None: sdb_opts = opts if isinstance(sdb_opts, six.string_types) and sdb_opts.startswith('sdb://'): return salt.utils.sdb.sdb...
Read in the Salt Cloud config and return the dict
def cloud_config(path=None, env_var='SALT_CLOUD_CONFIG', defaults=None, master_config_path=None, master_config=None, providers_config_path=None, providers_config=None, profiles_config_path=None, profiles_config=None): ''' Read in the Salt Cloud config and retur...
Return a cloud config
def apply_cloud_config(overrides, defaults=None): ''' Return a cloud config ''' if defaults is None: defaults = DEFAULT_CLOUD_OPTS.copy() config = defaults.copy() if overrides: config.update(overrides) # If the user defined providers in salt cloud's main configuration file,...
Read in the salt cloud VM config file
def vm_profiles_config(path, providers, env_var='SALT_CLOUDVM_CONFIG', defaults=None): ''' Read in the salt cloud VM config file ''' if defaults is None: defaults = VM_CONFIG_DEFAULTS overrides = salt.config.load_config( ...
Read in the salt cloud providers configuration file
def cloud_providers_config(path, env_var='SALT_CLOUD_PROVIDERS_CONFIG', defaults=None): ''' Read in the salt cloud providers configuration file ''' if defaults is None: defaults = PROVIDER_CONFIG_DEFAULTS overrides = salt.config.load_con...
Apply the loaded cloud providers configuration.
def apply_cloud_providers_config(overrides, defaults=None): ''' Apply the loaded cloud providers configuration. ''' if defaults is None: defaults = PROVIDER_CONFIG_DEFAULTS config = defaults.copy() if overrides: config.update(overrides) # Is the user still using the old for...
Search and return a setting in a known order: 1. In the virtual machine's configuration 2. In the virtual machine's profile configuration 3. In the virtual machine's provider configuration 4. In the salt cloud configuration if global searching is enabled 5. Return the provided d...
def get_cloud_config_value(name, vm_, opts, default=None, search_global=True): ''' Search and return a setting in a known order: 1. In the virtual machine's configuration 2. In the virtual machine's profile configuration 3. In the virtual machine's provider configuration 4. In t...
Check and return the first matching and fully configured cloud provider configuration.
def is_provider_configured(opts, provider, required_keys=(), log_message=True, aliases=()): ''' Check and return the first matching and fully configured cloud provider configuration. ''' if ':' in provider: alias, driver = provider.split(':') if alias not in opts['providers']: ...
Check if the requested profile contains the minimum required parameters for a profile. Required parameters include image and provider for all drivers, while some drivers also require size keys. .. versionadded:: 2015.8.0
def is_profile_configured(opts, provider, profile_name, vm_=None): ''' Check if the requested profile contains the minimum required parameters for a profile. Required parameters include image and provider for all drivers, while some drivers also require size keys. .. versionadded:: 2015.8.0 ...
Check if the driver's dependencies are available. .. versionadded:: 2015.8.0 driver The name of the driver. dependencies The dictionary of dependencies to check.
def check_driver_dependencies(driver, dependencies): ''' Check if the driver's dependencies are available. .. versionadded:: 2015.8.0 driver The name of the driver. dependencies The dictionary of dependencies to check. ''' ret = True for key, value in six.iteritems(dep...
Helper function, writes minion id to a cache file.
def _cache_id(minion_id, cache_file): ''' Helper function, writes minion id to a cache file. ''' path = os.path.dirname(cache_file) try: if not os.path.isdir(path): os.makedirs(path) except OSError as exc: # Handle race condition where dir is created after os.path.isd...
Evaluate the function that determines the ID if the 'id_function' option is set and return the result
def call_id_function(opts): ''' Evaluate the function that determines the ID if the 'id_function' option is set and return the result ''' if opts.get('id'): return opts['id'] # Import 'salt.loader' here to avoid a circular dependency import salt.loader as loader if isinstance(o...
Depending on the values of `minion_id_remove_domain`, remove all domains or a single domain from a FQDN, effectivly generating a hostname.
def remove_domain_from_fqdn(opts, newid): ''' Depending on the values of `minion_id_remove_domain`, remove all domains or a single domain from a FQDN, effectivly generating a hostname. ''' opt_domain = opts.get('minion_id_remove_domain') if opt_domain is True: if '.' in newid: ...
Guess the id of the minion. If CONFIG_DIR/minion_id exists, use the cached minion ID from that file. If no minion id is configured, use multiple sources to find a FQDN. If no FQDN is found you may get an ip address. Returns two values: the detected ID, and a boolean value noting whether or not an ...
def get_id(opts, cache_minion_id=False): ''' Guess the id of the minion. If CONFIG_DIR/minion_id exists, use the cached minion ID from that file. If no minion id is configured, use multiple sources to find a FQDN. If no FQDN is found you may get an ip address. Returns two values: the detected ...
Resolves string names to integer constant in ssl configuration.
def _update_ssl_config(opts): ''' Resolves string names to integer constant in ssl configuration. ''' if opts['ssl'] in (None, False): opts['ssl'] = None return if opts['ssl'] is True: opts['ssl'] = {} return import ssl for key, prefix in (('cert_reqs', 'CERT_...
Adjusts the log_file based on the log_dir override
def _adjust_log_file_override(overrides, default_log_file): ''' Adjusts the log_file based on the log_dir override ''' if overrides.get('log_dir'): # Adjust log_file if a log_dir override is introduced if overrides.get('log_file'): if not os.path.isabs(overrides['log_file']):...
Returns minion configurations dict.
def apply_minion_config(overrides=None, defaults=None, cache_minion_id=False, minion_id=None): ''' Returns minion configurations dict. ''' if defaults is None: defaults = DEFAULT_MINION_OPTS.copy() if overrides is None: ...
Update discovery config for all instances. :param opts: :return:
def _update_discovery_config(opts): ''' Update discovery config for all instances. :param opts: :return: ''' if opts.get('discovery') not in (None, False): if opts['discovery'] is True: opts['discovery'] = {} discovery_config = {'attempts': 3, 'pause': 5, 'port': 452...
Reads in the master configuration file and sets up default options This is useful for running the actual master daemon. For running Master-side client interfaces that need the master opts see :py:func:`salt.client.client_config`.
def master_config(path, env_var='SALT_MASTER_CONFIG', defaults=None, exit_on_config_errors=False): ''' Reads in the master configuration file and sets up default options This is useful for running the actual master daemon. For running Master-side client interfaces that need the master opts see :py:...
Returns master configurations dict.
def apply_master_config(overrides=None, defaults=None): ''' Returns master configurations dict. ''' if defaults is None: defaults = DEFAULT_MASTER_OPTS.copy() if overrides is None: overrides = {} opts = defaults.copy() opts['__role'] = 'master' _adjust_log_file_override(...
Read in the Salt Master config file and add additional configs that need to be stubbed out for salt-api
def api_config(path): ''' Read in the Salt Master config file and add additional configs that need to be stubbed out for salt-api ''' # Let's grab a copy of salt-api's required defaults opts = DEFAULT_API_OPTS.copy() # Let's override them with salt's master opts opts.update(client_confi...
Load Master configuration data Usage: .. code-block:: python import salt.config master_opts = salt.config.client_config('/etc/salt/master') Returns a dictionary of the Salt Master configuration file with necessary options needed to communicate with a locally-running Salt Master daemo...
def client_config(path, env_var='SALT_CLIENT_CONFIG', defaults=None): ''' Load Master configuration data Usage: .. code-block:: python import salt.config master_opts = salt.config.client_config('/etc/salt/master') Returns a dictionary of the Salt Master configuration file with ne...
Read in the salt master config file and add additional configs that need to be stubbed out for spm .. versionadded:: 2015.8.0
def spm_config(path): ''' Read in the salt master config file and add additional configs that need to be stubbed out for spm .. versionadded:: 2015.8.0 ''' # Let's grab a copy of salt's master default opts defaults = DEFAULT_MASTER_OPTS.copy() # Let's override them with spm's required d...
Returns the spm configurations dict. .. versionadded:: 2015.8.1
def apply_spm_config(overrides, defaults): ''' Returns the spm configurations dict. .. versionadded:: 2015.8.1 ''' opts = defaults.copy() _adjust_log_file_override(overrides, defaults['log_file']) if overrides: opts.update(overrides) # Prepend root_dir to other paths prepen...
Render config template, substituting grains where found.
def _render_template(config_file): ''' Render config template, substituting grains where found. ''' dirname, filename = os.path.split(config_file) env = jinja2.Environment(loader=jinja2.FileSystemLoader(dirname)) template = env.get_template(filename) return template.render(__grains__)
Return a value for 'name' from the config file options. If the 'name' is not in the config, the 'default' value is returned. This method converts unicode values to str type under python 2.
def _config(name, conf, default=None): ''' Return a value for 'name' from the config file options. If the 'name' is not in the config, the 'default' value is returned. This method converts unicode values to str type under python 2. ''' try: value = conf[name] except KeyError: ...
Aggregates LDAP search result based on rules, returns a dictionary. Rules: Attributes tagged in the pillar config as 'attrs' or 'lists' are scanned for a 'key=value' format (non matching entries are ignored. Entries matching the 'attrs' tag overwrite previous values where the key matches a previou...
def _result_to_dict(data, result, conf, source): ''' Aggregates LDAP search result based on rules, returns a dictionary. Rules: Attributes tagged in the pillar config as 'attrs' or 'lists' are scanned for a 'key=value' format (non matching entries are ignored. Entries matching the 'attrs' tag ...
Builds connection and search arguments, performs the LDAP search and formats the results as a dictionary appropriate for pillar use.
def _do_search(conf): ''' Builds connection and search arguments, performs the LDAP search and formats the results as a dictionary appropriate for pillar use. ''' # Build LDAP connection args connargs = {} for name in ['server', 'port', 'tls', 'binddn', 'bindpw', 'anonymous']: connar...
Execute LDAP searches and return the aggregated data
def ext_pillar(minion_id, # pylint: disable=W0613 pillar, # pylint: disable=W0613 config_file): ''' Execute LDAP searches and return the aggregated data ''' config_template = None try: config_template = _render_template(config_file) except jinja2.exception...
Import the certificate file into the given certificate store. :param str name: The path of the certificate file to import. :param str cert_format: The certificate format. Specify 'cer' for X.509, or 'pfx' for PKCS #12. :param str context: The name of the certificate store location context. :param str s...
def import_cert(name, cert_format=_DEFAULT_FORMAT, context=_DEFAULT_CONTEXT, store=_DEFAULT_STORE, exportable=True, password='', saltenv='base'): ''' Import the certificate file into the given certificate store. :param str name: The path of the certificate file to import. :param str cer...
Remove the certificate from the given certificate store. :param str thumbprint: The thumbprint value of the target certificate. :param str context: The name of the certificate store location context. :param str store: The name of the certificate store. Example of usage with only the required arguments...
def remove_cert(name, thumbprint, context=_DEFAULT_CONTEXT, store=_DEFAULT_STORE): ''' Remove the certificate from the given certificate store. :param str thumbprint: The thumbprint value of the target certificate. :param str context: The name of the certificate store location context. :param str s...
Set a key/value pair in the etcd service
def set_(key, value, service=None, profile=None): # pylint: disable=W0613 ''' Set a key/value pair in the etcd service ''' client = _get_conn(profile) client.set(key, value) return get(key, service, profile)
Get a value from the etcd service
def get(key, service=None, profile=None): # pylint: disable=W0613 ''' Get a value from the etcd service ''' client = _get_conn(profile) result = client.get(key) return result.value
Get a value from the etcd service
def delete(key, service=None, profile=None): # pylint: disable=W0613 ''' Get a value from the etcd service ''' client = _get_conn(profile) try: client.delete(key) return True except Exception: return False
.. versionadded:: 2014.7.0 Verify the chain is exist. name A user-defined chain name. table The table to own the chain. family Networking family, either ipv4 or ipv6
def chain_present(name, table='filter', table_type=None, hook=None, priority=None, family='ipv4'): ''' .. versionadded:: 2014.7.0 Verify the chain is exist. name A user-defined chain name. table The table to own the chain. family Networking family, either ipv4 or ipv6...
.. versionadded:: 2014.7.0 Verify the chain is absent. family Networking family, either ipv4 or ipv6
def chain_absent(name, table='filter', family='ipv4'): ''' .. versionadded:: 2014.7.0 Verify the chain is absent. family Networking family, either ipv4 or ipv6 ''' ret = {'name': name, 'changes': {}, 'result': None, 'comment': ''} chain_check = __...
.. versionadded:: 0.17.0 Append a rule to a chain name A user-defined name to call this rule by in another part of a state or formula. This should not be an actual rule. family Network family, ipv4 or ipv6. All other arguments are passed in with the same name as the long opti...
def append(name, family='ipv4', **kwargs): ''' .. versionadded:: 0.17.0 Append a rule to a chain name A user-defined name to call this rule by in another part of a state or formula. This should not be an actual rule. family Network family, ipv4 or ipv6. All other argu...
.. versionadded:: 2014.7.0 Flush current nftables state family Networking family, either ipv4 or ipv6
def flush(name, family='ipv4', **kwargs): ''' .. versionadded:: 2014.7.0 Flush current nftables state family Networking family, either ipv4 or ipv6 ''' ret = {'name': name, 'changes': {}, 'result': None, 'comment': ''} for ignore in _STATE_INTERNA...
Execute Riak commands
def __execute_cmd(name, cmd): ''' Execute Riak commands ''' return __salt__['cmd.run_all']( '{0} {1}'.format(salt.utils.path.which(name), cmd) )
Start Riak CLI Example: .. code-block:: bash salt '*' riak.start
def start(): ''' Start Riak CLI Example: .. code-block:: bash salt '*' riak.start ''' ret = {'comment': '', 'success': False} cmd = __execute_cmd('riak', 'start') if cmd['retcode'] != 0: ret['comment'] = cmd['stderr'] else: ret['comment'] = cmd['stdout'] ...
Stop Riak .. versionchanged:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' riak.stop
def stop(): ''' Stop Riak .. versionchanged:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' riak.stop ''' ret = {'comment': '', 'success': False} cmd = __execute_cmd('riak', 'stop') if cmd['retcode'] != 0: ret['comment'] = cmd['stderr'] else: r...
Join a Riak cluster .. versionchanged:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' riak.cluster_join <user> <host> username - The riak username to join the cluster hostname - The riak hostname you are connecting to
def cluster_join(username, hostname): ''' Join a Riak cluster .. versionchanged:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' riak.cluster_join <user> <host> username - The riak username to join the cluster hostname - The riak hostname you are connecting to ''' r...
Commit Cluster Changes .. versionchanged:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' riak.cluster_commit
def cluster_commit(): ''' Commit Cluster Changes .. versionchanged:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' riak.cluster_commit ''' ret = {'comment': '', 'success': False} cmd = __execute_cmd('riak-admin', 'cluster commit') if cmd['retcode'] != 0: r...
Get cluster member status .. versionchanged:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' riak.member_status
def member_status(): ''' Get cluster member status .. versionchanged:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' riak.member_status ''' ret = {'membership': {}, 'summary': {'Valid': 0, 'Leaving': 0, 'Exiting': 0, ...
Current node status .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' riak.status
def status(): ''' Current node status .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' riak.status ''' ret = {} cmd = __execute_cmd('riak-admin', 'status') for i in cmd['stdout'].splitlines(): if ':' in i: (name, val) = i.split('...
Enforce the given flags on the given package or ``DEPEND`` atom. .. warning:: In most cases, the affected package(s) need to be rebuilt in order to apply the changes. name The name of the package or its DEPEND atom use A list of ``USE`` flags accept_keywords A ...
def flags(name, use=None, accept_keywords=None, env=None, license=None, properties=None, unmask=False, mask=False): ''' Enforce the given flags on the given package or ``DEPEND`` atom. .. warning:: In most cases, the affected pa...
Add a user to htpasswd file using the htpasswd command. If the htpasswd file does not exist, it will be created. pwfile Path to htpasswd file user User name password User password opts Valid options that can be passed are: - `n` Don't update file; di...
def useradd(pwfile, user, password, opts='', runas=None): ''' Add a user to htpasswd file using the htpasswd command. If the htpasswd file does not exist, it will be created. pwfile Path to htpasswd file user User name password User password opts Valid opt...
Delete a user from the specified htpasswd file. pwfile Path to htpasswd file user User name runas The system user to run htpasswd command with all_results Return stdout, stderr, and retcode, not just stdout CLI Examples: .. code-block:: bash salt '*...
def userdel(pwfile, user, runas=None, all_results=False): ''' Delete a user from the specified htpasswd file. pwfile Path to htpasswd file user User name runas The system user to run htpasswd command with all_results Return stdout, stderr, and retcode, not jus...
Return True if the htpasswd file exists, the user has an entry, and their password matches. pwfile Fully qualified path to htpasswd file user User name password User password opts Valid options that can be passed are: - `m` Force MD5 encryption of th...
def verify(pwfile, user, password, opts='', runas=None): ''' Return True if the htpasswd file exists, the user has an entry, and their password matches. pwfile Fully qualified path to htpasswd file user User name password User password opts Valid options t...
Is the passed user a member of the Administrators group Args: name (str): The name to check Returns: bool: True if user is a member of the Administrators group, False otherwise
def is_admin(name): ''' Is the passed user a member of the Administrators group Args: name (str): The name to check Returns: bool: True if user is a member of the Administrators group, False otherwise ''' groups = get_user_groups(name, True) for group in groups: ...
Get the groups to which a user belongs Args: name (str): The user name to query sid (bool): True will return a list of SIDs, False will return a list of group names Returns: list: A list of group names or sids
def get_user_groups(name, sid=False): ''' Get the groups to which a user belongs Args: name (str): The user name to query sid (bool): True will return a list of SIDs, False will return a list of group names Returns: list: A list of group names or sids ''' if nam...
This is a tool for getting a sid from a name. The name can be any object. Usually a user or a group Args: name (str): The name of the user or group for which to get the sid Returns: str: The corresponding SID
def get_sid_from_name(name): ''' This is a tool for getting a sid from a name. The name can be any object. Usually a user or a group Args: name (str): The name of the user or group for which to get the sid Returns: str: The corresponding SID ''' # If None is passed, use the...
Gets the user executing the process Args: with_domain (bool): ``True`` will prepend the user name with the machine name or domain separated by a backslash Returns: str: The user name
def get_current_user(with_domain=True): ''' Gets the user executing the process Args: with_domain (bool): ``True`` will prepend the user name with the machine name or domain separated by a backslash Returns: str: The user name ''' try: user_name...
r''' Gets the SAM name for a user. It basically prefixes a username without a backslash with the computer name. If the user does not exist, a SAM compatible name will be returned using the local hostname as the domain. i.e. salt.utils.get_same_name('Administrator') would return 'DOMAIN.COM\Administrato...
def get_sam_name(username): r''' Gets the SAM name for a user. It basically prefixes a username without a backslash with the computer name. If the user does not exist, a SAM compatible name will be returned using the local hostname as the domain. i.e. salt.utils.get_same_name('Administrator') would...
Escape the argument for the cmd.exe shell. See http://blogs.msdn.com/b/twistylittlepassagesallalike/archive/2011/04/23/everyone-quotes-arguments-the-wrong-way.aspx First we escape the quote chars to produce a argument suitable for CommandLineToArgvW. We don't need to do this for simple arguments. Args...
def escape_argument(arg, escape=True): ''' Escape the argument for the cmd.exe shell. See http://blogs.msdn.com/b/twistylittlepassagesallalike/archive/2011/04/23/everyone-quotes-arguments-the-wrong-way.aspx First we escape the quote chars to produce a argument suitable for CommandLineToArgvW. We do...
Escape an argument string to be suitable to be passed to cmd.exe on Windows This method takes an argument that is expected to already be properly escaped for the receiving program to be properly parsed. This argument will be further escaped to pass the interpolation performed by cmd.exe unchanged. ...
def escape_for_cmd_exe(arg): ''' Escape an argument string to be suitable to be passed to cmd.exe on Windows This method takes an argument that is expected to already be properly escaped for the receiving program to be properly parsed. This argument will be further escaped to pass the interpola...
Send a WM_SETTINGCHANGE Broadcast to all Windows Args: message (str): A string value representing the portion of the system that has been updated and needs to be refreshed. Default is ``Environment``. These are some common values: - "Environment" : to effec...
def broadcast_setting_change(message='Environment'): ''' Send a WM_SETTINGCHANGE Broadcast to all Windows Args: message (str): A string value representing the portion of the system that has been updated and needs to be refreshed. Default is ``Environment``. These ...
Converts a GUID to a compressed guid (SQUID) Each Guid has 5 parts separated by '-'. For the first three each one will be totally reversed, and for the remaining two each one will be reversed by every other character. Then the final compressed Guid will be constructed by concatenating all the reverse...
def guid_to_squid(guid): ''' Converts a GUID to a compressed guid (SQUID) Each Guid has 5 parts separated by '-'. For the first three each one will be totally reversed, and for the remaining two each one will be reversed by every other character. Then the final compressed Guid will be constructed...
Converts a compressed GUID (SQUID) back into a GUID Args: squid (str): A valid compressed GUID Returns: str: A valid GUID
def squid_to_guid(squid): ''' Converts a compressed GUID (SQUID) back into a GUID Args: squid (str): A valid compressed GUID Returns: str: A valid GUID ''' squid_pattern = re.compile(r'^(\w{8})(\w{4})(\w{4})(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)$') squid_match = ...
Gathers the data from the specified minions' mine, pass in the target, function to look up and the target type CLI Example: .. code-block:: bash salt-run mine.get '*' network.interfaces
def get(tgt, fun, tgt_type='glob'): ''' Gathers the data from the specified minions' mine, pass in the target, function to look up and the target type CLI Example: .. code-block:: bash salt-run mine.get '*' network.interfaces ''' ret = salt.utils.minions.mine_get(tgt, fun, tgt_typ...
.. versionadded:: 2017.7.0 Update the mine data on a certain group of minions. tgt Which minions to target for the execution. tgt_type: ``glob`` The type of ``tgt``. clear: ``False`` Boolean flag specifying whether updating will clear the existing mines, or will updat...
def update(tgt, tgt_type='glob', clear=False, mine_functions=None): ''' .. versionadded:: 2017.7.0 Update the mine data on a certain group of minions. tgt Which minions to target for the execution. tgt_type: ``glob`` The type of ``tgt``. clear...
Send exec and config commands to the NX-OS device over NX-API. commands The exec or config commands to be sent. method: ``cli_show_ascii``: Return raw test or unstructured output. ``cli_show``: Return structured output. ``cli_conf``: Send configuration commands to the device. ...
def nxapi_request(commands, method='cli_show', **kwargs): ''' Send exec and config commands to the NX-OS device over NX-API. commands The exec or config commands to be sent. method: ``cli_show_ascii``: Return raw test or unstructured output. ...
Helper method to return parsed system_info from the 'show version' command.
def system_info(data): ''' Helper method to return parsed system_info from the 'show version' command. ''' if not data: return {} info = { 'software': _parse_software(data), 'hardware': _parse_hardware(data), 'plugins': _parse_plugins(data), } return {'nxo...
Set connection arguments for remote or local connection.
def _prepare_conn_args(self, kwargs): ''' Set connection arguments for remote or local connection. ''' kwargs['connect_over_uds'] = True kwargs['timeout'] = kwargs.get('timeout', 60) kwargs['cookie'] = kwargs.get('cookie', 'admin') if self._use_remote_connection(k...