INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Execute a single state function with the named kwargs, returns False if insufficient data is sent to the command By default, the values of the kwargs will be parsed as YAML. So, you can specify lists values, or lists of single entry key-value maps, as you would in a YAML salt file. Alternatively, JSON ...
def single(fun, name, test=None, queue=False, **kwargs): ''' Execute a single state function with the named kwargs, returns False if insufficient data is sent to the command By default, the values of the kwargs will be parsed as YAML. So, you can specify lists values, or lists of single entry key-v...
Clear out cached state files, forcing even cache runs to refresh the cache on the next state execution. Remember that the state cache is completely disabled by default, this execution only applies if cache=True is used in states CLI Example: .. code-block:: bash salt '*' state.clear_cach...
def clear_cache(): ''' Clear out cached state files, forcing even cache runs to refresh the cache on the next state execution. Remember that the state cache is completely disabled by default, this execution only applies if cache=True is used in states CLI Example: .. code-block:: bash ...
Execute a packaged state run, the packaged state run will exist in a tarball available locally. This packaged state can be generated using salt-ssh. CLI Example: .. code-block:: bash salt '*' state.pkg /tmp/salt_state.tgz 760a9353810e36f6d81416366fc426dc md5
def pkg(pkg_path, pkg_sum, hash_type, test=None, **kwargs): ''' Execute a packaged state run, the packaged state run will exist in a tarball available locally. This packaged state can be generated using salt-ssh. CLI Example: .. code-block:: bash salt '...
Disable state runs. CLI Example: .. code-block:: bash salt '*' state.disable highstate salt '*' state.disable highstate,test.succeed_without_changes .. note:: To disable a state file from running provide the same name that would be passed in a state.sls call. sa...
def disable(states): ''' Disable state runs. CLI Example: .. code-block:: bash salt '*' state.disable highstate salt '*' state.disable highstate,test.succeed_without_changes .. note:: To disable a state file from running provide the same name that would be passed...
Enable state function or sls run CLI Example: .. code-block:: bash salt '*' state.enable highstate salt '*' state.enable test.succeed_without_changes .. note:: To enable a state file from running provide the same name that would be passed in a state.sls call. sa...
def enable(states): ''' Enable state function or sls run CLI Example: .. code-block:: bash salt '*' state.enable highstate salt '*' state.enable test.succeed_without_changes .. note:: To enable a state file from running provide the same name that would be passed ...
Return messages for disabled states that match state functions in funs.
def _disabled(funs): ''' Return messages for disabled states that match state functions in funs. ''' ret = [] _disabled = __salt__['grains.get']('state_runs_disabled') for state in funs: for _state in _disabled: if '.*' in _state: target_state = _state.spl...
r''' Watch Salt's event bus and block until the given tag is matched .. versionadded:: 2016.3.0 .. versionchanged:: 2019.2.0 ``tagmatch`` can now be either a glob or regular expression. This is useful for utilizing Salt's event bus from shell scripts or for taking simple actions directly f...
def event(tagmatch='*', count=-1, quiet=False, sock_dir=None, pretty=False, node='minion'): r''' Watch Salt's event bus and block until the given tag is matched .. versionadded:: 2016.3.0 .. versionchanged:: 2019.2.0 ``tagmatch`` can now be eith...
Ensure that a grain is set name The grain name delimiter A delimiter different from the default can be provided. Check whether a grain exists. Does not attempt to check or set the value.
def exists(name, delimiter=DEFAULT_TARGET_DELIM): ''' Ensure that a grain is set name The grain name delimiter A delimiter different from the default can be provided. Check whether a grain exists. Does not attempt to check or set the value. ''' name = re.sub(delimiter, DEF...
Ensure that a grain is set .. versionchanged:: v2015.8.2 name The grain name value The value to set on the grain force If force is True, the existing grain will be overwritten regardless of its existing or provided value type. Defaults to False .. versionadde...
def present(name, value, delimiter=DEFAULT_TARGET_DELIM, force=False): ''' Ensure that a grain is set .. versionchanged:: v2015.8.2 name The grain name value The value to set on the grain force If force is True, the existing grain will be overwritten regardles...
.. versionadded:: 2014.1.0 Ensure the value is present in the list-type grain. Note: If the grain that is provided in ``name`` is not present on the system, this new grain will be created with the corresponding provided value. name The grain name. value The value is present in the...
def list_present(name, value, delimiter=DEFAULT_TARGET_DELIM): ''' .. versionadded:: 2014.1.0 Ensure the value is present in the list-type grain. Note: If the grain that is provided in ``name`` is not present on the system, this new grain will be created with the corresponding provided value. ...
Delete a value from a grain formed as a list. .. versionadded:: 2014.1.0 name The grain name. value The value to delete from the grain list. delimiter A delimiter different from the default ``:`` can be provided. .. versionadded:: v2015.8.2 The grain should be `l...
def list_absent(name, value, delimiter=DEFAULT_TARGET_DELIM): ''' Delete a value from a grain formed as a list. .. versionadded:: 2014.1.0 name The grain name. value The value to delete from the grain list. delimiter A delimiter different from the default ``:`` can be ...
.. versionadded:: 2014.7.0 Delete a grain from the grains config file name The grain name destructive If destructive is True, delete the entire grain. If destructive is False, set the grain's value to None. Defaults to False. force If force is True, the existing grain...
def absent(name, destructive=False, delimiter=DEFAULT_TARGET_DELIM, force=False): ''' .. versionadded:: 2014.7.0 Delete a grain from the grains config file name The grain name destructive If destructive is True, delete the entire grain. If ...
.. versionadded:: 2014.7.0 Append a value to a list in the grains config file. The grain that is being appended to (name) must exist before the new value can be added. name The grain name value The value to append convert If convert is True, convert non-list contents into...
def append(name, value, convert=False, delimiter=DEFAULT_TARGET_DELIM): ''' .. versionadded:: 2014.7.0 Append a value to a list in the grains config file. The grain that is being appended to (name) must exist before the new value can be added. name The grain name value ...
Clear variables stored in __context__. Run this function when a new version of chocolatey is installed.
def _clear_context(context): ''' Clear variables stored in __context__. Run this function when a new version of chocolatey is installed. ''' for var in (x for x in __context__ if x.startswith('chocolatey.')): context.pop(var)
Returns ['--yes'] if on v0.9.9.0 or later, otherwise returns an empty list
def _yes(context): ''' Returns ['--yes'] if on v0.9.9.0 or later, otherwise returns an empty list ''' if 'chocolatey._yes' in __context__: return context['chocolatey._yes'] if _LooseVersion(chocolatey_version()) >= _LooseVersion('0.9.9'): answer = ['--yes'] else: answer =...
Returns ['--no-progress'] if on v0.10.4 or later, otherwise returns an empty list
def _no_progress(context): ''' Returns ['--no-progress'] if on v0.10.4 or later, otherwise returns an empty list ''' if 'chocolatey._no_progress' in __context__: return context['chocolatey._no_progress'] if _LooseVersion(chocolatey_version()) >= _LooseVersion('0.10.4'): answer = ...
Returns the full path to chocolatey.bat on the host.
def _find_chocolatey(context, salt): ''' Returns the full path to chocolatey.bat on the host. ''' if 'chocolatey._path' in context: return context['chocolatey._path'] choc_defaults = ['C:\\Chocolatey\\bin\\chocolatey.bat', 'C:\\ProgramData\\Chocolatey\\bin\\chocolatey.ex...
Returns the version of Chocolatey installed on the minion. CLI Example: .. code-block:: bash salt '*' chocolatey.chocolatey_version
def chocolatey_version(): ''' Returns the version of Chocolatey installed on the minion. CLI Example: .. code-block:: bash salt '*' chocolatey.chocolatey_version ''' if 'chocolatey._version' in __context__: return __context__['chocolatey._version'] cmd = [_find_chocolatey...
Download and install the latest version of the Chocolatey package manager via the official bootstrap. Chocolatey requires Windows PowerShell and the .NET v4.0 runtime. Depending on the host's version of Windows, chocolatey.bootstrap will attempt to ensure these prerequisites are met by downloading and ...
def bootstrap(force=False): ''' Download and install the latest version of the Chocolatey package manager via the official bootstrap. Chocolatey requires Windows PowerShell and the .NET v4.0 runtime. Depending on the host's version of Windows, chocolatey.bootstrap will attempt to ensure these p...
Instructs Chocolatey to pull a vague package list from the repository. Args: narrow (str): Term used to narrow down results. Searches against name/description/tag. Default is None. all_versions (bool): Display all available package versions in results. Default ...
def list_(narrow=None, all_versions=False, pre_versions=False, source=None, local_only=False, exact=False): ''' Instructs Chocolatey to pull a vague package list from the repository. Args: narrow (str): Term used to narrow down results....
Instructs Chocolatey to pull a full package list from the Windows Features list, via the Deployment Image Servicing and Management tool. Returns: str: List of Windows Features CLI Example: .. code-block:: bash salt '*' chocolatey.list_windowsfeatures
def list_windowsfeatures(): ''' Instructs Chocolatey to pull a full package list from the Windows Features list, via the Deployment Image Servicing and Management tool. Returns: str: List of Windows Features CLI Example: .. code-block:: bash salt '*' chocolatey.list_windowsfe...
Instructs Chocolatey to install a package via Cygwin. name The name of the package to be installed. Only accepts a single argument. install_args A list of install arguments you want to pass to the installation process i.e product key or feature list override_args Set to tr...
def install_cygwin(name, install_args=None, override_args=False): ''' Instructs Chocolatey to install a package via Cygwin. name The name of the package to be installed. Only accepts a single argument. install_args A list of install arguments you want to pass to the installation proces...
Instructs Chocolatey to install a package via Ruby's Gems. name The name of the package to be installed. Only accepts a single argument. version Install a specific version of the package. Defaults to latest version available. install_args A list of install arguments you wa...
def install_gem(name, version=None, install_args=None, override_args=False): ''' Instructs Chocolatey to install a package via Ruby's Gems. name The name of the package to be installed. Only accepts a single argument. version Install a specific version of the package. Defaults to lates...
Instructs Chocolatey to install a package if it doesn't already exist. .. versionchanged:: 2014.7.0 If the minion has Chocolatey >= 0.9.8.24 installed, this function calls :mod:`chocolatey.install <salt.modules.chocolatey.install>` instead, as ``installmissing`` is deprecated as of that ver...
def install_missing(name, version=None, source=None): ''' Instructs Chocolatey to install a package if it doesn't already exist. .. versionchanged:: 2014.7.0 If the minion has Chocolatey >= 0.9.8.24 installed, this function calls :mod:`chocolatey.install <salt.modules.chocolatey.install>` i...
Instructs Chocolatey to install a package via Python's easy_install. name The name of the package to be installed. Only accepts a single argument. version Install a specific version of the package. Defaults to latest version available. install_args A list of install argume...
def install_python(name, version=None, install_args=None, override_args=False): ''' Instructs Chocolatey to install a package via Python's easy_install. name The name of the package to be installed. Only accepts a single argument. version Install a specific version of the package. Defa...
Instructs Chocolatey to install a package via the Microsoft Web PI service. name The name of the package to be installed. Only accepts a single argument. install_args A list of install arguments you want to pass to the installation process i.e product key or feature list override_...
def install_webpi(name, install_args=None, override_args=False): ''' Instructs Chocolatey to install a package via the Microsoft Web PI service. name The name of the package to be installed. Only accepts a single argument. install_args A list of install arguments you want to pass to th...
Instructs Chocolatey to uninstall a package. name The name of the package to be uninstalled. Only accepts a single argument. version Uninstalls a specific version of the package. Defaults to latest version installed. uninstall_args A list of uninstall arguments you...
def uninstall(name, version=None, uninstall_args=None, override_args=False): ''' Instructs Chocolatey to uninstall a package. name The name of the package to be uninstalled. Only accepts a single argument. version Uninstalls a specific version of the package. Defaults to latest...
.. versionadded:: 2016.3.4 Instructs Chocolatey to upgrade packages on the system. (update is being deprecated). This command will install the package if not installed. Args: name (str): The name of the package to update, or "all" to update everything installed on the syst...
def upgrade(name, version=None, source=None, force=False, pre_versions=False, install_args=None, override_args=False, force_x86=False, package_args=None): ''' .. versionadded:: 2016.3.4 Instructs Chocolatey to u...
Instructs Chocolatey to update packages on the system. name The name of the package to update, or "all" to update everything installed on the system. source Chocolatey repository (directory, share or remote URL feed) the package comes from. Defaults to the official Chocolatey f...
def update(name, source=None, pre_versions=False): ''' Instructs Chocolatey to update packages on the system. name The name of the package to update, or "all" to update everything installed on the system. source Chocolatey repository (directory, share or remote URL feed) the pa...
Instructs Chocolatey to add a source. name The name of the source to be added as a chocolatey repository. source Location of the source you want to work with. username Provide username for chocolatey sources that need authentication credentials. password Provi...
def add_source(name, source_location, username=None, password=None): ''' Instructs Chocolatey to add a source. name The name of the source to be added as a chocolatey repository. source Location of the source you want to work with. username Provide username for chocolatey ...
Instructs Chocolatey to check an installed package version, and optionally compare it to one available from a remote feed. Args: name (str): The name of the package to check. Required. check_remote (bool): Get the version number of the latest package from the remote fe...
def version(name, check_remote=False, source=None, pre_versions=False): ''' Instructs Chocolatey to check an installed package version, and optionally compare it to one available from a remote feed. Args: name (str): The name of the package to check. Required. check_remote...
Instructs Chocolatey to change the state of a source. name Name of the repository to affect. state State in which you want the chocolatey repository.
def _change_source_state(name, state): ''' Instructs Chocolatey to change the state of a source. name Name of the repository to affect. state State in which you want the chocolatey repository. ''' choc_path = _find_chocolatey(__context__, __salt__) cmd = [choc_path, 'sourc...
Add the given overlay from the cached remote list to your locally installed overlays. Specify 'ALL' to add all overlays from the remote list. Return a list of the new overlay(s) added: CLI Example: .. code-block:: bash salt '*' layman.add <overlay name>
def add(overlay): ''' Add the given overlay from the cached remote list to your locally installed overlays. Specify 'ALL' to add all overlays from the remote list. Return a list of the new overlay(s) added: CLI Example: .. code-block:: bash salt '*' layman.add <overlay name> ...
Remove the given overlay from the your locally installed overlays. Specify 'ALL' to remove all overlays. Return a list of the overlays(s) that were removed: CLI Example: .. code-block:: bash salt '*' layman.delete <overlay name>
def delete(overlay): ''' Remove the given overlay from the your locally installed overlays. Specify 'ALL' to remove all overlays. Return a list of the overlays(s) that were removed: CLI Example: .. code-block:: bash salt '*' layman.delete <overlay name> ''' ret = list() o...
List the locally installed overlays. Return a list of installed overlays: CLI Example: .. code-block:: bash salt '*' layman.list_local
def list_local(): ''' List the locally installed overlays. Return a list of installed overlays: CLI Example: .. code-block:: bash salt '*' layman.list_local ''' cmd = 'layman --quietness=1 --list-local --nocolor' out = __salt__['cmd.run'](cmd, python_shell=False).split('\n') ...
Prepare the connection to the Django authentication framework
def __django_auth_setup(): ''' Prepare the connection to the Django authentication framework ''' if django.VERSION >= (1, 7): django.setup() global DJANGO_AUTH_CLASS if DJANGO_AUTH_CLASS is not None: return # Versions 1.7 and later of Django don't pull models until # t...
Simple Django auth
def auth(username, password): ''' Simple Django auth ''' django_auth_path = __opts__['django_auth_path'] if django_auth_path not in sys.path: sys.path.append(django_auth_path) os.environ.setdefault('DJANGO_SETTINGS_MODULE', __opts__['django_auth_settings']) __django_auth_setup() ...
Takes the data passed to a top file environment and determines if the data matches this minion
def confirm_top(match, data, nodegroups=None): ''' Takes the data passed to a top file environment and determines if the data matches this minion ''' matcher = 'compound' if not data: log.error('Received bad data when setting the match from the top ' 'file') ret...
List installed features. Supported on Windows Server 2008 and Windows 8 and newer. Returns: dict: A dictionary of installed features CLI Example: .. code-block:: bash salt '*' win_servermanager.list_installed
def list_installed(): ''' List installed features. Supported on Windows Server 2008 and Windows 8 and newer. Returns: dict: A dictionary of installed features CLI Example: .. code-block:: bash salt '*' win_servermanager.list_installed ''' cmd = 'Get-WindowsFeature ' \...
r''' Install a feature .. note:: Some features require reboot after un/installation, if so until the server is restarted other features can not be installed! .. note:: Some features take a long time to complete un/installation, set -t with a long timeout Args: ...
def install(feature, recurse=False, restart=False, source=None, exclude=None): r''' Install a feature .. note:: Some features require reboot after un/installation, if so until the server is restarted other features can not be installed! .. note:: Some features take a long time ...
r''' Remove an installed feature .. note:: Some features require a reboot after installation/uninstallation. If one of these features are modified, then other features cannot be installed until the server is restarted. Additionally, some features take a while to complete install...
def remove(feature, remove_payload=False, restart=False): r''' Remove an installed feature .. note:: Some features require a reboot after installation/uninstallation. If one of these features are modified, then other features cannot be installed until the server is restarted. Additi...
List networks on a wireless interface CLI Examples: salt minion iwtools.scan wlp3s0 salt minion iwtools.scan wlp3s0 list
def scan(iface, style=None): ''' List networks on a wireless interface CLI Examples: salt minion iwtools.scan wlp3s0 salt minion iwtools.scan wlp3s0 list ''' if not _valid_iface(iface): raise SaltInvocationError( 'The interface specified is not valid' ) ...
List networks on a wireless interface CLI Example: salt minion iwtools.set_mode wlp3s0 Managed
def set_mode(iface, mode): ''' List networks on a wireless interface CLI Example: salt minion iwtools.set_mode wlp3s0 Managed ''' if not _valid_iface(iface): raise SaltInvocationError( 'The interface specified is not valid' ) valid_modes = ('Managed', 'Ad-H...
List all of the wireless interfaces CLI Example: salt minion iwtools.list_interfaces
def list_interfaces(style=None): ''' List all of the wireless interfaces CLI Example: salt minion iwtools.list_interfaces ''' ret = {} tmp = None iface = None out = __salt__['cmd.run']('iwconfig') for line in out.splitlines(): if not line: continue ...
Validate the beacon configuration
def validate(config): ''' Validate the beacon configuration ''' vcfg_ret = True vcfg_msg = 'Valid beacon configuration' if not isinstance(config, list): vcfg_ret = False vcfg_msg = 'Configuration for vmadm beacon must be a list!' return vcfg_ret, vcfg_msg
Poll vmadm for changes
def beacon(config): ''' Poll vmadm for changes ''' ret = [] # NOTE: lookup current images current_vms = __salt__['vmadm.list']( keyed=True, order='uuid,state,alias,hostname,dns_domain', ) # NOTE: apply configuration if VMADM_STATE['first_run']: log.info('App...
Run a SQL query and return query result as list of tuples, or a list of dictionaries if as_dict was passed, or an empty list if no data is available. CLI Example: .. code-block:: bash salt minion mssql.tsql_query 'SELECT @@version as version' as_dict=True
def tsql_query(query, **kwargs): ''' Run a SQL query and return query result as list of tuples, or a list of dictionaries if as_dict was passed, or an empty list if no data is available. CLI Example: .. code-block:: bash salt minion mssql.tsql_query 'SELECT @@version as version' as_dict=True ...
Creates a new database. Does not update options of existing databases. new_database_options can only be a list of strings CLI Example: .. code-block:: bash salt minion mssql.db_create DB_NAME
def db_create(database, containment='NONE', new_database_options=None, **kwargs): ''' Creates a new database. Does not update options of existing databases. new_database_options can only be a list of strings CLI Example: .. code-block:: bash salt minion mssql.db_create DB_NAME '''...
Drops a specific database from the MS SQL server. It will not drop any of 'master', 'model', 'msdb' or 'tempdb'. CLI Example: .. code-block:: bash salt minion mssql.db_remove database_name='DBNAME'
def db_remove(database_name, **kwargs): ''' Drops a specific database from the MS SQL server. It will not drop any of 'master', 'model', 'msdb' or 'tempdb'. CLI Example: .. code-block:: bash salt minion mssql.db_remove database_name='DBNAME' ''' try: if db_exists(database_...
Checks if a role exists. CLI Example: .. code-block:: bash salt minion mssql.role_exists db_owner
def role_exists(role, **kwargs): ''' Checks if a role exists. CLI Example: .. code-block:: bash salt minion mssql.role_exists db_owner ''' # We should get one, and only one row return len(tsql_query(query='sp_helprole "{0}"'.format(role), as_dict=True, **kwargs)) == 1
Creates a new database role. If no owner is specified, the role will be owned by the user that executes CREATE ROLE, which is the user argument or mssql.user option. grants is list of strings. CLI Example: .. code-block:: bash salt minion mssql.role_create role=product01 owner=sysdba gran...
def role_create(role, owner=None, grants=None, **kwargs): ''' Creates a new database role. If no owner is specified, the role will be owned by the user that executes CREATE ROLE, which is the user argument or mssql.user option. grants is list of strings. CLI Example: .. code-block:: bash ...
Remove a database role. CLI Example: .. code-block:: bash salt minion mssql.role_create role=test_role01
def role_remove(role, **kwargs): ''' Remove a database role. CLI Example: .. code-block:: bash salt minion mssql.role_create role=test_role01 ''' try: conn = _get_connection(**kwargs) conn.autocommit(True) cur = conn.cursor() cur.execute('DROP ROLE {0}'...
Find if a login exists in the MS SQL server. domain, if provided, will be prepended to login CLI Example: .. code-block:: bash salt minion mssql.login_exists 'LOGIN'
def login_exists(login, domain='', **kwargs): ''' Find if a login exists in the MS SQL server. domain, if provided, will be prepended to login CLI Example: .. code-block:: bash salt minion mssql.login_exists 'LOGIN' ''' if domain: login = '{0}\\{1}'.format(domain, login) ...
Creates a new login. Does not update password of existing logins. For Windows authentication, provide ``new_login_domain``. For SQL Server authentication, prvide ``new_login_password``. Since hashed passwords are *varbinary* values, if the ``new_login_password`` is 'int / long', it will be considere...
def login_create(login, new_login_password=None, new_login_domain='', new_login_roles=None, new_login_options=None, **kwargs): ''' Creates a new login. Does not update password of existing logins. For Windows authentication, provide ``new_login_domain``. For SQL Server authentication, prvide ``new_lo...
Removes an login. CLI Example: .. code-block:: bash salt minion mssql.login_remove LOGINNAME
def login_remove(login, **kwargs): ''' Removes an login. CLI Example: .. code-block:: bash salt minion mssql.login_remove LOGINNAME ''' try: conn = _get_connection(**kwargs) conn.autocommit(True) cur = conn.cursor() cur.execute("DROP LOGIN [{0}]".format...
Find if an user exists in a specific database on the MS SQL server. domain, if provided, will be prepended to username CLI Example: .. code-block:: bash salt minion mssql.user_exists 'USERNAME' [database='DBNAME']
def user_exists(username, domain='', database=None, **kwargs): ''' Find if an user exists in a specific database on the MS SQL server. domain, if provided, will be prepended to username CLI Example: .. code-block:: bash salt minion mssql.user_exists 'USERNAME' [database='DBNAME'] ''' ...
Creates a new user. If login is not specified, the user will be created without a login. domain, if provided, will be prepended to username. options can only be a list of strings CLI Example: .. code-block:: bash salt minion mssql.user_create USERNAME database=DBNAME
def user_create(username, login=None, domain='', database=None, roles=None, options=None, **kwargs): ''' Creates a new user. If login is not specified, the user will be created without a login. domain, if provided, will be prepended to username. options can only be a list of strings CLI Example: ...
Removes an user. CLI Example: .. code-block:: bash salt minion mssql.user_remove USERNAME database=DBNAME
def user_remove(username, **kwargs): ''' Removes an user. CLI Example: .. code-block:: bash salt minion mssql.user_remove USERNAME database=DBNAME ''' # 'database' argument is mandatory if 'database' not in kwargs: return False try: conn = _get_connection(**kwa...
Ensure the cloudwatch alarm exists. name Name of the alarm attributes A dict of key/value cloudwatch alarm attributes. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and ke...
def present( name, attributes, region=None, key=None, keyid=None, profile=None): ''' Ensure the cloudwatch alarm exists. name Name of the alarm attributes A dict of key/value cloudwatch alarm attributes. region Region to conn...
DRY code for joining comments together and conditionally adding a period at the end, and adding this comment string to the state return dict.
def _format_comments(ret, comments): ''' DRY code for joining comments together and conditionally adding a period at the end, and adding this comment string to the state return dict. ''' if isinstance(comments, six.string_types): ret['comment'] = comments else: ret['comment'] = '...
Check the diff for signs of incorrect argument handling in previous releases, as discovered here: https://github.com/saltstack/salt/pull/39996#issuecomment-288025200
def _check_diff(changes): ''' Check the diff for signs of incorrect argument handling in previous releases, as discovered here: https://github.com/saltstack/salt/pull/39996#issuecomment-288025200 ''' for conf_dict in changes: if conf_dict == 'Networks': continue for ...
Common logic for parsing the networks
def _parse_networks(networks): ''' Common logic for parsing the networks ''' networks = salt.utils.args.split_input(networks or []) if not networks: networks = {} else: # We don't want to recurse the repack, as the values of the kwargs # being passed when connecting to th...
Resolve the image ID and pull the image if necessary
def _resolve_image(ret, image, client_timeout): ''' Resolve the image ID and pull the image if necessary ''' image_id = __salt__['docker.resolve_image_id'](image) if image_id is False: if not __opts__['test']: # Image not pulled locally, so try pulling it try: ...
Ensure that a container with a specific configuration is present and running name Name of the container image Image to use for the container .. note:: This state will pull the image if it is not present. However, if the image needs to be built from a Docker...
def running(name, image=None, skip_translate=None, ignore_collisions=False, validate_ip_addrs=True, force=False, watch_action='force', start=True, shutdown_timeout=None, client_timeout=salt.utils.docker.CLIENT_TI...
.. versionadded:: 2018.3.0 .. note:: If no tag is specified in the image name, and nothing matching the specified image is pulled on the minion, the ``docker pull`` that retrieves the image will pull *all tags* for the image. A tag of ``latest`` is not implicit for the pull. For thi...
def run(name, image=None, onlyif=None, unless=None, creates=None, bg=False, failhard=True, replace=False, force=False, skip_translate=None, ignore_collisions=False, validate_ip_addrs=True, client_timeout=salt.utils.docker.CL...
Ensure that a container is absent name Name of the container force : False Set to ``True`` to remove the container even if it is running Usage Examples: .. code-block:: yaml mycontainer: docker_container.absent multiple_containers: docker_contain...
def absent(name, force=False): ''' Ensure that a container is absent name Name of the container force : False Set to ``True`` to remove the container even if it is running Usage Examples: .. code-block:: yaml mycontainer: docker_container.absent mu...
Execute the onlyif/unless/creates logic. Returns a result dict if any of the checks fail, otherwise returns True
def mod_run_check(onlyif, unless, creates): ''' Execute the onlyif/unless/creates logic. Returns a result dict if any of the checks fail, otherwise returns True ''' cmd_kwargs = {'use_vt': False, 'bg': False} if onlyif is not None: if isinstance(onlyif, six.string_types): on...
The docker_container watcher, called to invoke the watch command. .. note:: This state exists to support special handling of the ``watch`` :ref:`requisite <requisites>`. It should not be called directly. Parameters for this function should be set by the state being triggered.
def mod_watch(name, sfun=None, **kwargs): ''' The docker_container watcher, called to invoke the watch command. .. note:: This state exists to support special handling of the ``watch`` :ref:`requisite <requisites>`. It should not be called directly. Parameters for this function sho...
Provide a place to hang onto results of --list-[locations|sizes|images] so we don't have to go out to the API and get them every time.
def _cache_provider_details(conn=None): ''' Provide a place to hang onto results of --list-[locations|sizes|images] so we don't have to go out to the API and get them every time. ''' DETAILS['avail_locations'] = {} DETAILS['avail_sizes'] = {} DETAILS['avail_images'] = {} locations = avai...
Return basic data on nodes
def list_nodes(**kwargs): ''' Return basic data on nodes ''' ret = {} nodes = list_nodes_full() for node in nodes: ret[node] = {} for prop in 'id', 'image', 'size', 'state', 'private_ips', 'public_ips': ret[node][prop] = nodes[node][prop] return ret
Return all data on nodes
def list_nodes_full(**kwargs): ''' Return all data on nodes ''' nodes = _query('server/list') ret = {} for node in nodes: name = nodes[node]['label'] ret[name] = nodes[node].copy() ret[name]['id'] = node ret[name]['image'] = nodes[node]['os'] ret[name]['s...
Remove a node from Vultr
def destroy(name): ''' Remove a node from Vultr ''' node = show_instance(name, call='action') params = {'SUBID': node['SUBID']} result = _query('server/destroy', method='POST', decode=False, data=_urlencode(params)) # The return of a destroy call is empty in the case of a success. # Err...
Show the details from the provider concerning an instance
def show_instance(name, call=None): ''' Show the details from the provider concerning an instance ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) nodes = list_nodes_full() # Find under which cloud s...
Helper function to retrieve a Vultr ID
def _lookup_vultrid(which_key, availkey, keyname): ''' Helper function to retrieve a Vultr ID ''' if DETAILS == {}: _cache_provider_details() which_key = six.text_type(which_key) try: return DETAILS[availkey][which_key][keyname] except KeyError: return False
Create a single VM from a data dict
def create(vm_): ''' Create a single VM from a data dict ''' if 'driver' not in vm_: vm_['driver'] = vm_['provider'] private_networking = config.get_cloud_config_value( 'enable_private_network', vm_, __opts__, search_global=False, default=False, ) startup_script = config.ge...
Perform a query directly against the Vultr REST API
def _query(path, method='GET', data=None, params=None, header_dict=None, decode=True): ''' Perform a query directly against the Vultr REST API ''' api_key = config.get_cloud_config_value( 'api_key', get_configured_provider(), __opts__, search_global=False, ) manag...
Grabs external pillar data based on configured function
def ext_pillar(minion_id, pillar, function, **kwargs): ''' Grabs external pillar data based on configured function ''' if function.startswith('_') or function not in globals(): return {} # Call specified function to pull redis data return globals()[function](minion_id, pillar, **kwargs)
Looks for key in redis matching minion_id, returns a structure based on the data type of the redis key. String for string type, dict for hash type and lists for lists, sets and sorted sets. pillar_key Pillar key to return data into
def key_value(minion_id, pillar, # pylint: disable=W0613 pillar_key='redis_pillar'): ''' Looks for key in redis matching minion_id, returns a structure based on the data type of the redis key. String for string type, dict for hash type and lists for lists, sets and sorted se...
Pulls a string from redis and deserializes it from json. Deserialized dictionary data loaded directly into top level if pillar_key is not set. pillar_key Pillar key to return data into
def key_json(minion_id, pillar, # pylint: disable=W0613 pillar_key=None): ''' Pulls a string from redis and deserializes it from json. Deserialized dictionary data loaded directly into top level if pillar_key is not set. pillar_key Pillar key to return data into '...
Sync portage/overlay trees and update the eix database CLI Example: .. code-block:: bash salt '*' eix.sync
def sync(): ''' Sync portage/overlay trees and update the eix database CLI Example: .. code-block:: bash salt '*' eix.sync ''' # Funtoo patches eix to use 'ego sync' if __grains__['os'] == 'Funtoo': cmd = 'eix-sync -q' else: cmd = 'eix-sync -q -C "--ask" -C "n"...
Add the specified group CLI Example: .. code-block:: bash salt '*' group.add foo 3456
def add(name, gid=None, **kwargs): ''' Add the specified group CLI Example: .. code-block:: bash salt '*' group.add foo 3456 ''' kwargs = salt.utils.args.clean_kwargs(**kwargs) if salt.utils.data.is_true(kwargs.pop('system', False)): log.warning('pw_group module does not s...
Add a user in the group. CLI Example: .. code-block:: bash salt '*' group.adduser foo bar Verifies if a valid username 'bar' as a member of an existing group 'foo', if not then adds it.
def adduser(name, username): ''' Add a user in the group. CLI Example: .. code-block:: bash salt '*' group.adduser foo bar Verifies if a valid username 'bar' as a member of an existing group 'foo', if not then adds it. ''' # Note: pw exits with code 65 if group is unknown ...
Remove a user from the group. CLI Example: .. code-block:: bash salt '*' group.deluser foo bar Removes a member user 'bar' from a group 'foo'. If group is not present then returns True.
def deluser(name, username): ''' Remove a user from the group. CLI Example: .. code-block:: bash salt '*' group.deluser foo bar Removes a member user 'bar' from a group 'foo'. If group is not present then returns True. ''' grp_info = __salt__['group.info'](name) if user...
Ensures that a datasource with given properties exist on the jboss instance. If datasource doesn't exist, it is created, otherwise only the properties that are different will be updated. name Datasource property name jboss_config Dict with connection properties (see state description) d...
def datasource_exists(name, jboss_config, datasource_properties, recreate=False, profile=None): ''' Ensures that a datasource with given properties exist on the jboss instance. If datasource doesn't exist, it is created, otherwise only the properties that are different will be updated. name Dat...
Ensures that given JNDI binding are present on the server. If a binding doesn't exist on the server it will be created. If it already exists its value will be changed. jboss_config: Dict with connection properties (see state description) bindings: Dict with bindings to set. profile:...
def bindings_exist(name, jboss_config, bindings, profile=None): ''' Ensures that given JNDI binding are present on the server. If a binding doesn't exist on the server it will be created. If it already exists its value will be changed. jboss_config: Dict with connection properties (see stat...
Ensures that the given application is deployed on server. jboss_config: Dict with connection properties (see state description) salt_source: How to find the artifact to be deployed. target_file: Where to look in the minion's file system for the artifact to be deploye...
def deployed(name, jboss_config, salt_source=None): '''Ensures that the given application is deployed on server. jboss_config: Dict with connection properties (see state description) salt_source: How to find the artifact to be deployed. target_file: Where to look...
Reloads configuration of jboss server. jboss_config: Dict with connection properties (see state description) timeout: Time to wait until jboss is back in running state. Default timeout is 60s. interval: Interval between state checks. Default interval is 5s. Decreasing the interval m...
def reloaded(name, jboss_config, timeout=60, interval=5): ''' Reloads configuration of jboss server. jboss_config: Dict with connection properties (see state description) timeout: Time to wait until jboss is back in running state. Default timeout is 60s. interval: Interval b...
Validates a username based on the guidelines in `useradd(8)`
def valid_username(user): ''' Validates a username based on the guidelines in `useradd(8)` ''' if not isinstance(user, six.string_types): return False if len(user) > 32: return False return VALID_USERNAME.match(user) is not None
This loads our states into the salt __context__
def load_states(): ''' This loads our states into the salt __context__ ''' states = {} # the loader expects to find pillar & grain data __opts__['grains'] = salt.loader.grains(__opts__) __opts__['pillar'] = __pillar__ lazy_utils = salt.loader.utils(__opts__) lazy_funcs = salt.loader...
Send a message to the google chat room specified in the webhook url. .. code-block:: bash salt '*' google_chat.send_message "https://chat.googleapis.com/v1/spaces/example_space/messages?key=example_key" "This is a test message"
def send_message(url, message): ''' Send a message to the google chat room specified in the webhook url. .. code-block:: bash salt '*' google_chat.send_message "https://chat.googleapis.com/v1/spaces/example_space/messages?key=example_key" "This is a test message" ''' headers = {'Content-Ty...
Raise an exception with __name__ from name, args from args If args is None Otherwise message from message\ If name is empty then use "Exception"
def raise_error(name=None, args=None, message=''): ''' Raise an exception with __name__ from name, args from args If args is None Otherwise message from message\ If name is empty then use "Exception" ''' name = name or 'Exception' if hasattr(salt.exceptions, name): ex = getattr(salt....
Fire raw exception across the event bus
def fire_exception(exc, opts, job=None, node='minion'): ''' Fire raw exception across the event bus ''' if job is None: job = {} event = salt.utils.event.SaltEvent(node, opts=opts, listen=False) event.fire_event(pack_exception(exc), '_salt_error')
Accepts a message pack string or a file object, renders said data back to a python dict. .. note: This renderer is NOT intended for use in creating sls files by hand, but exists to allow for data backends to serialize the highdata structure in an easily transportable way. This is to all...
def render(msgpack_data, saltenv='base', sls='', **kws): ''' Accepts a message pack string or a file object, renders said data back to a python dict. .. note: This renderer is NOT intended for use in creating sls files by hand, but exists to allow for data backends to serialize the high...
Clear out the ext pillar caches, used when the master starts
def init_git_pillar(opts): ''' Clear out the ext pillar caches, used when the master starts ''' ret = [] for opts_dict in [x for x in opts.get('ext_pillar', [])]: if 'git' in opts_dict: try: pillar = salt.utils.gitfs.GitPillar( opts, ...
Clean out the old fileserver backends
def clean_fsbackend(opts): ''' Clean out the old fileserver backends ''' # Clear remote fileserver backend caches so they get recreated for backend in ('git', 'hg', 'svn'): if backend in opts['fileserver_backend']: env_cache = os.path.join( opts['cachedir'], ...
Clean expired tokens from the master
def clean_expired_tokens(opts): ''' Clean expired tokens from the master ''' loadauth = salt.auth.LoadAuth(opts) for tok in loadauth.list_tokens(): token_data = loadauth.get_tok(tok) if 'expire' not in token_data or token_data.get('expire', 0) < time.time(): loadauth.rm_t...
Clean out the old jobs from the job cache
def clean_old_jobs(opts): ''' Clean out the old jobs from the job cache ''' # TODO: better way to not require creating the masterminion every time? mminion = salt.minion.MasterMinion( opts, states=False, rend=False, ) # If the maste...
Clean out old tracked jobs running on the master Generally, anything tracking a job should remove the job once the job has finished. However, this will remove any jobs that for some reason were not properly removed when finished or errored.
def clean_proc_dir(opts): ''' Clean out old tracked jobs running on the master Generally, anything tracking a job should remove the job once the job has finished. However, this will remove any jobs that for some reason were not properly removed when finished or errored. ''' serial = sal...
A key needs to be placed in the filesystem with permissions 0400 so clients are required to run as root.
def access_keys(opts): ''' A key needs to be placed in the filesystem with permissions 0400 so clients are required to run as root. ''' # TODO: Need a way to get all available users for systems not supported by pwd module. # For now users pattern matching will not work for publisher_acl. ...
Update the fileserver backends, requires that a salt.fileserver.Fileserver object be passed in
def fileserver_update(fileserver): ''' Update the fileserver backends, requires that a salt.fileserver.Fileserver object be passed in ''' try: if not fileserver.servers: log.error( 'No fileservers loaded, the master will not be able to ' 'serve fil...