INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Render a state file and retrieve all of the include states
def render_state(self, sls, saltenv, mods, matches, local=False): ''' Render a state file and retrieve all of the include states ''' errors = [] if not local: state_data = self.client.get_state(sls, saltenv) fn_ = state_data.get('dest', False) else...
Take a state and apply the iorder system
def _handle_iorder(self, state): ''' Take a state and apply the iorder system ''' if self.opts['state_auto_order']: for name in state: for s_dec in state[name]: if not isinstance(s_dec, six.string_types): # PyDSL Ord...
Take the extend dec out of state and apply to the highstate global dec
def _handle_extend(self, state, sls, saltenv, errors): ''' Take the extend dec out of state and apply to the highstate global dec ''' if 'extend' in state: ext = state.pop('extend') if not isinstance(ext, dict): errors.append(('Extension va...
Add sls and saltenv components to the state
def _handle_state_decls(self, state, sls, saltenv, errors): ''' Add sls and saltenv components to the state ''' for name in state: if not isinstance(state[name], dict): if name == '__extend__': continue if name == '__exclude...
Take the exclude dec out of the state and apply it to the highstate global dec
def _handle_exclude(self, state, sls, saltenv, errors): ''' Take the exclude dec out of the state and apply it to the highstate global dec ''' if 'exclude' in state: exc = state.pop('exclude') if not isinstance(exc, list): err = ('Exclude D...
Gather the state files and render them into a single unified salt high data structure.
def render_highstate(self, matches): ''' Gather the state files and render them into a single unified salt high data structure. ''' highstate = self.building_highstate all_errors = [] mods = set() statefiles = [] for saltenv, states in six.iteritem...
Check the pillar for errors, refuse to run the state if there are errors in the pillar and return the pillar errors
def _check_pillar(self, force=False): ''' Check the pillar for errors, refuse to run the state if there are errors in the pillar and return the pillar errors ''' if force: return True if '_errors' in self.state.opts['pillar']: return False ...
Reads over the matches and returns a matches dict with just the ones that are in the whitelist
def matches_whitelist(self, matches, whitelist): ''' Reads over the matches and returns a matches dict with just the ones that are in the whitelist ''' if not whitelist: return matches ret_matches = {} if not isinstance(whitelist, list): wh...
Run the sequence to execute the salt highstate for this minion
def call_highstate(self, exclude=None, cache=None, cache_name='highstate', force=False, whitelist=None, orchestration_jid=None): ''' Run the sequence to execute the salt highstate for this minion ''' # Check that top file exists tag_name = 'no_|-states_|-st...
Return just the highstate or the errors
def compile_highstate(self): ''' Return just the highstate or the errors ''' err = [] top = self.get_top() err += self.verify_tops(top) matches = self.top_matches(top) high, errors = self.render_highstate(matches) err += errors if err: ...
Compile the highstate but don't run it, return the low chunks to see exactly what the highstate will execute
def compile_low_chunks(self): ''' Compile the highstate but don't run it, return the low chunks to see exactly what the highstate will execute ''' top = self.get_top() matches = self.top_matches(top) high, errors = self.render_highstate(matches) # If ther...
Return all used and unused states for the minion based on the top match data
def compile_state_usage(self): ''' Return all used and unused states for the minion based on the top match data ''' err = [] top = self.get_top() err += self.verify_tops(top) if err: return err matches = self.top_matches(top) state_us...
Load the modules into the state
def load_modules(self, data=None, proxy=None): ''' Load the modules into the state ''' log.info('Loading fresh modules for state activity') # Load a modified client interface that looks like the interface used # from the minion, but uses remote execution # ...
Return the state data from the master
def compile_master(self): ''' Return the state data from the master ''' load = {'grains': self.grains, 'opts': self.opts, 'cmd': '_master_state'} try: return self.channel.send(load, tries=3, timeout=72000) except SaltReqTimeoutE...
Output the data in lines, very nice for running commands
def output(data, **kwargs): # pylint: disable=unused-argument ''' Output the data in lines, very nice for running commands ''' ret = '' if hasattr(data, 'keys'): for key in data: value = data[key] # Don't blow up on non-strings try: for li...
Recursively compare two configs, writing any needed changes to the update_config and capturing changes in the changes dict.
def compare_and_update_config(config, update_config, changes, namespace=''): ''' Recursively compare two configs, writing any needed changes to the update_config and capturing changes in the changes dict. ''' if isinstance(config, dict): if not update_config: if config: ...
Manage a memcached key. name The key to manage value The value to set for that key host The memcached server IP address port The memcached server port .. code-block:: yaml foo: memcached.managed: - value: bar
def managed(name, value=None, host=DEFAULT_HOST, port=DEFAULT_PORT, time=DEFAULT_TIME, min_compress_len=DEFAULT_MIN_COMPRESS_LEN): ''' Manage a memcached key. name The key to manage value The value to set for that key hos...
Parse /etc/hosts file. CLI Example: .. code-block:: bash salt '*' dnsutil.parse_hosts
def parse_hosts(hostsfile='/etc/hosts', hosts=None): ''' Parse /etc/hosts file. CLI Example: .. code-block:: bash salt '*' dnsutil.parse_hosts ''' if not hosts: try: with salt.utils.files.fopen(hostsfile, 'r') as fp_: hosts = salt.utils.stringutils....
Append a single line to the /etc/hosts file. CLI Example: .. code-block:: bash salt '*' dnsutil.hosts_append /etc/hosts 127.0.0.1 ad1.yuk.co,ad2.yuk.co
def hosts_append(hostsfile='/etc/hosts', ip_addr=None, entries=None): ''' Append a single line to the /etc/hosts file. CLI Example: .. code-block:: bash salt '*' dnsutil.hosts_append /etc/hosts 127.0.0.1 ad1.yuk.co,ad2.yuk.co ''' host_list = entries.split(',') hosts = parse_hosts(...
Remove a host from the /etc/hosts file. If doing so will leave a line containing only an IP address, then the line will be deleted. This function will leave comments and blank lines intact. CLI Examples: .. code-block:: bash salt '*' dnsutil.hosts_remove /etc/hosts ad1.yuk.co salt '*'...
def hosts_remove(hostsfile='/etc/hosts', entries=None): ''' Remove a host from the /etc/hosts file. If doing so will leave a line containing only an IP address, then the line will be deleted. This function will leave comments and blank lines intact. CLI Examples: .. code-block:: bash ...
Parses a zone file. Can be passed raw zone data on the API level. CLI Example: .. code-block:: bash salt ns1 dnsutil.parse_zone /var/lib/named/example.com.zone
def parse_zone(zonefile=None, zone=None): ''' Parses a zone file. Can be passed raw zone data on the API level. CLI Example: .. code-block:: bash salt ns1 dnsutil.parse_zone /var/lib/named/example.com.zone ''' if zonefile: try: with salt.utils.files.fopen(zonefile,...
Converts a time value to seconds. As per RFC1035 (page 45), max time is 1 week, so anything longer (or unreadable) will be set to one week (604800 seconds).
def _to_seconds(timestr): ''' Converts a time value to seconds. As per RFC1035 (page 45), max time is 1 week, so anything longer (or unreadable) will be set to one week (604800 seconds). ''' timestr = timestr.upper() if 'H' in timestr: seconds = int(timestr.replace('H', '')) * 3600 ...
Return the A record(s) for ``host``. Always returns a list. CLI Example: .. code-block:: bash salt ns1 dnsutil.A www.google.com
def A(host, nameserver=None): ''' Return the A record(s) for ``host``. Always returns a list. CLI Example: .. code-block:: bash salt ns1 dnsutil.A www.google.com ''' if _has_dig(): return __salt__['dig.A'](host, nameserver) elif nameserver is None: # fall back...
Return the AAAA record(s) for ``host``. Always returns a list. .. versionadded:: 2014.7.5 CLI Example: .. code-block:: bash salt ns1 dnsutil.AAAA www.google.com
def AAAA(host, nameserver=None): ''' Return the AAAA record(s) for ``host``. Always returns a list. .. versionadded:: 2014.7.5 CLI Example: .. code-block:: bash salt ns1 dnsutil.AAAA www.google.com ''' if _has_dig(): return __salt__['dig.AAAA'](host, nameserver) ...
Return a list of IPs of the nameservers for ``domain`` If 'resolve' is False, don't resolve names. CLI Example: .. code-block:: bash salt ns1 dnsutil.NS google.com
def NS(domain, resolve=True, nameserver=None): ''' Return a list of IPs of the nameservers for ``domain`` If 'resolve' is False, don't resolve names. CLI Example: .. code-block:: bash salt ns1 dnsutil.NS google.com ''' if _has_dig(): return __salt__['dig.NS'](domain, res...
Return a list of lists for the MX of ``domain``. If the 'resolve' argument is True, resolve IPs for the servers. It's limited to one IP, because although in practice it's very rarely a round robin, it is an acceptable configuration and pulling just one IP lets the data be similar to the non-resolved v...
def MX(domain, resolve=False, nameserver=None): ''' Return a list of lists for the MX of ``domain``. If the 'resolve' argument is True, resolve IPs for the servers. It's limited to one IP, because although in practice it's very rarely a round robin, it is an acceptable configuration and pulling ju...
Some things need to be init'd after the fork has completed The easiest example is that one of these module types creates a thread in the parent process, then once the fork happens you'll start getting errors like "WARNING: Mixing fork() and threads detected; memory leaked."
def _post_fork_init(self): ''' Some things need to be init'd after the fork has completed The easiest example is that one of these module types creates a thread in the parent process, then once the fork happens you'll start getting errors like "WARNING: Mixing fork() and threads ...
This is the general passive maintenance process controller for the Salt master. This is where any data that needs to be cleanly maintained from the master is maintained.
def run(self): ''' This is the general passive maintenance process controller for the Salt master. This is where any data that needs to be cleanly maintained from the master is maintained. ''' salt.utils.process.appendproctitle(self.__class__.__name__) #...
Evaluate accepted keys and create a msgpack file which contains a list
def handle_key_cache(self): ''' Evaluate accepted keys and create a msgpack file which contains a list ''' if self.opts['key_cache'] == 'sched': keys = [] #TODO DRY from CKMinions if self.opts['transport'] in ('zeromq', 'tcp'): ...
Rotate the AES key rotation
def handle_key_rotate(self, now): ''' Rotate the AES key rotation ''' to_rotate = False dfn = os.path.join(self.opts['cachedir'], '.dfn') try: stats = os.stat(dfn) # Basic Windows permissions don't distinguish between # user/group/all. ...
Update git pillar
def handle_git_pillar(self): ''' Update git pillar ''' try: for pillar in self.git_pillar: pillar.fetch_remotes() except Exception as exc: log.error('Exception caught while updating git_pillar', exc_info=True)
Evaluate the scheduler
def handle_schedule(self): ''' Evaluate the scheduler ''' try: self.schedule.eval() # Check if scheduler requires lower loop interval than # the loop_interval setting if self.schedule.loop_interval < self.loop_interval: self...
Fire presence events if enabled
def handle_presence(self, old_present): ''' Fire presence events if enabled ''' # On the first run it may need more time for the EventPublisher # to come up and be ready. Set the timeout to account for this. if self.presence_events and self.event.connect_pull(timeout=3): ...
Get the configured backends and the intervals for any backend which supports them, and set up the update "buckets". There will be one bucket for each thing being updated at a given interval.
def fill_buckets(self): ''' Get the configured backends and the intervals for any backend which supports them, and set up the update "buckets". There will be one bucket for each thing being updated at a given interval. ''' update_intervals = self.fileserver.update_interva...
Threading target which handles all updates for a given wait interval
def update_fileserver(self, interval, backends): ''' Threading target which handles all updates for a given wait interval ''' def _do_update(): log.debug( 'Performing fileserver updates for items with an update ' 'interval of %d', interval ...
Start the update threads
def run(self): ''' Start the update threads ''' salt.utils.process.appendproctitle(self.__class__.__name__) # Clean out the fileserver backend cache salt.daemons.masterapi.clean_fsbackend(self.opts) for interval in self.buckets: self.update_threads[in...
Run pre flight checks. If anything in this method fails then the master should not start up.
def _pre_flight(self): ''' Run pre flight checks. If anything in this method fails then the master should not start up. ''' errors = [] critical_errors = [] try: os.chdir('/') except OSError as err: errors.append( '...
Turn on the master server components
def start(self): ''' Turn on the master server components ''' self._pre_flight() log.info('salt-master is starting as user \'%s\'', salt.utils.user.get_user()) enable_sigusr1_handler() enable_sigusr2_handler() self.__set_max_open_files() # Reset...
Fire up halite!
def run(self): ''' Fire up halite! ''' salt.utils.process.appendproctitle(self.__class__.__name__) halite.start(self.hopts)
Binds the reply server
def __bind(self): ''' Binds the reply server ''' if self.log_queue is not None: salt.log.setup.set_multiprocessing_logging_queue(self.log_queue) if self.log_queue_level is not None: salt.log.setup.set_multiprocessing_logging_level(self.log_queue_level) ...
Bind to the local port
def __bind(self): ''' Bind to the local port ''' # using ZMQIOLoop since we *might* need zmq in there install_zmq() self.io_loop = ZMQDefaultLoop() self.io_loop.make_current() for req_channel in self.req_channels: req_channel.post_fork(self._ha...
The _handle_payload method is the key method used to figure out what needs to be done with communication to the server Example cleartext payload generated for 'salt myminion test.ping': {'enc': 'clear', 'load': {'arg': [], 'cmd': 'publish', 'fun': '...
def _handle_payload(self, payload): ''' The _handle_payload method is the key method used to figure out what needs to be done with communication to the server Example cleartext payload generated for 'salt myminion test.ping': {'enc': 'clear', 'load': {'arg': [], ...
Fire events with stat info if it's time
def _post_stats(self, stats): ''' Fire events with stat info if it's time ''' end_time = time.time() if end_time - self.stat_clock > self.opts['master_stats_event_iter']: # Fire the event with the stats and wipe the tracker self.aes_funcs.event.fire_event(...
Process a cleartext command :param dict load: Cleartext payload :return: The result of passing the load to a function in ClearFuncs corresponding to the command specified in the load's 'cmd' key.
def _handle_clear(self, load): ''' Process a cleartext command :param dict load: Cleartext payload :return: The result of passing the load to a function in ClearFuncs corresponding to the command specified in the load's 'cmd' key. ''' log.trace('Clear pa...
Process a command sent via an AES key :param str load: Encrypted payload :return: The result of passing the load to a function in AESFuncs corresponding to the command specified in the load's 'cmd' key.
def _handle_aes(self, data): ''' Process a command sent via an AES key :param str load: Encrypted payload :return: The result of passing the load to a function in AESFuncs corresponding to the command specified in the load's 'cmd' key. ''' if 'cmd' not i...
Start a Master Worker
def run(self): ''' Start a Master Worker ''' salt.utils.process.appendproctitle(self.name) self.clear_funcs = ClearFuncs( self.opts, self.key, ) self.aes_funcs = AESFuncs(self.opts) salt.utils.crypt.reinit_crypto() self.__b...
Set the local file objects from the file server interface
def __setup_fileserver(self): ''' Set the local file objects from the file server interface ''' # Avoid circular import import salt.fileserver self.fs_ = salt.fileserver.Fileserver(self.opts) self._serve_file = self.fs_.serve_file self._file_find = self.fs...
Take a minion id and a string signed with the minion private key The string needs to verify as 'salt' with the minion public key :param str id_: A minion ID :param str token: A string signed with the minion private key :rtype: bool :return: Boolean indicating whether or not the...
def __verify_minion(self, id_, token): ''' Take a minion id and a string signed with the minion private key The string needs to verify as 'salt' with the minion public key :param str id_: A minion ID :param str token: A string signed with the minion private key :rtype: ...
Verify that the passed information authorized a minion to execute :param dict clear_load: A publication load from a minion :rtype: bool :return: A boolean indicating if the minion is allowed to publish the command in the load
def __verify_minion_publish(self, clear_load): ''' Verify that the passed information authorized a minion to execute :param dict clear_load: A publication load from a minion :rtype: bool :return: A boolean indicating if the minion is allowed to publish the command in the load ...
A utility function to perform common verification steps. :param dict load: A payload received from a minion :param list verify_keys: A list of strings that should be present in a given load :rtype: bool :rtype: dict :return: The original load (except for the token) if t...
def __verify_load(self, load, verify_keys): ''' A utility function to perform common verification steps. :param dict load: A payload received from a minion :param list verify_keys: A list of strings that should be present in a given load :rtype: bool :rtype: dic...
Return the results from an external node classifier if one is specified :param dict load: A payload received from a minion :return: The results from an external node classifier
def _master_tops(self, load): ''' Return the results from an external node classifier if one is specified :param dict load: A payload received from a minion :return: The results from an external node classifier ''' load = self.__verify_load(load, ('id', 'tok')) ...
Gathers the data from the specified minions' mine :param dict load: A payload received from a minion :rtype: dict :return: Mine data from the specified minions
def _mine_get(self, load): ''' Gathers the data from the specified minions' mine :param dict load: A payload received from a minion :rtype: dict :return: Mine data from the specified minions ''' load = self.__verify_load(load, ('id', 'tgt', 'fun', 'tok')) ...
Store the mine data :param dict load: A payload received from a minion :rtype: bool :return: True if the data has been stored in the mine
def _mine(self, load): ''' Store the mine data :param dict load: A payload received from a minion :rtype: bool :return: True if the data has been stored in the mine ''' load = self.__verify_load(load, ('id', 'data', 'tok')) if load is False: ...
Allow the minion to delete a specific function from its own mine :param dict load: A payload received from a minion :rtype: bool :return: Boolean indicating whether or not the given function was deleted from the mine
def _mine_delete(self, load): ''' Allow the minion to delete a specific function from its own mine :param dict load: A payload received from a minion :rtype: bool :return: Boolean indicating whether or not the given function was deleted from the mine ''' load = ...
Allow the minion to delete all of its own mine contents :param dict load: A payload received from a minion
def _mine_flush(self, load): ''' Allow the minion to delete all of its own mine contents :param dict load: A payload received from a minion ''' load = self.__verify_load(load, ('id', 'tok')) if load is False: return {} else: return self.ma...
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 False if not isinstance(load['path'], list): return False ...
Return the pillar data for the minion :param dict load: Minion payload :rtype: dict :return: The pillar data for the minion
def _pillar(self, load): ''' Return the pillar data for the minion :param dict load: Minion payload :rtype: dict :return: The pillar data for the minion ''' if any(key not in load for key in ('id', 'grains')): return False if not salt.utils.v...
Receive an event from the minion and fire it on the master event interface :param dict load: The minion payload
def _minion_event(self, load): ''' Receive an event from the minion and fire it on the master event interface :param dict load: The minion payload ''' load = self.__verify_load(load, ('id', 'tok')) if load is False: return {} # Route to master...
Act on specific events from minions
def _handle_minion_event(self, load): ''' Act on specific events from minions ''' id_ = load['id'] if load.get('tag', '') == '_salt_error': log.error( 'Received minion error from [%s]: %s', id_, load['data']['message'] ) ...
Handle the return data sent from the minions. Takes the return, verifies it and fires it on the master event bus. Typically, this event is consumed by the Salt CLI waiting on the other end of the event bus but could be heard by any listener on the bus. :param dict load: The minion payl...
def _return(self, load): ''' Handle the return data sent from the minions. Takes the return, verifies it and fires it on the master event bus. Typically, this event is consumed by the Salt CLI waiting on the other end of the event bus but could be heard by any listener on the bu...
Receive a syndic minion return and format it to look like returns from individual minions. :param dict load: The minion payload
def _syndic_return(self, load): ''' Receive a syndic minion return and format it to look like returns from individual minions. :param dict load: The minion payload ''' loads = load.get('load') if not isinstance(loads, list): loads = [load] # support ...
Execute a runner from a minion, return the runner's function data :param dict clear_load: The minion payload :rtype: dict :return: The runner function data
def minion_runner(self, clear_load): ''' Execute a runner from a minion, return the runner's function data :param dict clear_load: The minion payload :rtype: dict :return: The runner function data ''' load = self.__verify_load(clear_load, ('fun', 'arg', 'id', 't...
Request the return data from a specific jid, only allowed if the requesting minion also initialted the execution. :param dict load: The minion payload :rtype: dict :return: Return data corresponding to a given JID
def pub_ret(self, load): ''' Request the return data from a specific jid, only allowed if the requesting minion also initialted the execution. :param dict load: The minion payload :rtype: dict :return: Return data corresponding to a given JID ''' load = ...
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 ...
def minion_pub(self, clear_load): ''' 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 fu...
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 ...
def minion_publish(self, clear_load): ''' 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 sal...
Allow a minion to request revocation of its own key :param dict load: The minion payload :rtype: dict :return: If the load is invalid, it may be returned. No key operation is performed. :rtype: bool :return: True if key was revoked, False if not
def revoke_auth(self, load): ''' Allow a minion to request revocation of its own key :param dict load: The minion payload :rtype: dict :return: If the load is invalid, it may be returned. No key operation is performed. :rtype: bool :return: True if key was revo...
Wrapper for running functions executed with AES encryption :param function func: The function to run :return: The result of the master function that was called
def run_func(self, func, load): ''' Wrapper for running functions executed with AES encryption :param function func: The function to run :return: The result of the master function that was called ''' # Don't honor private functions if func.startswith('__'): ...
Send a master control function back to the runner system
def runner(self, clear_load): ''' Send a master control function back to the runner system ''' # All runner ops pass through eauth auth_type, err_name, key, sensitive_load_keys = self._prep_auth_info(clear_load) # Authenticate auth_check = self.loadauth.check_aut...
Send a master control function back to the wheel system
def wheel(self, clear_load): ''' Send a master control function back to the wheel system ''' # All wheel ops pass through eauth auth_type, err_name, key, sensitive_load_keys = self._prep_auth_info(clear_load) # Authenticate auth_check = self.loadauth.check_authen...
Create and return an authentication token, the clear load needs to contain the eauth key and the needed authentication creds.
def mk_token(self, clear_load): ''' Create and return an authentication token, the clear load needs to contain the eauth key and the needed authentication creds. ''' token = self.loadauth.mk_token(clear_load) if not token: log.warning('Authentication failure o...
This method sends out publications to the minions, it can only be used by the LocalClient.
def publish(self, clear_load): ''' This method sends out publications to the minions, it can only be used by the LocalClient. ''' extra = clear_load.get('kwargs', {}) publisher_acl = salt.acl.PublisherACL(self.opts['publisher_acl_blacklist']) if publisher_acl.us...
Return a jid for this publication
def _prep_jid(self, clear_load, extra): ''' Return a jid for this publication ''' # the jid in clear_load can be None, '', or something else. this is an # attempt to clean up the value before passing to plugins passed_jid = clear_load['jid'] if clear_load.get('jid') else ...
Take a load and send it across the network to connected minions
def _send_pub(self, load): ''' Take a load and send it across the network to connected minions ''' for transport, opts in iter_transport_opts(self.opts): chan = salt.transport.server.PubServerChannel.factory(opts) chan.publish(load)
Take a load and send it across the network to ssh minions
def _send_ssh_pub(self, load, ssh_minions=False): ''' Take a load and send it across the network to ssh minions ''' if self.opts['enable_ssh_minions'] is True and ssh_minions is True: log.debug('Send payload to ssh minions') threading.Thread(target=self.ssh_client...
Take a given load and perform the necessary steps to prepare a publication. TODO: This is really only bound by temporal cohesion and thus should be refactored even further.
def _prep_pub(self, minions, jid, clear_load, extra, missing): ''' Take a given load and perform the necessary steps to prepare a publication. TODO: This is really only bound by temporal cohesion and thus should be refactored even further. ''' clear_load['jid'] =...
Makes sure the specified row is absent in db. If multiple rows match where_sql, then the state will fail. name Only used as the unique ID db The database file name table The table name to check where_sql The sql to select the row to check where_args ...
def row_absent(name, db, table, where_sql, where_args=None): ''' Makes sure the specified row is absent in db. If multiple rows match where_sql, then the state will fail. name Only used as the unique ID db The database file name table The table name to check wher...
Checks to make sure the given row exists. If row exists and update is True then row will be updated with data. Otherwise it will leave existing row unmodified and check it against data. If the existing data doesn't match data_check the state will fail. If the row doesn't exist then it will insert data ...
def row_present(name, db, table, data, where_sql, where_args=None, update=False): ''' Checks to make sure the given row exists. If row exists and update is True then row will be updated with data. Otherwise it wi...
Make sure the specified table does not exist name The name of the table db The name of the database file
def table_absent(name, db): ''' Make sure the specified table does not exist name The name of the table db The name of the database file ''' changes = {'name': name, 'changes': {}, 'result': None, 'comment': ''} conn = None t...
Make sure the specified table exists with the specified schema name The name of the table db The name of the database file schema The dictionary containing the schema information force If the name of the table exists and force is set to False, the state will f...
def table_present(name, db, schema, force=False): ''' Make sure the specified table exists with the specified schema name The name of the table db The name of the database file schema The dictionary containing the schema information force If the name of the ta...
Matches based on range cluster
def match(tgt, opts=None): ''' Matches based on range cluster ''' if not opts: opts = __opts__ if HAS_RANGE: range_ = seco.range.Range(opts['range_server']) try: return opts['grains']['fqdn'] in range_.expand(tgt) except seco.range.RangeException as exc: ...
Return data to a Cassandra ColumnFamily
def returner(ret): ''' Return data to a Cassandra ColumnFamily ''' consistency_level = getattr(pycassa.ConsistencyLevel, __opts__['cassandra.consistency_level']) pool = pycassa.ConnectionPool(__opts__['cassandra.keyspace'], __opts__...
Update and get the random script to a random place CLI Example: .. code-block:: bash salt '*' seed.prep_bootstrap /tmp
def prep_bootstrap(mpt): ''' Update and get the random script to a random place CLI Example: .. code-block:: bash salt '*' seed.prep_bootstrap /tmp ''' # Verify that the boostrap script is downloaded bs_ = __salt__['config.gather_bootstrap_script']() fpd_ = os.path.join(mpt, ...
Seed a location (disk image, directory, or block device) with the minion config, approve the minion's key, and/or install salt-minion. CLI Example: .. code-block:: bash salt 'minion' seed.apply path id [config=config_data] \\ [gen_key=(true|false)] [approve_key=(true|false)] \\ ...
def apply_(path, id_=None, config=None, approve_key=True, install=True, prep_install=False, pub_key=None, priv_key=None, mount_point=None): ''' Seed a location (disk image, directory, or block device) with the minion config, approve the minion's key, and/or install salt-minion. CLI Example: ...
Generate keys and config and put them in a tmp directory. pub_key absolute path or file content of an optional preseeded salt key priv_key absolute path or file content of an optional preseeded salt key CLI Example: .. code-block:: bash salt 'minion' seed.mkconfig [config=co...
def mkconfig(config=None, tmp=None, id_=None, approve_key=True, pub_key=None, priv_key=None): ''' Generate keys and config and put them in a tmp directory. pub_key absolute path or file content of an optional preseeded salt key p...
Check that the resolv.conf is present and populated
def _check_resolv(mpt): ''' Check that the resolv.conf is present and populated ''' resolv = os.path.join(mpt, 'etc/resolv.conf') replace = False if os.path.islink(resolv): resolv = os.path.realpath(resolv) if not os.path.isdir(os.path.dirname(resolv)): os.makedirs(os...
Determine whether salt-minion is installed and, if not, install it. Return True if install is successful or already installed.
def _install(mpt): ''' Determine whether salt-minion is installed and, if not, install it. Return True if install is successful or already installed. ''' _check_resolv(mpt) boot_, tmppath = (prep_bootstrap(mpt) or salt.syspaths.BOOTSTRAP) # Exec the chroot command cmd = ...
helper function to get the results of ``netsh -f content.txt`` Running ``netsh`` will drop you into a ``netsh`` prompt where you can issue ``netsh`` commands. You can put a series of commands in an external file and run them as if from a ``netsh`` prompt using the ``-f`` switch. That's what this functi...
def _netsh_file(content): ''' helper function to get the results of ``netsh -f content.txt`` Running ``netsh`` will drop you into a ``netsh`` prompt where you can issue ``netsh`` commands. You can put a series of commands in an external file and run them as if from a ``netsh`` prompt using the ``-f...
Get the firewall property from the specified profile in the specified store as returned by ``netsh advfirewall``. Args: profile (str): The firewall profile to query. Valid options are: - domain - public - private section (str): The ...
def get_settings(profile, section, store='local'): ''' Get the firewall property from the specified profile in the specified store as returned by ``netsh advfirewall``. Args: profile (str): The firewall profile to query. Valid options are: - domain - public...
Gets all the properties for the specified profile in the specified store Args: profile (str): The firewall profile to query. Valid options are: - domain - public - private store (str): The store to use. This is either the local firewall...
def get_all_settings(profile, store='local'): ''' Gets all the properties for the specified profile in the specified store Args: profile (str): The firewall profile to query. Valid options are: - domain - public - private store (str): ...
Gets all properties for all profiles in the specified store Args: store (str): The store to use. This is either the local firewall policy or the policy defined by local group policy. Valid options are: - lgpo - local Default is ``local`` R...
def get_all_profiles(store='local'): ''' Gets all properties for all profiles in the specified store Args: store (str): The store to use. This is either the local firewall policy or the policy defined by local group policy. Valid options are: - lgpo ...
Set the firewall inbound/outbound settings for the specified profile and store Args: profile (str): The firewall profile to configure. Valid options are: - domain - public - private inbound (str): The inbound setting. If ``None`` is...
def set_firewall_settings(profile, inbound=None, outbound=None, store='local'): ''' Set the firewall inbound/outbound settings for the specified profile and store Args: profile (str): The firewall profile...
Configure logging settings for the Windows firewall. Args: profile (str): The firewall profile to configure. Valid options are: - domain - public - private setting (str): The logging setting to configure. Valid options are: ...
def set_logging_settings(profile, setting, value, store='local'): ''' Configure logging settings for the Windows firewall. Args: profile (str): The firewall profile to configure. Valid options are: - domain - public - private setting (str):...
Configure firewall settings. Args: profile (str): The firewall profile to configure. Valid options are: - domain - public - private setting (str): The firewall setting to configure. Valid options are: - localfirewallrules ...
def set_settings(profile, setting, value, store='local'): ''' Configure firewall settings. Args: profile (str): The firewall profile to configure. Valid options are: - domain - public - private setting (str): The firewall settin...
Configure the firewall state. Args: profile (str): The firewall profile to configure. Valid options are: - domain - public - private state (str): The firewall state. Valid options are: - on - off - n...
def set_state(profile, state, store='local'): ''' Configure the firewall state. Args: profile (str): The firewall profile to configure. Valid options are: - domain - public - private state (str): The firewall state. Valid option...
Parse the aliases file, and return a list of line components: [ (alias1, target1, comment1), (alias2, target2, comment2), ]
def __parse_aliases(): ''' Parse the aliases file, and return a list of line components: [ (alias1, target1, comment1), (alias2, target2, comment2), ] ''' afn = __get_aliases_filename() ret = [] if not os.path.isfile(afn): return ret with salt.utils.files.fopen(a...
Write a new copy of the aliases file. Lines is a list of lines as returned by __parse_aliases.
def __write_aliases_file(lines): ''' Write a new copy of the aliases file. Lines is a list of lines as returned by __parse_aliases. ''' afn = __get_aliases_filename() adir = os.path.dirname(afn) out = tempfile.NamedTemporaryFile(dir=adir, delete=False) if not __opts__.get('integration...
Return the aliases found in the aliases file in this format:: {'alias': 'target'} CLI Example: .. code-block:: bash salt '*' aliases.list_aliases
def list_aliases(): ''' Return the aliases found in the aliases file in this format:: {'alias': 'target'} CLI Example: .. code-block:: bash salt '*' aliases.list_aliases ''' ret = dict((alias, target) for alias, target, comment in __parse_aliases() if alias) return ret
Return true if the alias/target is set CLI Example: .. code-block:: bash salt '*' aliases.has_target alias target
def has_target(alias, target): ''' Return true if the alias/target is set CLI Example: .. code-block:: bash salt '*' aliases.has_target alias target ''' if target == '': raise SaltInvocationError('target can not be an empty string') aliases = list_aliases() if alias no...
Set the entry in the aliases file for the given alias, this will overwrite any previous entry for the given alias or create a new one if it does not exist. CLI Example: .. code-block:: bash salt '*' aliases.set_target alias target
def set_target(alias, target): ''' Set the entry in the aliases file for the given alias, this will overwrite any previous entry for the given alias or create a new one if it does not exist. CLI Example: .. code-block:: bash salt '*' aliases.set_target alias target ''' if ali...
Remove an entry from the aliases file CLI Example: .. code-block:: bash salt '*' aliases.rm_alias alias
def rm_alias(alias): ''' Remove an entry from the aliases file CLI Example: .. code-block:: bash salt '*' aliases.rm_alias alias ''' if not get_target(alias): return True lines = __parse_aliases() out = [] for (line_alias, line_target, line_comment) in lines: ...