INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Destroy a node. CLI Example: .. code-block:: bash salt-cloud --destroy mymachine
def destroy(name, call=None): ''' Destroy a node. CLI Example: .. code-block:: bash salt-cloud --destroy mymachine ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' )...
Start a node. CLI Example: .. code-block:: bash salt-cloud -a start mymachine
def start(name, call=None): ''' Start a node. CLI Example: .. code-block:: bash salt-cloud -a start mymachine ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) data = query(action='ve',...
Send a Telegram message with the data. :param ret: The data to be sent. :return: Boolean if message was sent successfully.
def returner(ret): ''' Send a Telegram message with the data. :param ret: The data to be sent. :return: Boolean if message was sent successfully. ''' _options = _get_options(ret) chat_id = _options.get('chat_id') token = _options.get('token') if not chat_id: log...
Walk though the jid dir and look for jobs
def _walk_through(job_dir): ''' Walk though the jid dir and look for jobs ''' serial = salt.payload.Serial(__opts__) for top in os.listdir(job_dir): t_path = os.path.join(job_dir, top) if not os.path.exists(t_path): continue for final in os.listdir(t_path): ...
Return a job id and prepare the job id directory. This is the function responsible for making sure jids don't collide (unless it is passed a jid). So do what you have to do to make sure that stays the case
def prep_jid(nocache=False, passed_jid=None, recurse_count=0): ''' Return a job id and prepare the job id directory. This is the function responsible for making sure jids don't collide (unless it is passed a jid). So do what you have to do to make sure that stays the case ''' if recurse_cou...
Return data to the local job cache
def returner(load): ''' Return data to the local job cache ''' serial = salt.payload.Serial(__opts__) # if a minion is returning a standalone job, get a jobid if load['jid'] == 'req': load['jid'] = prep_jid(nocache=load.get('nocache', False)) jid_dir = salt.utils.jid.jid_dir(load['...
Save/update the serialized list of minions for a given job
def save_minions(jid, minions, syndic_id=None): ''' Save/update the serialized list of minions for a given job ''' # Ensure we have a list for Python 3 compatability minions = list(minions) log.debug( 'Adding minions for job %s%s: %s', jid, ' from syndic master \'{0}\''....
Return the load data that marks a specified jid
def get_load(jid): ''' Return the load data that marks a specified jid ''' jid_dir = salt.utils.jid.jid_dir(jid, _job_dir(), __opts__['hash_type']) load_fn = os.path.join(jid_dir, LOAD_P) if not os.path.exists(jid_dir) or not os.path.exists(load_fn): return {} serial = salt.payload.S...
Return the information returned when the specified job id was executed
def get_jid(jid): ''' Return the information returned when the specified job id was executed ''' jid_dir = salt.utils.jid.jid_dir(jid, _job_dir(), __opts__['hash_type']) serial = salt.payload.Serial(__opts__) ret = {} # Check to see if the jid is real, if not return the empty dict if no...
Return a dict mapping all job ids to job information
def get_jids(): ''' Return a dict mapping all job ids to job information ''' ret = {} for jid, job, _, _ in _walk_through(_job_dir()): ret[jid] = salt.utils.jid.format_jid_instance(jid, job) if __opts__.get('job_cache_store_endtime'): endtime = get_endtime(jid) ...
Return a list of all jobs information filtered by the given criteria. :param int count: show not more than the count of most recent jobs :param bool filter_find_jobs: filter out 'saltutil.find_job' jobs
def get_jids_filter(count, filter_find_job=True): ''' Return a list of all jobs information filtered by the given criteria. :param int count: show not more than the count of most recent jobs :param bool filter_find_jobs: filter out 'saltutil.find_job' jobs ''' keys = [] ret = [] for jid,...
Clean out the old jobs from the job cache
def clean_old_jobs(): ''' Clean out the old jobs from the job cache ''' if __opts__['keep_jobs'] != 0: jid_root = _job_dir() if not os.path.exists(jid_root): return # Keep track of any empty t_path dirs that need to be removed later dirs_to_remove = set() ...
Update (or store) the end time for a given job Endtime is stored as a plain text string
def update_endtime(jid, time): ''' Update (or store) the end time for a given job Endtime is stored as a plain text string ''' jid_dir = salt.utils.jid.jid_dir(jid, _job_dir(), __opts__['hash_type']) try: if not os.path.exists(jid_dir): os.makedirs(jid_dir) with salt...
Retrieve the stored endtime for a given job Returns False if no endtime is present
def get_endtime(jid): ''' Retrieve the stored endtime for a given job Returns False if no endtime is present ''' jid_dir = salt.utils.jid.jid_dir(jid, _job_dir(), __opts__['hash_type']) etpath = os.path.join(jid_dir, ENDTIME) if not os.path.exists(etpath): return False with salt...
Save the register to msgpack files
def save_reg(data): ''' Save the register to msgpack files ''' reg_dir = _reg_dir() regfile = os.path.join(reg_dir, 'register') try: if not os.path.exists(reg_dir): os.makedirs(reg_dir) except OSError as exc: if exc.errno == errno.EEXIST: pass ...
Load the register from msgpack files
def load_reg(): ''' Load the register from msgpack files ''' reg_dir = _reg_dir() regfile = os.path.join(reg_dir, 'register') try: with salt.utils.files.fopen(regfile, 'r') as fh_: return salt.utils.msgpack.load(fh_) except Exception: log.error('Could not write to...
Merge obj_b into obj_a.
def merge_recursive(obj_a, obj_b, level=False): ''' Merge obj_b into obj_a. ''' return aggregate(obj_a, obj_b, level, map_class=AggregatedMap, sequence_class=AggregatedSequence)
Build the SLSMap
def construct_yaml_omap(self, node): ''' Build the SLSMap ''' sls_map = SLSMap() if not isinstance(node, MappingNode): raise ConstructorError( None, None, 'expected a mapping node, but found {0}'.format(node.id), ...
Build the SLSString.
def construct_sls_str(self, node): ''' Build the SLSString. ''' # Ensure obj is str, not py2 unicode or py3 bytes obj = self.construct_scalar(node) if six.PY2: obj = obj.encode('utf-8') return SLSString(obj)
Verify integers and pass them in correctly is they are declared as octal
def construct_sls_int(self, node): ''' Verify integers and pass them in correctly is they are declared as octal ''' if node.value == '0': pass elif node.value.startswith('0') \ and not node.value.startswith(('0b', '0x')): node.value...
Ensure the DynamoDB table exists. Table throughput can be updated after table creation. Global secondary indexes (GSIs) are managed with some exceptions: - If a GSI deletion is detected, a failure will occur (deletes should be done manually in the AWS console). - If multiple GSIs are added in a...
def present(name=None, table_name=None, region=None, key=None, keyid=None, profile=None, read_capacity_units=None, write_capacity_units=None, alarms=None, alarms_from_pillar="boto_dynamodb_alarms", ha...
Handles global secondary index for the table present state.
def _global_indexes_present(provisioned_indexes, global_indexes, changes_old, changes_new, comments, name, region, key, keyid, profile): '''Handles global secondary index for the table present state.''' ret = {'result': True} if provisioned_indexes: ...
Returns 3 disjoint sets of indexes: existing, to be created, and to be deleted.
def _partition_index_names(provisioned_index_names, index_names): '''Returns 3 disjoint sets of indexes: existing, to be created, and to be deleted.''' existing_index_names = set() new_index_names = set() for name in index_names: if name in provisioned_index_names: existing_index_nam...
Updates ret iff there was a failure or in test mode.
def _add_global_secondary_index(ret, name, index_name, changes_old, changes_new, comments, gsi_config, region, key, keyid, profile): '''Updates ret iff there was a failure or in test mode.''' if __opts__['test']: ret['result'] = None ret['comment'] = 'Dynamo table...
Updates ret iff there was a failure or in test mode.
def _update_global_secondary_indexes(ret, changes_old, changes_new, comments, existing_index_names, provisioned_gsi_config, gsi_config, name, region, key, keyid, profile): '''Updates ret iff there was a failure or in test mode.''' try: ...
helper method for present. ensure that cloudwatch_alarms are set
def _alarms_present(name, alarms, alarms_from_pillar, write_capacity_units, read_capacity_units, region, key, keyid, profile): '''helper method for present. ensure that cloudwatch_alarms are set''' # load data from alarms_from_pillar tmp = copy.deepcopy( __sa...
Datapipeline API is throttling us, as all the pipelines are started at the same time. We would like to uniformly distribute the startTime over a 60 minute window. Return the next future utc datetime where hour == utc_hour minute = A value between 0-59 (depending on table name) second = ...
def _next_datetime_with_utc_hour(table_name, utc_hour): ''' Datapipeline API is throttling us, as all the pipelines are started at the same time. We would like to uniformly distribute the startTime over a 60 minute window. Return the next future utc datetime where hour == utc_hour minut...
Generate winrepo_cachefile based on sls files in the winrepo_dir opts Specify an alternate opts dict. Should not be used unless this function is imported into an execution module. fire_event : True Fire an event on failure. Only supported on the master. CLI Example: .. code-b...
def genrepo(opts=None, fire_event=True): ''' Generate winrepo_cachefile based on sls files in the winrepo_dir opts Specify an alternate opts dict. Should not be used unless this function is imported into an execution module. fire_event : True Fire an event on failure. Only supp...
Checkout git repos containing Windows Software Package Definitions opts Specify an alternate opts dict. Should not be used unless this function is imported into an execution module. clean : False Clean repo cachedirs which are not configured under :conf_master:`winrepo_remotes`...
def update_git_repos(opts=None, clean=False, masterless=False): ''' Checkout git repos containing Windows Software Package Definitions opts Specify an alternate opts dict. Should not be used unless this function is imported into an execution module. clean : False Clean repo cac...
Sync custom modules into the extension_modules directory
def sync(opts, form, saltenv=None, extmod_whitelist=None, extmod_blacklist=None): ''' Sync custom modules into the extension_modules directory ''' if saltenv is None: saltenv = ['base'] if extmod_whitelist is None: extmod_whitelist = opts['extmod_...
Applies a function to each element of a list, returning the resulting list. A separate thread is created for each element in the input list and the passed function is called for each of the elements. When all threads have finished execution a list with the results corresponding to the inputs is returne...
def _parallel_map(func, inputs): ''' Applies a function to each element of a list, returning the resulting list. A separate thread is created for each element in the input list and the passed function is called for each of the elements. When all threads have finished execution a list with the resul...
Invoke a state run on a given target name An arbitrary name used to track the state execution tgt The target specification for the state run. .. versionadded: 2016.11.0 Masterless support: When running on a masterless minion, the ``tgt`` is ignored and will always be ...
def state(name, tgt, ssh=False, tgt_type='glob', ret='', ret_config=None, ret_kwargs=None, highstate=None, sls=None, top=None, saltenv=None, test=None, pillar=None, pillarenv=None, expect_minions=True, ...
Execute a single module function on a remote minion via salt or salt-ssh name The name of the function to run, aka cmd.run or pkg.install tgt The target specification, aka '*' for all minions tgt_type The target type, defaults to ``glob`` arg The list of arguments to ...
def function( name, tgt, ssh=False, tgt_type='glob', ret='', ret_config=None, ret_kwargs=None, expect_minions=False, fail_minions=None, fail_function=None, arg=None, kwarg=None, timeout=None, batch=None, ...
Watch Salt's event bus and block until a condition is met .. versionadded:: 2014.7.0 name An event tag to watch for; supports Reactor-style globbing. id_list A list of event identifiers to watch for -- usually the minion ID. Each time an event tag is matched the event data is inspe...
def wait_for_event( name, id_list, event_id='id', timeout=300, node='master'): ''' Watch Salt's event bus and block until a condition is met .. versionadded:: 2014.7.0 name An event tag to watch for; supports Reactor-style globbing. id_list A...
Execute a runner module on the master .. versionadded:: 2014.7.0 name The name of the function to run kwargs Any keyword arguments to pass to the runner function asynchronous Run the salt command but don't wait for a reply. .. versionadded:: neon .. code-block:...
def runner(name, **kwargs): ''' Execute a runner module on the master .. versionadded:: 2014.7.0 name The name of the function to run kwargs Any keyword arguments to pass to the runner function asynchronous Run the salt command but don't wait for a reply. .. ...
Executes multiple runner modules on the master in parallel. .. versionadded:: 2017.x.0 (Nitrogen) A separate thread is spawned for each runner. This state is intended to be used with the orchestrate runner in place of the ``saltmod.runner`` state when different tasks should be run in parallel. In gene...
def parallel_runners(name, runners, **kwargs): # pylint: disable=unused-argument ''' Executes multiple runner modules on the master in parallel. .. versionadded:: 2017.x.0 (Nitrogen) A separate thread is spawned for each runner. This state is intended to be used with the orchestrate runner in pla...
Execute a wheel module on the master .. versionadded:: 2014.7.0 name The name of the function to run kwargs Any keyword arguments to pass to the wheel function asynchronous Run the salt command but don't wait for a reply. .. versionadded:: neon .. code-block:: ...
def wheel(name, **kwargs): ''' Execute a wheel module on the master .. versionadded:: 2014.7.0 name The name of the function to run kwargs Any keyword arguments to pass to the wheel function asynchronous Run the salt command but don't wait for a reply. .. ver...
List all Slack rooms. :param api_key: The Slack admin api key. :return: The room list. CLI Example: .. code-block:: bash salt '*' slack.list_rooms salt '*' slack.list_rooms api_key=peWcBiMOS9HrZG15peWcBiMOS9HrZG15
def list_rooms(api_key=None): ''' List all Slack rooms. :param api_key: The Slack admin api key. :return: The room list. CLI Example: .. code-block:: bash salt '*' slack.list_rooms salt '*' slack.list_rooms api_key=peWcBiMOS9HrZG15peWcBiMOS9HrZG15 ''' if not api_key:...
Find a room by name and return it. :param name: The room name. :param api_key: The Slack admin api key. :return: The room object. CLI Example: .. code-block:: bash salt '*' slack.find_room name="random" salt '*' slack.find_room name="random" api_key=peWcBiMOS9HrZG15peW...
def find_room(name, api_key=None): ''' Find a room by name and return it. :param name: The room name. :param api_key: The Slack admin api key. :return: The room object. CLI Example: .. code-block:: bash salt '*' slack.find_room name="random" salt '*' slack.find...
Find a user by name and return it. :param name: The user name. :param api_key: The Slack admin api key. :return: The user object. CLI Example: .. code-block:: bash salt '*' slack.find_user name="ThomasHatch" salt '*' slack.find_user name="ThomasHatch" api_k...
def find_user(name, api_key=None): ''' Find a user by name and return it. :param name: The user name. :param api_key: The Slack admin api key. :return: The user object. CLI Example: .. code-block:: bash salt '*' slack.find_user name="ThomasHatch" sa...
Send a message to a Slack channel. :param channel: The channel name, either will work. :param message: The message to send to the Slack channel. :param from_name: Specify who the message is from. :param api_key: The Slack api key, if not specified in the configuration. :param icon: ...
def post_message(channel, message, from_name, api_key=None, icon=None): ''' Send a message to a Slack channel. :param channel: The channel name, either will work. :param message: The message to send to the Slack channel. :p...
Send message to Slack incoming webhook. :param message: The topic of message. :param attachment: The message to send to the Slacke WebHook. :param color: The color of border of left side :param short: An optional flag indicating whether the value is short enough...
def call_hook(message, attachment=None, color='good', short=False, identifier=None, channel=None, username=None, icon_emoji=None): ''' Send message to Slack incoming webhook. :param message: The topic of m...
Add the specified group name Name of the new group gid Use GID for the new group system Create a system account root Directory to chroot into CLI Example: .. code-block:: bash salt '*' group.add foo 3456
def add(name, gid=None, system=False, root=None): ''' Add the specified group name Name of the new group gid Use GID for the new group system Create a system account root Directory to chroot into CLI Example: .. code-block:: bash salt '*' gr...
Remove the named group name Name group to delete root Directory to chroot into CLI Example: .. code-block:: bash salt '*' group.delete foo
def delete(name, root=None): ''' Remove the named group name Name group to delete root Directory to chroot into CLI Example: .. code-block:: bash salt '*' group.delete foo ''' cmd = ['groupdel'] if root is not None: cmd.extend(('-R', root)) ...
Return information about a group name Name of the group root Directory to chroot into CLI Example: .. code-block:: bash salt '*' group.info foo
def info(name, root=None): ''' Return information about a group name Name of the group root Directory to chroot into CLI Example: .. code-block:: bash salt '*' group.info foo ''' if root is not None: getgrnam = functools.partial(_getgrnam, root=root) ...
Return info on all groups refresh Force a refresh of group information root Directory to chroot into CLI Example: .. code-block:: bash salt '*' group.getent
def getent(refresh=False, root=None): ''' Return info on all groups refresh Force a refresh of group information root Directory to chroot into CLI Example: .. code-block:: bash salt '*' group.getent ''' if 'group.getent' in __context__ and not refresh: ...
Change an attribute for a named user
def _chattrib(name, key, value, param, root=None): ''' Change an attribute for a named user ''' pre_info = info(name, root=root) if not pre_info: return False if value == pre_info[key]: return True cmd = ['groupmod'] if root is not None: cmd.extend(('-R', root)...
Add a user in the group. name Name of the group to modify username Username to add to the group root Directory to chroot into CLI Example: .. code-block:: bash salt '*' group.adduser foo bar Verifies if a valid username 'bar' as a member of an existing gro...
def adduser(name, username, root=None): ''' Add a user in the group. name Name of the group to modify username Username to add to the group root Directory to chroot into CLI Example: .. code-block:: bash salt '*' group.adduser foo bar Verifies if a...
Remove a user from the group. name Name of the group to modify username Username to delete from the group root Directory to chroot into CLI Example: .. code-block:: bash salt '*' group.deluser foo bar Removes a member user 'bar' from a group 'foo'. If grou...
def deluser(name, username, root=None): ''' Remove a user from the group. name Name of the group to modify username Username to delete from the group root Directory to chroot into CLI Example: .. code-block:: bash salt '*' group.deluser foo bar Rem...
Replaces members of the group with a provided list. name Name of the group to modify members_list Username list to set into the group root Directory to chroot into CLI Example: salt '*' group.members foo 'user1,user2,user3,...' Replaces a membership list for a l...
def members(name, members_list, root=None): ''' Replaces members of the group with a provided list. name Name of the group to modify members_list Username list to set into the group root Directory to chroot into CLI Example: salt '*' group.members foo 'user1,...
Alternative implementation for getgrnam, that use only /etc/group
def _getgrnam(name, root=None): ''' Alternative implementation for getgrnam, that use only /etc/group ''' root = root or '/' passwd = os.path.join(root, 'etc/group') with salt.utils.files.fopen(passwd) as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) ...
Execute nagios plugin if it's in the directory with salt command specified in run_type
def _execute_cmd(plugin, args='', run_type='cmd.retcode'): ''' Execute nagios plugin if it's in the directory with salt command specified in run_type ''' data = {} all_plugins = list_plugins() if plugin in all_plugins: data = __salt__[run_type]( '{0}{1} {2}'.format(PLUGI...
Run one or more nagios plugins from pillar data and get the result of run_type The pillar have to be in this format: ------ webserver: Ping_google: - check_icmp: 8.8.8.8 - check_icmp: google.com Load: - check_load: -w 0.8 -c 1 APT: - ch...
def _execute_pillar(pillar_name, run_type): ''' Run one or more nagios plugins from pillar data and get the result of run_type The pillar have to be in this format: ------ webserver: Ping_google: - check_icmp: 8.8.8.8 - check_icmp: google.com Load: ...
Run one nagios plugin and return retcode of the execution
def retcode(plugin, args='', key_name=None): ''' Run one nagios plugin and return retcode of the execution ''' data = {} # Remove all the spaces, the key must not have any space if key_name is None: key_name = _format_dict_key(args, plugin) data[key_name] = {} status = _execut...
Run one or more nagios plugins from pillar data and get the result of cmd.retcode The pillar have to be in this format:: ------ webserver: Ping_google: - check_icmp: 8.8.8.8 - check_icmp: google.com Load: - check_load: -w 0.8 -...
def retcode_pillar(pillar_name): ''' Run one or more nagios plugins from pillar data and get the result of cmd.retcode The pillar have to be in this format:: ------ webserver: Ping_google: - check_icmp: 8.8.8.8 - check_icmp: google.com ...
List all the nagios plugins CLI Example: .. code-block:: bash salt '*' nagios.list_plugins
def list_plugins(): ''' List all the nagios plugins CLI Example: .. code-block:: bash salt '*' nagios.list_plugins ''' plugin_list = os.listdir(PLUGINDIR) ret = [] for plugin in plugin_list: # Check if execute bit stat_f = os.path.join(PLUGINDIR, plugin) ...
Make sure that a package is installed. name The name of the package to install cyg_arch : x86_64 The cygwin architecture to install the package into. Current options are x86 and x86_64 mirrors : None List of mirrors to check. None will use a default mirror (kernel....
def installed(name, cyg_arch='x86_64', mirrors=None): ''' Make sure that a package is installed. name The name of the package to install cyg_arch : x86_64 The cygwin architecture to install the package into. Current options are x86 and x86_64 mi...
Make sure that a package is not installed. name The name of the package to uninstall cyg_arch : x86_64 The cygwin architecture to remove the package from. Current options are x86 and x86_64 mirrors : None List of mirrors to check. None will use a default mirror (ke...
def removed(name, cyg_arch='x86_64', mirrors=None): ''' Make sure that a package is not installed. name The name of the package to uninstall cyg_arch : x86_64 The cygwin architecture to remove the package from. Current options are x86 and x86_64 mirrors : None List...
Make sure all packages are up to date. name : None No affect, salt fails poorly without the arg available cyg_arch : x86_64 The cygwin architecture to update. Current options are x86 and x86_64 mirrors : None List of mirrors to check. None will use a default mirror...
def updated(name=None, cyg_arch='x86_64', mirrors=None): ''' Make sure all packages are up to date. name : None No affect, salt fails poorly without the arg available cyg_arch : x86_64 The cygwin architecture to update. Current options are x86 and x86_64 mirrors : None ...
Query the PagerDuty API
def query(method='GET', profile_dict=None, url=None, path='api/v1', action=None, api_key=None, service=None, params=None, data=None, subdomain=None, client_url=None, description=None, opts=None, verify_ssl=True): ''' Query the PagerDuty API ''' user_agent = 'SaltStack {0}'....
Parse varstack data and return the result
def ext_pillar(minion_id, # pylint: disable=W0613 pillar, # pylint: disable=W0613 conf): ''' Parse varstack data and return the result ''' vs = varstack.Varstack(config_filename=conf) return vs.evaluate(__grains__)
List items belonging to an API call. Used for list_services() and list_incidents()
def list_items(action, key, profile_dict=None, api_key=None, opts=None): ''' List items belonging to an API call. Used for list_services() and list_incidents() ''' items = salt.utils.json.loads(query( profile_dict=profile_dict, api_key=api_key, action=action, opts=opt...
Add the specified group CLI Example: .. code-block:: bash salt '*' group.add foo 3456
def add(name, gid=None, system=False, root=None): ''' Add the specified group CLI Example: .. code-block:: bash salt '*' group.add foo 3456 ''' cmd = 'mkgroup ' if system and root is not None: cmd += '-a ' if gid: cmd += 'id={0} '.format(gid) cmd += name ...
Return information about a group CLI Example: .. code-block:: bash salt '*' group.info foo
def info(name): ''' Return information about a group CLI Example: .. code-block:: bash salt '*' group.info foo ''' try: grinfo = grp.getgrnam(name) except KeyError: return {} else: return {'name': grinfo.gr_name, 'passwd': grinfo.gr_pass...
Return info on all groups CLI Example: .. code-block:: bash salt '*' group.getent
def getent(refresh=False): ''' Return info on all groups CLI Example: .. code-block:: bash salt '*' group.getent ''' if 'group.getent' in __context__ and not refresh: return __context__['group.getent'] ret = [] for grinfo in grp.getgrall(): ret.append(info(gri...
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, root=None): ''' 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) ...
Replaces members of the group with a provided list. CLI Example: salt '*' group.members foo 'user1,user2,user3,...' Replaces a membership list for a local group 'foo'. foo:x:1234:user1,user2,user3,...
def members(name, members_list, root=None): ''' Replaces members of the group with a provided list. CLI Example: salt '*' group.members foo 'user1,user2,user3,...' Replaces a membership list for a local group 'foo'. foo:x:1234:user1,user2,user3,... ''' cmd = 'chgrpmem -m = {0}...
Install pyenv systemwide CLI Example: .. code-block:: bash salt '*' pyenv.install
def install(runas=None, path=None): ''' Install pyenv systemwide CLI Example: .. code-block:: bash salt '*' pyenv.install ''' path = path or _pyenv_path(runas) path = os.path.expanduser(path) return _install_pyenv(path, runas)
Updates the current versions of pyenv and python-Build CLI Example: .. code-block:: bash salt '*' pyenv.update
def update(runas=None, path=None): ''' Updates the current versions of pyenv and python-Build CLI Example: .. code-block:: bash salt '*' pyenv.update ''' path = path or _pyenv_path(runas) path = os.path.expanduser(path) return _update_pyenv(path, runas)
Install a python implementation. python The version of python to install, should match one of the versions listed by pyenv.list CLI Example: .. code-block:: bash salt '*' pyenv.install_python 2.0.0-p0
def install_python(python, runas=None): ''' Install a python implementation. python The version of python to install, should match one of the versions listed by pyenv.list CLI Example: .. code-block:: bash salt '*' pyenv.install_python 2.0.0-p0 ''' python = re.sub...
Uninstall a python implementation. python The version of python to uninstall. Should match one of the versions listed by :mod:`pyenv.versions <salt.modules.pyenv.versions>` CLI Example: .. code-block:: bash salt '*' pyenv.uninstall_python 2.0.0-p0
def uninstall_python(python, runas=None): ''' Uninstall a python implementation. python The version of python to uninstall. Should match one of the versions listed by :mod:`pyenv.versions <salt.modules.pyenv.versions>` CLI Example: .. code-block:: bash salt '*' pyenv.unin...
List the installed versions of python. CLI Example: .. code-block:: bash salt '*' pyenv.versions
def versions(runas=None): ''' List the installed versions of python. CLI Example: .. code-block:: bash salt '*' pyenv.versions ''' ret = _pyenv_exec('versions', '--bare', runas=runas) return [] if ret is False else ret.splitlines()
Returns or sets the currently defined default python. python=None The version to set as the default. Should match one of the versions listed by :mod:`pyenv.versions <salt.modules.pyenv.versions>`. Leave blank to return the current default. CLI Example: .. code-block:: bash ...
def default(python=None, runas=None): ''' Returns or sets the currently defined default python. python=None The version to set as the default. Should match one of the versions listed by :mod:`pyenv.versions <salt.modules.pyenv.versions>`. Leave blank to return the current default. ...
Execute a python command with pyenv's shims from the user or the system. CLI Example: .. code-block:: bash salt '*' pyenv.do 'gem list bundler' salt '*' pyenv.do 'gem list bundler' deploy
def do(cmdline=None, runas=None): ''' Execute a python command with pyenv's shims from the user or the system. CLI Example: .. code-block:: bash salt '*' pyenv.do 'gem list bundler' salt '*' pyenv.do 'gem list bundler' deploy ''' path = _pyenv_path(runas) cmd_split = cmdli...
Execute a python command with pyenv's shims using a specific python version. CLI Example: .. code-block:: bash salt '*' pyenv.do_with_python 2.0.0-p0 'gem list bundler' salt '*' pyenv.do_with_python 2.0.0-p0 'gem list bundler' deploy
def do_with_python(python, cmdline, runas=None): ''' Execute a python command with pyenv's shims using a specific python version. CLI Example: .. code-block:: bash salt '*' pyenv.do_with_python 2.0.0-p0 'gem list bundler' salt '*' pyenv.do_with_python 2.0.0-p0 'gem list bundler' deplo...
Ensure RDS instance exists. name Name of the RDS state definition. allocated_storage The amount of storage (in gigabytes) to be initially allocated for the database instance. db_instance_class The compute and memory capacity of the Amazon RDS DB instance. engine ...
def present(name, allocated_storage, db_instance_class, engine, master_username, master_user_password, db_name=None, storage_type=None, db_security_groups=None, vpc_security_group_ids=None, vpc_securi...
Ensure RDS replica exists. .. code-block:: yaml Ensure myrds replica RDS exists: boto_rds.create_replica: - name: myreplica - source: mydb
def replica_present(name, source, db_instance_class=None, availability_zone=None, port=None, auto_minor_version_upgrade=None, iops=None, option_group_name=None, publicly_accessible=None, tags=None, region=None, key=None, keyid=None, ...
Ensure DB subnet group exists. name The name for the DB subnet group. This value is stored as a lowercase string. subnet_ids A list of the EC2 Subnet IDs for the DB subnet group. Either subnet_ids or subnet_names must be provided. subnet_names A list of The EC2 Subnet name...
def subnet_group_present(name, description, subnet_ids=None, subnet_names=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Ensure DB subnet group exists. name The name for the DB subnet group. This value is stored as a lowercas...
Ensure RDS instance is absent. name Name of the RDS instance. skip_final_snapshot Whether a final db snapshot is created before the instance is deleted. If True, no snapshot is created. If False, a snapshot is created before deleting the instance. final_db_snapshot_identif...
def absent(name, skip_final_snapshot=None, final_db_snapshot_identifier=None, tags=None, wait_for_deletion=True, timeout=180, region=None, key=None, keyid=None, profile=None): ''' Ensure RDS instance is absent. name Name of the RDS instance. skip_final_snapshot Wh...
Ensure DB parameter group exists and update parameters. name The name for the parameter group. db_parameter_group_family The DB parameter group family name. A DB parameter group can be associated with one and only one DB parameter group family, and can be applied only to a DB i...
def parameter_present(name, db_parameter_group_family, description, parameters=None, apply_method="pending-reboot", tags=None, region=None, key=None, keyid=None, profile=None): ''' Ensure DB parameter group exists and update parameters. name The name for the parameter group. ...
Convert an interval string like 1w3d6h into the number of seconds, time resolution (1 unit of the smallest specified time unit) and the modifier( '+', '-', or ''). w = week d = day h = hour m = minute s = second
def _parse_interval(value): ''' Convert an interval string like 1w3d6h into the number of seconds, time resolution (1 unit of the smallest specified time unit) and the modifier( '+', '-', or ''). w = week d = day h = hour m = minute s = second ''' match = ...
WRITEME
def find(path, options): ''' WRITEME ''' finder = Finder(options) for path in finder.find(path): yield path
Generate filenames in path that satisfy criteria specified in the constructor. This method is a generator and should be repeatedly called until there are no more results.
def find(self, path): ''' Generate filenames in path that satisfy criteria specified in the constructor. This method is a generator and should be repeatedly called until there are no more results. ''' if self.mindepth < 1: dirpath, name = os.path.split...
List services belonging to this account CLI Example: salt myminion pagerduty.list_services my-pagerduty-account
def list_services(profile=None, api_key=None): ''' List services belonging to this account CLI Example: salt myminion pagerduty.list_services my-pagerduty-account ''' return salt.utils.pagerduty.list_items( 'services', 'name', __salt__['config.option'](profile), ...
Create an event in PagerDuty. Designed for use in states. CLI Example: .. code-block:: yaml salt myminion pagerduty.create_event <service_key> <description> <details> \ profile=my-pagerduty-account The following parameters are required: service_key This key can be found by u...
def create_event(service_key=None, description=None, details=None, incident_key=None, profile=None): ''' Create an event in PagerDuty. Designed for use in states. CLI Example: .. code-block:: yaml salt myminion pagerduty.create_event <service_key> <description> <details> \ ...
Store a certificate to the given store name The certificate to store, this can use local paths or salt:// paths store The store to add the certificate to saltenv The salt environment to use, this is ignored if a local path is specified
def add_store(name, store, saltenv='base'): ''' Store a certificate to the given store name The certificate to store, this can use local paths or salt:// paths store The store to add the certificate to saltenv The salt environment to use, this is ignored if a local...
Execute a function through the master network interface.
def master_call(self, **kwargs): ''' Execute a function through the master network interface. ''' load = kwargs load['cmd'] = self.client channel = salt.transport.client.ReqChannel.factory(self.opts, crypt='clear'...
Execute a runner function synchronously; eauth is respected This function requires that :conf_master:`external_auth` is configured and the user is authorized to execute runner functions: (``@runner``). .. code-block:: python runner.eauth_sync({ 'fun': 'jobs.list_jo...
def cmd_sync(self, low, timeout=None, full_return=False): ''' Execute a runner function synchronously; eauth is respected This function requires that :conf_master:`external_auth` is configured and the user is authorized to execute runner functions: (``@runner``). .. code-block:...
Execute a function .. code-block:: python >>> opts = salt.config.master_config('/etc/salt/master') >>> runner = salt.runner.RunnerClient(opts) >>> runner.cmd('jobs.list_jobs', []) { '20131219215650131543': { 'Arguments': [300]...
def cmd(self, fun, arg=None, pub_data=None, kwarg=None, print_event=True, full_return=False): ''' Execute a function .. code-block:: python >>> opts = salt.config.master_config('/etc/salt/master') >>> runner = salt.runner.RunnerClient(opts) >>> runner.cmd('j...
Helper that allows us to turn off storing jobs for different classes that may incorporate this mixin.
def store_job(self): ''' Helper that allows us to turn off storing jobs for different classes that may incorporate this mixin. ''' try: class_name = self.__class__.__name__.lower() except AttributeError: log.warning( 'Unable to dete...
Execute a function from low data Low data includes: required: - fun: the name of the function to run optional: - arg: a list of args to pass to fun - kwarg: kwargs for fun - __user__: user who is running the command ...
def low(self, fun, low, print_event=True, full_return=False): ''' Execute a function from low data Low data includes: required: - fun: the name of the function to run optional: - arg: a list of args to pass to fun - kwarg: k...
Return a dictionary of functions and the inline documentation for each
def get_docs(self, arg=None): ''' Return a dictionary of functions and the inline documentation for each ''' if arg: if '*' in arg: target_mod = arg _use_fnmatch = True else: target_mod = arg + '.' if not arg.endswit...
Execute the function in a multiprocess and return the event tag to use to watch for the return
def asynchronous(self, fun, low, user='UNKNOWN', pub=None): ''' Execute the function in a multiprocess and return the event tag to use to watch for the return ''' async_pub = pub if pub is not None else self._gen_async_pub() proc = salt.utils.process.SignalHandlingMultip...
Print all of the events with the prefix 'tag'
def print_async_event(self, suffix, event): ''' Print all of the events with the prefix 'tag' ''' if not isinstance(event, dict): return # if we are "quiet", don't print if self.opts.get('quiet', False): return # some suffixes we don't wa...
Generate a JSON file to serve as an index for short-URL lookups
def write_urls_index(app, exc): ''' Generate a JSON file to serve as an index for short-URL lookups ''' inventory = os.path.join(app.builder.outdir, 'objects.inv') objects = sphinx.ext.intersphinx.fetch_inventory(app, DOCS_URL, inventory) with open(os.path.join(app.builder.outdir, 'shorturls.js...
Executes the passed command. Returns True if successful :param str cmd: The command to run :return: True if successful, otherwise False :rtype: bool :raises: Error if command fails or is not supported
def execute_return_success(cmd): ''' Executes the passed command. Returns True if successful :param str cmd: The command to run :return: True if successful, otherwise False :rtype: bool :raises: Error if command fails or is not supported ''' ret = _run_all(cmd) if ret['retcode']...
Executes the passed command. Returns the standard out if successful :param str cmd: The command to run :return: The standard out of the command if successful, otherwise returns an error :rtype: str :raises: Error if command fails or is not supported
def execute_return_result(cmd): ''' Executes the passed command. Returns the standard out if successful :param str cmd: The command to run :return: The standard out of the command if successful, otherwise returns an error :rtype: str :raises: Error if command fails or is not supported ...
Helper function to validate the enabled parameter. Boolean values are converted to "on" and "off". String values are checked to make sure they are either "on" or "off"/"yes" or "no". Integer ``0`` will return "off". All other integers will return "on" :param enabled: Enabled can be boolean True or Fals...
def validate_enabled(enabled): ''' Helper function to validate the enabled parameter. Boolean values are converted to "on" and "off". String values are checked to make sure they are either "on" or "off"/"yes" or "no". Integer ``0`` will return "off". All other integers will return "on" :param e...
Wait up to ``wait`` seconds for a system parameter to be changed before deciding it hasn't changed. :param str value: The value indicating a successful change :param function check_fun: The function whose return is compared with ``value`` :param bool normalize_ret: Whether to normalize the re...
def confirm_updated(value, check_fun, normalize_ret=False, wait=5): ''' Wait up to ``wait`` seconds for a system parameter to be changed before deciding it hasn't changed. :param str value: The value indicating a successful change :param function check_fun: The function whose return is compared wi...
Run a launchctl command and raise an error if it fails Args: additional args are passed to launchctl sub_cmd (str): Sub command supplied to launchctl Kwargs: passed to ``cmd.run_all`` return_stdout (bool): A keyword argument. If true return the stdout of the launchctl command ...
def launchctl(sub_cmd, *args, **kwargs): ''' Run a launchctl command and raise an error if it fails Args: additional args are passed to launchctl sub_cmd (str): Sub command supplied to launchctl Kwargs: passed to ``cmd.run_all`` return_stdout (bool): A keyword argument. If true return ...