text
stringlengths
81
112k
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 pul...
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...
.. 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...
Ensure that a container (or containers) is stopped name Name or ID of the container containers Run this state on more than one container at a time. The following two examples accomplish the same thing: .. code-block:: yaml stopped_containers: docker_...
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...
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 = {'us...
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_watc...
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 e...
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 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][...
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 ca...
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.' ) ...
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...
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, ...
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(), _...
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 ...
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=...
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): ''' Pull...
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 'eg...
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) ...
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::...
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-bl...
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...
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:...
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...
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...
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)...
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.lo...
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...
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 m...
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...
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 = sa...
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( ...
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) < ...
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=...
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 j...
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 syst...
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(...
Check if the specified filename has correct permissions def check_permissions(self, filename): ''' Check if the specified filename has correct permissions ''' if salt.utils.platform.is_windows(): return True # After we've ascertained we're not on windows gro...
Check a keyid for membership in a signing file def check_signing_file(self, keyid, signing_file): ''' Check a keyid for membership in a signing file ''' if not signing_file or not os.path.exists(signing_file): return False if not self.check_permissions(signing_file)...
Check a keyid for membership in a autosign directory. def check_autosign_dir(self, keyid): ''' Check a keyid for membership in a autosign directory. ''' autosign_dir = os.path.join(self.opts['pki_dir'], 'minions_autosign') # cleanup expired files expire_minutes = self.o...
Check for matching grains in the autosign_grains_dir. def check_autosign_grains(self, autosign_grains): ''' Check for matching grains in the autosign_grains_dir. ''' if not autosign_grains or 'autosign_grains_dir' not in self.opts: return False autosign_grains_dir =...
Checks if the specified keyid should automatically be signed. def check_autosign(self, keyid, autosign_grains=None): ''' Checks if the specified keyid should automatically be signed. ''' if self.opts['auto_accept']: return True if self.check_signing_file(keyid, self....
Set the local file objects from the file server interface def __setup_fileserver(self): ''' Set the local file objects from the file server interface ''' fs_ = salt.fileserver.Fileserver(self.opts) self._serve_file = fs_.serve_file self._file_find = fs_._find_file ...
Verify that the passed information authorized a minion to execute def __verify_minion_publish(self, load): ''' Verify that the passed information authorized a minion to execute ''' # Verify that the load is valid if 'peer' not in self.opts: return False if no...
Return the master options to the minion def _master_opts(self, load): ''' Return the master options to the minion ''' mopts = {} file_roots = {} envs = self._file_envs() for saltenv in envs: if saltenv not in file_roots: file_roots[sal...
Return the results from master_tops if configured def _master_tops(self, load, skip_verify=False): ''' Return the results from master_tops if configured ''' if not skip_verify: if 'id' not in load: log.error('Received call for external nodes without an id') ...
Gathers the data from the specified minions' mine def _mine_get(self, load, skip_verify=False): ''' Gathers the data from the specified minions' mine ''' if not skip_verify: if any(key not in load for key in ('id', 'tgt', 'fun')): return {} if isinst...
Return the mine data def _mine(self, load, skip_verify=False): ''' Return the mine data ''' if not skip_verify: if 'id' not in load or 'data' not in load: return False if self.opts.get('minion_data_cache', False) or self.opts.get('enforce_mine_cache',...
Allow the minion to delete a specific function from its own mine def _mine_delete(self, load): ''' Allow the minion to delete a specific function from its own mine ''' if 'id' not in load or 'fun' not in load: return False if self.opts.get('minion_data_cache', False)...
Allow the minion to delete all of its own mine contents def _mine_flush(self, load, skip_verify=False): ''' Allow the minion to delete all of its own mine contents ''' if not skip_verify and 'id' not in load: return False if self.opts.get('minion_data_cache', False) ...
Allows minions to send files to the master, files are sent to the master file cache def _file_recv(self, load): ''' Allows minions to send files to the master, files are sent to the master file cache ''' if any(key not in load for key in ('id', 'path', 'loc')): ...
Return the pillar data for the minion def _pillar(self, load): ''' Return the pillar data for the minion ''' if any(key not in load for key in ('id', 'grains')): return False # pillar = salt.pillar.Pillar( log.debug('Master _pillar using ext: %s', load.get('ex...
Receive an event from the minion and fire it on the master event interface def _minion_event(self, load): ''' Receive an event from the minion and fire it on the master event interface ''' if 'id' not in load: return False if 'events' not in load and ...
Handle the return data sent from the minions def _return(self, load): ''' Handle the return data sent from the minions ''' # Generate EndTime endtime = salt.utils.jid.jid_to_time(salt.utils.jid.gen_jid(self.opts)) # If the return data is invalid, just ignore it i...
Receive a syndic minion return and format it to look like returns from individual minions. def _syndic_return(self, load): ''' Receive a syndic minion return and format it to look like returns from individual minions. ''' # Verify the load if any(key not in load ...
Execute a runner from a minion, return the runner's function data def minion_runner(self, load): ''' Execute a runner from a minion, return the runner's function data ''' if 'peer_run' not in self.opts: return {} if not isinstance(self.opts['peer_run'], dict): ...
Request the return data from a specific jid, only allowed if the requesting minion also initialted the execution. def pub_ret(self, load, skip_verify=False): ''' Request the return data from a specific jid, only allowed if the requesting minion also initialted the execution. '''...
Publish a command initiated from a minion, this method executes minion restrictions so that the minion publication will only work if it is enabled in the config. The configuration on the master allows minions to be matched to salt functions, so the minions can only publish allowed salt f...
Publish a command initiated from a minion, this method executes minion restrictions so that the minion publication will only work if it is enabled in the config. The configuration on the master allows minions to be matched to salt functions, so the minions can only publish allowed salt f...
Allow a minion to request revocation of its own key def revoke_auth(self, load): ''' Allow a minion to request revocation of its own key ''' if 'id' not in load: return False keyapi = salt.key.Key(self.opts) keyapi.delete_key(load['id'], ...
Send a master control function back to the runner system def runner(self, load): ''' Send a master control function back to the runner system ''' # All runner opts pass through eauth auth_type, err_name, key = self._prep_auth_info(load) # Authenticate auth_check...
Send a master control function back to the wheel system def wheel(self, load): ''' Send a master control function back to the wheel system ''' # All wheel ops pass through eauth auth_type, err_name, key = self._prep_auth_info(load) # Authenticate auth_check = se...
Create and return an authentication token, the clear load needs to contain the eauth key and the needed authentication creds. def mk_token(self, load): ''' Create and return an authentication token, the clear load needs to contain the eauth key and the needed authentication creds. ...
This method sends out publications to the minions, it can only be used by the LocalClient. def publish(self, load): ''' This method sends out publications to the minions, it can only be used by the LocalClient. ''' extra = load.get('kwargs', {}) publisher_acl = ...
Listen to slack events and forward them to salt, new version def start(token, control=False, trigger='!', groups=None, groups_pillar_name=None, fire_all=False, tag='salt/engines/slack'): ''' Listen to slack events and forward them to salt, new version...
Get all users from Slack def get_slack_users(self, token): ''' Get all users from Slack ''' ret = salt.utils.slack.query(function='users', api_key=token, opts=__opts__) users = {} if 'message' in ...
Get all channel names from Slack def get_slack_channels(self, token): ''' Get all channel names from Slack ''' ret = salt.utils.slack.query( function='rooms', api_key=token, # These won't be honored until https://github.com/saltstack/salt/pull/41187/...
get info from groups in config, and from the named pillar todo: add specification for the minion to use to recover pillar def get_config_groups(self, groups_conf, groups_pillar_name): ''' get info from groups in config, and from the named pillar todo: add specification for the minion ...
pillar_prefix is the pillar.get syntax for the pillar to be queried. Group name is gotten via the equivalent of using ``salt['pillar.get']('{}:{}'.format(pillar_prefix, group_name))`` in a jinja template. returns a dictionary (unless the pillar is mis-formatted) XXX: instead of ...
This replaces a function in main called 'fire' It fires an event into the salt bus. def fire(self, tag, msg): ''' This replaces a function in main called 'fire' It fires an event into the salt bus. ''' if __opts__.get('__role') == 'master': fire_master = sa...
Break out the permissions into the following: Check whether a user is in any group, including whether a group has the '*' membership :type user: str :param user: The username being checked against :type command: str :param command: The command that is being invoked (e.g. test....
cmdline_str is the string of the command line trigger_string is the trigger string, to be removed def commandline_to_list(self, cmdline_str, trigger_string): ''' cmdline_str is the string of the command line trigger_string is the trigger string, to be removed ''' cmdline...
Returns a tuple of (target, cmdline,) for the response Raises IndexError if a user can't be looked up from all_slack_users Returns (False, False) if the user doesn't have permission These are returned together because the commandline and the targeting interact with the group config (s...
Raises ValueError if a value doesn't work out, and TypeError if this isn't a message type def message_text(self, m_data): ''' Raises ValueError if a value doesn't work out, and TypeError if this isn't a message type ''' if m_data.get('type') != 'message': rai...
slack_token = string trigger_string = string input_valid_users = set input_valid_commands = set When the trigger_string prefixes the message text, yields a dictionary of:: { 'message_data': m_data, 'cmdline': cmdline_list, # this is a...
When we are permitted to run a command on a target, look to see what the default targeting is for that group, and for that specific command (if provided). It's possible for None or False to be the result of either, which means that it's expected that the caller provide a specific target...
Print out YAML using the block mode def format_return_text(self, data, function, **kwargs): # pylint: disable=unused-argument ''' Print out YAML using the block mode ''' # emulate the yaml_out output formatter. It relies on a global __opts__ object which # we can't obviously pa...
cmdline: list returns tuple of: args (list), kwargs (dict) def parse_args_and_kwargs(self, cmdline): ''' cmdline: list returns tuple of: args (list), kwargs (dict) ''' # Parse args and kwargs args = [] kwargs = {} if len(cmdline) > 1: ...
Given a list of job_ids, return a dictionary of those job_ids that have completed and their results. Query the salt event bus via the jobs runner. jobs.list_job will show a job in progress, jobs.lookup_jid will return a job that has completed. returns a dictionary of job id: re...
Pull any pending messages from the message_generator, sending each one to either the event bus, the command_async or both, depending on the values of fire_all and command def run_commands_from_slack_async(self, message_generator, fire_all, tag, control, interval=1): ''' Pull any pending...
:type message_generator: generator of dict :param message_generator: Generates messages from slack that should be run :type fire_all: bool :param fire_all: Whether to also fire messages to the event bus :type tag: str :param tag: The tag to send to use to send to the event bus ...
Return a Pg cursor def _get_serv(ret=None, commit=False): ''' Return a Pg cursor ''' _options = _get_options(ret) try: conn = psycopg2.connect(host=_options.get('host'), user=_options.get('user'), password=_options.get('passwd'...
Return data to a postgres server def returner(ret): ''' Return data to a postgres server ''' try: with _get_serv(ret, commit=True) as cur: sql = '''INSERT INTO salt_returns (fun, jid, return, id, success, full_ret) VALUES (%s, %s, %s, %s, %s, ...
Return a list of all job ids def get_jids(): ''' Return a list of all job ids ''' with _get_serv(ret=None, commit=True) as cur: sql = '''SELECT jid, load FROM jids''' cur.execute(sql) data = cur.fetchall() ret = {} for jid, load in data: ...
Ensures that the host group exists, eventually creates new host group. .. versionadded:: 2016.3.0 :param name: name of the host group :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring) :param _connection_password: Optional - zabbix password (can...
Ensures that the host group does not exist, eventually delete host group. .. versionadded:: 2016.3.0 :param name: name of the host group :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring) :param _connection_password: Optional - zabbix password (...
Encode json values in unicode to match that of the API def _json_to_unicode(data): ''' Encode json values in unicode to match that of the API ''' ret = {} for key, value in data.items(): if not isinstance(value, six.text_type): if isinstance(value, dict): ret[key...
Compare the API results to the current statefile data def _is_updated(old_conf, new_conf): ''' Compare the API results to the current statefile data ''' changed = {} # Dirty json hacking to get parameters in the same format new_conf = _json_to_unicode(salt.utils.json.loads( salt.utils....
Generic function to create or update an element def _do_element_present(name, elem_type, data, server=None): ''' Generic function to create or update an element ''' ret = {'changes': {}, 'update': False, 'create': False, 'error': None} try: elements = __salt__['glassfish.enum_{0}'.format(el...
Generic function to delete an element def _do_element_absent(name, elem_type, data, server=None): ''' Generic function to delete an element ''' ret = {'delete': False, 'error': None} try: elements = __salt__['glassfish.enum_{0}'.format(elem_type)]() except requests.ConnectionError as er...
Ensures that the Connection Factory is present name Name of the connection factory restype Type of the connection factory, can be either ``connection_factory``, ``queue_connection_factory` or ``topic_connection_factory``, defaults to ``connection_factory`` description ...
Ensures the transaction factory is absent. name Name of the connection factory both Delete both the pool and the resource, defaults to ``true`` def connection_factory_absent(name, both=True, server=None): ''' Ensures the transaction factory is absent. name Name of the con...
Ensures that the JMS Destination Resource (queue or topic) is present name The JMS Queue/Topic name physical The Physical destination name restype The JMS Destination resource type, either ``queue`` or ``topic``, defaults is ``queue`` description A description of the ...
Ensures that the JMS Destination doesn't exists name Name of the JMS Destination def destination_absent(name, server=None): ''' Ensures that the JMS Destination doesn't exists name Name of the JMS Destination ''' ret = {'name': name, 'result': None, 'comment': None, 'changes':...
Ensures that the JDBC Datasource exists name Name of the datasource description Description of the datasource enabled Is the datasource enabled? defaults to ``true`` restype Resource type, can be ``datasource``, ``xa_datasource``, ``connection_pool_datasource`...
Ensures the JDBC Datasource doesn't exists name Name of the datasource both Delete both the pool and the resource, defaults to ``true`` def jdbc_datasource_absent(name, both=True, server=None): ''' Ensures the JDBC Datasource doesn't exists name Name of the datasource ...
Ensures that the system properties are present properties The system properties def system_properties_present(server=None, **kwargs): ''' Ensures that the system properties are present properties The system properties ''' ret = {'name': '', 'result': None, 'comment': None, 'ch...
Ensures that the system property doesn't exists name Name of the system property def system_properties_absent(name, server=None): ''' Ensures that the system property doesn't exists name Name of the system property ''' ret = {'name': '', 'result': None, 'comment': None, 'chang...