INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
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
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
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
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
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
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.
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
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
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
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
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
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
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
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.
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.
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
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.
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.
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.
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
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
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.
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.
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 into the table. I...
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
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
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
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.
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.
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...
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 = ...
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...
helper function to get the results of netsh - f content. txt
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.
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
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
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
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.
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.
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.
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:
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::
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
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.
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
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: ...
Gather the specified data from the minion data cache
def gather_cache(self): ''' Gather the specified data from the minion data cache ''' cache = {'grains': {}, 'pillar': {}} if self.grains or self.pillar: if self.opts.get('minion_data_cache'): minions = self.cache.list('minions') if not ...
Start the system!
def start_runtime(self): ''' Start the system! ''' while True: try: self.call_runtime() except Exception: log.error('Exception in Thorium: ', exc_info=True) time.sleep(self.opts['thorium_interval'])
Compile the top file and return the lowstate for the thorium runtime to iterate over
def get_chunks(self, exclude=None, whitelist=None): ''' Compile the top file and return the lowstate for the thorium runtime to iterate over ''' ret = {} err = [] try: top = self.get_top() except SaltRenderError as err: return ret ...
iterate over the available events and return a list of events
def get_events(self): ''' iterate over the available events and return a list of events ''' ret = [] while True: event = self.event.get_event(wait=1, full=True) if event is None: return ret ret.append(event)
Execute the runtime
def call_runtime(self): ''' Execute the runtime ''' cache = self.gather_cache() chunks = self.get_chunks() interval = self.opts['thorium_interval'] recompile = self.opts.get('thorium_recompile', 300) r_start = time.time() while True: ev...
Decorator for common function argument validation
def _validate(wrapped): ''' Decorator for common function argument validation ''' @functools.wraps(wrapped) def wrapper(*args, **kwargs): container_type = kwargs.get('container_type') exec_driver = kwargs.get('exec_driver') valid_driver = { 'docker': ('lxc-attach'...
Wrapper for cp. cache_file which raises an error if the file was unable to be cached.
def cache_file(source): ''' Wrapper for cp.cache_file which raises an error if the file was unable to be cached. CLI Example: .. code-block:: bash salt myminion container_resource.cache_file salt://foo/bar/baz.txt ''' try: # Don't just use cp.cache_file for this. Docker ha...
Common logic for running shell commands in containers
def run(name, cmd, container_type=None, exec_driver=None, output=None, no_start=False, stdin=None, python_shell=True, output_loglevel='debug', ignore_retcode=False, path=None, use_vt=False, keep_env=None): ''' Common...
Common logic for copying files to containers
def copy_to(name, source, dest, container_type=None, path=None, exec_driver=None, overwrite=False, makedirs=False): ''' Common logic for copying files to containers path path to the container parent (for LXC only) ...
Directly calls the given function with arguments
def execute(opts, data, func, args, kwargs): ''' Directly calls the given function with arguments ''' if data['fun'] == 'saltutil.find_job': return __executors__['direct_call.execute'](opts, data, func, args, kwargs) if data['fun'] in DOCKER_MOD_MAP: return __executors__['direct_call...
Execute the salt command line
def run(self): ''' Execute the salt command line ''' import salt.client self.parse_args() if self.config['log_level'] not in ('quiet', ): # Setup file logging! self.setup_logfile_logger() verify_log(self.config) try: ...
Display returns summary
def _print_returns_summary(self, ret): ''' Display returns summary ''' return_counter = 0 not_return_counter = 0 not_return_minions = [] not_response_minions = [] not_connected_minions = [] failed_minions = [] for each_minion in ret: ...
Print progress events
def _progress_ret(self, progress, out): ''' Print progress events ''' import salt.output # Get the progress bar if not hasattr(self, 'progress_bar'): try: self.progress_bar = salt.output.get_progress(self.config, out, progress) exce...
Print the output from a single return to the terminal
def _output_ret(self, ret, out, retcode=0): ''' Print the output from a single return to the terminal ''' import salt.output # Handle special case commands if self.config['fun'] == 'sys.doc' and not isinstance(ret, Exception): self._print_docs(ret) els...
Take the full return data and format it to simple output
def _format_ret(self, full_ret): ''' Take the full return data and format it to simple output ''' ret = {} out = '' retcode = 0 for key, data in six.iteritems(full_ret): ret[key] = data['ret'] if 'out' in data: out = data['o...
Determine a retcode for a given return
def _get_retcode(self, ret): ''' Determine a retcode for a given return ''' retcode = 0 # if there is a dict with retcode, use that if isinstance(ret, dict) and ret.get('retcode', 0) != 0: if isinstance(ret.get('retcode', 0), dict): return max(...
Print out the docstrings for all of the functions on the minions
def _print_docs(self, ret): ''' Print out the docstrings for all of the functions on the minions ''' import salt.output docs = {} if not ret: self.exit(2, 'No minions found to gather docs from\n') if isinstance(ret, six.string_types): self....
Make text into a double - quoted YAML string with correct escaping for special characters. Includes the opening and closing double quote characters.
def yaml_dquote(text): ''' Make text into a double-quoted YAML string with correct escaping for special characters. Includes the opening and closing double quote characters. ''' with io.StringIO() as ostream: yemitter = yaml.emitter.Emitter(ostream, width=six.MAXSIZE) yemitter.w...
Make text into a single - quoted YAML string with correct escaping for special characters. Includes the opening and closing single quote characters.
def yaml_squote(text): ''' Make text into a single-quoted YAML string with correct escaping for special characters. Includes the opening and closing single quote characters. ''' with io.StringIO() as ostream: yemitter = yaml.emitter.Emitter(ostream, width=six.MAXSIZE) yemitter.w...
A simple YAML encode that can take a single - element datatype and return a string representation.
def yaml_encode(data): ''' A simple YAML encode that can take a single-element datatype and return a string representation. ''' yrepr = yaml.representer.SafeRepresenter() ynode = yrepr.represent_data(data) if not isinstance(ynode, yaml.ScalarNode): raise TypeError( "yaml_...
Recursively try to decrypt any object. If the object is a six. string_types ( string or unicode ) and it contains a valid NACLENC pretext decrypt it otherwise keep going until a string is found.
def _decrypt_object(obj, **kwargs): ''' Recursively try to decrypt any object. If the object is a six.string_types (string or unicode), and it contains a valid NACLENC pretext, decrypt it, otherwise keep going until a string is found. ''' if salt.utils.stringio.is_readable(obj): return _...
Execute queries against MySQL merge and return as a dict
def ext_pillar(minion_id, pillar, *args, **kwargs): ''' Execute queries against MySQL, merge and return as a dict ''' return MySQLExtPillar().fetch(minion_id, pillar, *args, **kwargs)
Returns options used for the MySQL connection.
def _get_options(self): ''' Returns options used for the MySQL connection. ''' defaults = {'host': 'localhost', 'user': 'salt', 'pass': 'salt', 'db': 'salt', 'port': 3306, 'ssl': {}} ...
Yield a MySQL cursor
def _get_cursor(self): ''' Yield a MySQL cursor ''' _options = self._get_options() conn = MySQLdb.connect(host=_options['host'], user=_options['user'], passwd=_options['pass'], db=_option...
This function normalizes the config block into a set of queries we can use. The return is a list of consistently laid out dicts.
def extract_queries(self, args, kwargs): ''' This function normalizes the config block into a set of queries we can use. The return is a list of consistently laid out dicts. ''' return super(MySQLExtPillar, self).extract_queries(args, kwargs)
Retrieves an option based on key merging all matches.
def merge(value, default='', omit_opts=False, omit_master=False, omit_pillar=False): ''' Retrieves an option based on key, merging all matches. Same as ``option()`` except that it merges all matches, rather than taking the first match. CLI Example: .. c...
.. versionadded: 0. 14. 0
def get(key, default=''): ''' .. versionadded: 0.14.0 Attempt to retrieve the named value from opts, pillar, grains of the master config, if the named value is not available return the passed default. The default return is an empty string. The value can also represent a value in a nested dict ...
Creates Zabbix Action object or if differs update it according defined parameters
def present(name, params, **kwargs): ''' Creates Zabbix Action object or if differs update it according defined parameters :param name: Zabbix Action name :param params: Definition of the Zabbix Action :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's ...
Return True if the named service is available.
def available(name): ''' Return True if the named service is available. CLI Example: .. code-block:: bash salt '*' service.available sshd ''' cmd = '{0} get {1}'.format(_cmd(), name) if __salt__['cmd.retcode'](cmd) == 2: return False return True
Return all installed services.
def get_all(): ''' Return all installed services. CLI Example: .. code-block:: bash salt '*' service.get_all ''' ret = [] service = _cmd() for svc in __salt__['cmd.run']('{0} ls all'.format(service)).splitlines(): ret.append(svc) return sorted(ret)
Return the status for a service returns a bool whether the service is running.
def status(name, sig=None): ''' Return the status for a service, returns a bool whether the service is running. CLI Example: .. code-block:: bash salt '*' service.status <service name> ''' if sig: return bool(__salt__['status.pid'](sig)) cmd = '{0} check {1}'.format(_...
Enable the named service to start at boot.
def enable(name, **kwargs): ''' Enable the named service to start at boot. flags : None Set optional flags to run the service with. service.flags can be used to change the default flags. CLI Example: .. code-block:: bash salt '*' service.enable <service name> salt '*...
Return True if the named service is enabled at boot and the provided flags match the configured ones ( if any ). Return False otherwise.
def enabled(name, **kwargs): ''' Return True if the named service is enabled at boot and the provided flags match the configured ones (if any). Return False otherwise. name Service name CLI Example: .. code-block:: bash salt '*' service.enabled <service name> salt '*'...
Creates a longer list of accepted users on the device.
def _expand_users(device_users, common_users): '''Creates a longer list of accepted users on the device.''' expected_users = deepcopy(common_users) expected_users.update(device_users) return expected_users
Checks if the input dictionary of users is valid.
def _check_users(users): '''Checks if the input dictionary of users is valid.''' messg = '' valid = True for user, user_details in six.iteritems(users): if not user_details: valid = False messg += 'Please provide details for username {user}.\n'.format(user=user) ...
Computes the differences between the actual config and the expected config
def _compute_diff(configured, expected): '''Computes the differences between the actual config and the expected config''' diff = { 'add': {}, 'update': {}, 'remove': {} } configured_users = set(configured.keys()) expected_users = set(expected.keys()) add_usernames = e...