INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Returns True if data is a list of one - element dicts ( as found in many SLS schemas ) otherwise returns False
def is_dictlist(data): ''' Returns True if data is a list of one-element dicts (as found in many SLS schemas), otherwise returns False ''' if isinstance(data, list): for element in data: if isinstance(element, dict): if len(element) != 1: retur...
Takes a list of one - element dicts ( as found in many SLS schemas ) and repacks into a single dictionary.
def repack_dictlist(data, strict=False, recurse=False, key_cb=None, val_cb=None): ''' Takes a list of one-element dicts (as found in many SLS schemas) and repacks into a single dictionary. ''' if isinstance(data, six.str...
Test if an object is iterable but not a string type.
def is_iter(y, ignore=six.string_types): ''' Test if an object is iterable, but not a string type. Test if an object is an iterator or is iterable itself. By default this does not return True for string objects. The `ignore` argument defaults to a list of string types that are not considered i...
Returns a boolean value representing the truth of the value passed. The rules for what is a True value are:
def is_true(value=None): ''' Returns a boolean value representing the "truth" of the value passed. The rules for what is a "True" value are: 1. Integer/float values greater than 0 2. The string values "True" and "true" 3. Any object for which bool(obj) returns True ''' # Fir...
Convert MySQL - style output to a python dictionary
def mysql_to_dict(data, key): ''' Convert MySQL-style output to a python dictionary ''' ret = {} headers = [''] for line in data: if not line: continue if line.startswith('+'): continue comps = line.split('|') for comp in range(len(comps)):...
Convert the data list dictionary into simple types i. e. int float string bool etc.
def simple_types_filter(data): ''' Convert the data list, dictionary into simple types, i.e., int, float, string, bool, etc. ''' if data is None: return data simpletypes_keys = (six.string_types, six.text_type, six.integer_types, float, bool) simpletypes_values = tuple(list(simplety...
Given an iterable returns its items as a list with any non - string items converted to unicode strings.
def stringify(data): ''' Given an iterable, returns its items as a list, with any non-string items converted to unicode strings. ''' ret = [] for item in data: if six.PY2 and isinstance(item, str): item = salt.utils.stringutils.to_unicode(item) elif not isinstance(ite...
Query data using JMESPath language ( http:// jmespath. org ).
def json_query(data, expr): ''' Query data using JMESPath language (http://jmespath.org). ''' if jmespath is None: err = 'json_query requires jmespath module installed' log.error(err) raise RuntimeError(err) return jmespath.search(expr, data)
Helper function for filter_falsey to determine if something is not to be considered falsey.
def _is_not_considered_falsey(value, ignore_types=()): ''' Helper function for filter_falsey to determine if something is not to be considered falsey. :param any value: The value to consider :param list ignore_types: The types to ignore when considering the value. :return bool ''' retu...
Helper function to remove items from an iterable with falsey value. Removes None {} and [] 0 ( but does not remove False ). Recurses into sub - iterables if recurse is set to True.
def filter_falsey(data, recurse_depth=None, ignore_types=()): ''' Helper function to remove items from an iterable with falsey value. Removes ``None``, ``{}`` and ``[]``, 0, '' (but does not remove ``False``). Recurses into sub-iterables if ``recurse`` is set to ``True``. :param dict/list data: Sou...
Returns a generator iterating over keys and values with the keys all being lowercase.
def items_lower(self): ''' Returns a generator iterating over keys and values, with the keys all being lowercase. ''' return ((key, val[1]) for key, val in six.iteritems(self._data))
Write a default to the system
def write(name, domain, value, vtype='string', user=None): ''' Write a default to the system name The key of the given domain to write to domain The name of the domain to write to value The value to write to the given key vtype The type of value to be written,...
Make sure the defaults value is absent
def absent(name, domain, user=None): ''' Make sure the defaults value is absent name The key of the given domain to remove domain The name of the domain to remove from user The user to write the defaults to ''' ret = {'name': name, 'result': True, ...
Return information for the specified user This is just returns dummy data so that salt states can work.
def info(name): ''' Return information for the specified user This is just returns dummy data so that salt states can work. :param str name: The name of the user account to show. CLI Example: .. code-block:: bash salt '*' shadow.info root ''' info = __salt__['user.info'](name...
Converts the dotted notation of a saltclass class to its possible file counterparts.
def get_class_paths(_class, saltclass_path): ''' Converts the dotted notation of a saltclass class to its possible file counterparts. :param str _class: Dotted notation of the class :param str saltclass_path: Root to saltclass storage :return: 3-tuple of possible file counterparts :rtype: tuple...
Converts the absolute path to a saltclass file back to the dotted notation.
def get_class_from_file(_file, saltclass_path): ''' Converts the absolute path to a saltclass file back to the dotted notation. .. code-block:: python print(get_class_from_file('/srv/saltclass/classes/services/nginx/init.yml', '/srv/saltclass')) # services.nginx :param str _file: Absolu...
Takes a class name possibly including * or ? wildcards ( or any other wildcards supportet by glob. glob ) and returns a list of expanded class names without wildcards.
def match_class_glob(_class, saltclass_path): ''' Takes a class name possibly including `*` or `?` wildcards (or any other wildcards supportet by `glob.glob`) and returns a list of expanded class names without wildcards. .. code-block:: python classes = match_class_glob('services.*', '/srv/salt...
Expand the list of classes to no longer include any globbing.
def expand_classes_glob(classes, salt_data): ''' Expand the list of `classes` to no longer include any globbing. :param iterable(str) classes: Iterable of classes :param dict salt_data: configuration data :return: Expanded list of classes with resolved globbing :rtype: list(str) ''' all...
Returns True if the given parameter value is an instance of either int str float or bool.
def _is_simple_type(value): ''' Returns True, if the given parameter value is an instance of either int, str, float or bool. ''' return isinstance(value, six.string_types) or isinstance(value, int) or isinstance(value, float) or isinstance(value, bool)
Returns the type id and option of a configuration object.
def _get_type_id_options(name, configuration): ''' Returns the type, id and option of a configuration object. ''' # it's in a form of source.name if '.' in name: type_, sep, id_ = name.partition('.') options = configuration else: type_ = next(six.iterkeys(configuration)) ...
Returns the only one key and it s value from a dictionary.
def _expand_one_key_dictionary(_dict): ''' Returns the only one key and it's value from a dictionary. ''' key = next(six.iterkeys(_dict)) value = _dict[key] return key, value
Creates Arguments in a TypedParametervalue.
def _parse_typed_parameter_typed_value(values): ''' Creates Arguments in a TypedParametervalue. ''' type_, value = _expand_one_key_dictionary(values) _current_parameter_value.type = type_ if _is_simple_type(value): arg = Argument(value) _current_parameter_value.add_argument(arg)...
Parses a TypedParameter and fills it with values.
def _parse_typed_parameter(param): ''' Parses a TypedParameter and fills it with values. ''' global _current_parameter_value type_, value = _expand_one_key_dictionary(param) _current_parameter.type = type_ if _is_simple_type(value) and value != '': _current_parameter_value = SimpleP...
Parses the configuration and creates Parameter instances.
def _create_and_add_parameters(params): ''' Parses the configuration and creates Parameter instances. ''' global _current_parameter if _is_simple_type(params): _current_parameter = SimpleParameter(params) _current_option.add_parameter(_current_parameter) else: # must be a...
Parses the configuration and creates an Option instance.
def _create_and_add_option(option): ''' Parses the configuration and creates an Option instance. ''' global _current_option _current_option = Option() type_, params = _expand_one_key_dictionary(option) _current_option.type = type_ _create_and_add_parameters(params) _current_statemen...
Return True if arg is a reference to a previously defined statement.
def _is_reference(arg): ''' Return True, if arg is a reference to a previously defined statement. ''' return isinstance(arg, dict) and len(arg) == 1 and isinstance(next(six.itervalues(arg)), six.string_types)
Return True if arg is a junction statement.
def _is_junction(arg): ''' Return True, if arg is a junction statement. ''' return isinstance(arg, dict) and len(arg) == 1 and next(six.iterkeys(arg)) == 'junction'
Adds a reference to statement.
def _add_reference(reference, statement): ''' Adds a reference to statement. ''' type_, value = _expand_one_key_dictionary(reference) opt = Option(type_) param = SimpleParameter(value) opt.add_parameter(param) statement.add_child(opt)
Returns True if arg is an inline definition of a statement.
def _is_inline_definition(arg): ''' Returns True, if arg is an inline definition of a statement. ''' return isinstance(arg, dict) and len(arg) == 1 and isinstance(next(six.itervalues(arg)), list)
Adds an inline definition to statement.
def _add_inline_definition(item, statement): ''' Adds an inline definition to statement. ''' global _current_statement backup = _current_statement type_, options = _expand_one_key_dictionary(item) _current_statement = UnnamedStatement(type=type_) _parse_statement(options) statement....
Adds a junction to the _current_statement.
def _add_junction(item): ''' Adds a junction to the _current_statement. ''' type_, channels = _expand_one_key_dictionary(item) junction = UnnamedStatement(type='junction') for item in channels: type_, value = _expand_one_key_dictionary(item) channel = UnnamedStatement(type='chann...
Parses a log path.
def _parse_log_statement(options): ''' Parses a log path. ''' for i in options: if _is_reference(i): _add_reference(i, _current_statement) elif _is_junction(i): _add_junction(i) elif _is_inline_definition(i): _add_inline_definition(i, _current_...
Build the configuration tree.
def _build_config_tree(name, configuration): ''' Build the configuration tree. The root object is _current_statement. ''' type_, id_, options = _get_type_id_options(name, configuration) global _INDENT, _current_statement _INDENT = '' if type_ == 'config': _current_statement = Gi...
Builds syslog - ng configuration. This function is intended to be used from the state module users should not use it directly!
def config(name, config, write=True): ''' Builds syslog-ng configuration. This function is intended to be used from the state module, users should not use it directly! name : the id of the Salt document or it is the format of <statement name>.id config : the parsed YAML code ...
Sets the path where the syslog - ng binary can be found. This function is intended to be used from states.
def set_binary_path(name): ''' Sets the path, where the syslog-ng binary can be found. This function is intended to be used from states. If syslog-ng is installed via a package manager, users don't need to use this function. CLI Example: .. code-block:: bash salt '*' syslog_ng.se...
Sets the configuration s name. This function is intended to be used from states.
def set_config_file(name): ''' Sets the configuration's name. This function is intended to be used from states. CLI Example: .. code-block:: bash salt '*' syslog_ng.set_config_file name=/etc/syslog-ng ''' global __SYSLOG_NG_CONFIG_FILE old = __SYSLOG_NG_CONFIG_FILE __SYSL...
Runs the command cmd with options as its CLI parameters and returns the result as a dictionary.
def _run_command(cmd, options=(), env=None): ''' Runs the command cmd with options as its CLI parameters and returns the result as a dictionary. ''' params = [cmd] params.extend(options) return __salt__['cmd.run_all'](params, env=env, python_shell=False)
Sets variables.
def set_parameters(version=None, binary_path=None, config_file=None, *args, **kwargs): ''' Sets variables. CLI Example: .. code-block:: bash salt '*' syslog_ng.set_parameters version='3.6' salt '*' syslog_ng.s...
Runs the specified command with the syslog_ng_sbin_dir in the PATH
def _run_command_in_extended_path(syslog_ng_sbin_dir, command, params): ''' Runs the specified command with the syslog_ng_sbin_dir in the PATH ''' orig_path = os.environ.get('PATH', '') env = None if syslog_ng_sbin_dir: # Custom environment variables should be str types. This code ...
Creates a dictionary from the parameters which can be used to return data to Salt.
def _format_return_data(retcode, stdout=None, stderr=None): ''' Creates a dictionary from the parameters, which can be used to return data to Salt. ''' ret = {'retcode': retcode} if stdout is not None: ret['stdout'] = stdout if stderr is not None: ret['stderr'] = stderr r...
Returns the version of the installed syslog - ng. If syslog_ng_sbin_dir is specified it is added to the PATH during the execution of the command syslog - ng.
def version(syslog_ng_sbin_dir=None): ''' Returns the version of the installed syslog-ng. If syslog_ng_sbin_dir is specified, it is added to the PATH during the execution of the command syslog-ng. CLI Example: .. code-block:: bash salt '*' syslog_ng.version salt '*' syslog_ng....
Returns the available modules. If syslog_ng_sbin_dir is specified it is added to the PATH during the execution of the command syslog - ng.
def modules(syslog_ng_sbin_dir=None): ''' Returns the available modules. If syslog_ng_sbin_dir is specified, it is added to the PATH during the execution of the command syslog-ng. CLI Example: .. code-block:: bash salt '*' syslog_ng.modules salt '*' syslog_ng.modules /home/user/in...
Returns statistics from the running syslog - ng instance. If syslog_ng_sbin_dir is specified it is added to the PATH during the execution of the command syslog - ng - ctl.
def stats(syslog_ng_sbin_dir=None): ''' Returns statistics from the running syslog-ng instance. If syslog_ng_sbin_dir is specified, it is added to the PATH during the execution of the command syslog-ng-ctl. CLI Example: .. code-block:: bash salt '*' syslog_ng.stats salt '*' sy...
Creates the state result dictionary.
def _format_state_result(name, result, changes=None, comment=''): ''' Creates the state result dictionary. ''' if changes is None: changes = {'old': '', 'new': ''} return {'name': name, 'result': result, 'changes': changes, 'comment': comment}
Adds key and value as a command line parameter to params.
def _add_cli_param(params, key, value): ''' Adds key and value as a command line parameter to params. ''' if value is not None: params.append('--{0}={1}'.format(key, value))
Adds key as a command line parameter to params.
def _add_boolean_cli_param(params, key, value): ''' Adds key as a command line parameter to params. ''' if value is True: params.append('--{0}'.format(key))
Kills syslog - ng. This function is intended to be used from the state module.
def stop(name=None): ''' Kills syslog-ng. This function is intended to be used from the state module. Users shouldn't use this function, if the service module is available on their system. If :mod:`syslog_ng.set_config_file <salt.modules.syslog_ng.set_binary_path>` is called before, this function ...
Ensures that syslog - ng is started via the given parameters. This function is intended to be used from the state module.
def start(name=None, user=None, group=None, chroot=None, caps=None, no_caps=False, pidfile=None, enable_core=False, fd_limit=None, verbose=False, debug=False, trace=False, yydebug=False, per...
Reloads syslog - ng. This function is intended to be used from states.
def reload_(name): ''' Reloads syslog-ng. This function is intended to be used from states. If :mod:`syslog_ng.set_config_file <salt.modules.syslog_ng.set_binary_path>`, is called before, this function will use the set binary path. CLI Example: .. code-block:: bash salt '*' syslo...
Writes the given parameter config into the config file. This function is intended to be used from states.
def write_config(config, newlines=2): ''' Writes the given parameter config into the config file. This function is intended to be used from states. If :mod:`syslog_ng.set_config_file <salt.modules.syslog_ng.set_config_file>`, is called before, this function will use the set config file. CL...
Writes the given parameter config into the config file.
def _write_config(config, newlines=2): ''' Writes the given parameter config into the config file. ''' text = config if isinstance(config, dict) and len(list(list(config.keys()))) == 1: key = next(six.iterkeys(config)) text = config[key] try: with salt.utils.files.fopen(...
Removes the previous configuration file then creates a new one and writes the name line. This function is intended to be used from states.
def write_version(name): ''' Removes the previous configuration file, then creates a new one and writes the name line. This function is intended to be used from states. If :mod:`syslog_ng.set_config_file <salt.modules.syslog_ng.set_config_file>`, is called before, this function will use the set...
Builds the body of a syslog - ng configuration object.
def build_body(self): ''' Builds the body of a syslog-ng configuration object. ''' _increase_indent() body_array = [x.build() for x in self.iterable] nl = '\n' if self.append_extra_newline else '' if len(self.iterable) >= 1: body = self.join_body_on....
Builds the textual representation of the whole configuration object with it s children.
def build(self): ''' Builds the textual representation of the whole configuration object with it's children. ''' header = self.build_header() body = self.build_body() tail = self.build_tail() return header + body + tail
Get the System Locale parameters from dbus
def _parse_dbus_locale(): ''' Get the 'System Locale' parameters from dbus ''' bus = dbus.SystemBus() localed = bus.get_object('org.freedesktop.locale1', '/org/freedesktop/locale1') properties = dbus.Interface(localed, 'org.freedesktop.DBus.Properties') system_lo...
Parse localectl status into a dict.: return: dict
def _localectl_status(): ''' Parse localectl status into a dict. :return: dict ''' if salt.utils.path.which('localectl') is None: raise CommandExecutionError('Unable to find "localectl"') ret = {} locale_ctl_out = (__salt__['cmd.run']('localectl status') or '').strip() ctl_key =...
Use systemd s localectl command to set the LANG locale parameter making sure not to trample on other params that have been set.
def _localectl_set(locale=''): ''' Use systemd's localectl command to set the LANG locale parameter, making sure not to trample on other params that have been set. ''' locale_params = _parse_dbus_locale() if dbus is not None else _localectl_status().get('system_locale', {}) locale_params['LANG']...
Get the current system locale
def get_locale(): ''' Get the current system locale CLI Example: .. code-block:: bash salt '*' locale.get_locale ''' ret = '' lc_ctl = salt.utils.systemd.booted(__context__) # localectl on SLE12 is installed but the integration is still broken in latest SP3 due to # config...
Sets the current system locale
def set_locale(locale): ''' Sets the current system locale CLI Example: .. code-block:: bash salt '*' locale.set_locale 'en_US.UTF-8' ''' lc_ctl = salt.utils.systemd.booted(__context__) # localectl on SLE12 is installed but the integration is broken -- config is rewritten by YaST2...
Check if a locale is available.
def avail(locale): ''' Check if a locale is available. .. versionadded:: 2014.7.0 CLI Example: .. code-block:: bash salt '*' locale.avail 'en_US.UTF-8' ''' try: normalized_locale = salt.utils.locales.normalize_locale(locale) except IndexError: log.error('Unabl...
Generate a locale. Options:
def gen_locale(locale, **kwargs): ''' Generate a locale. Options: .. versionadded:: 2014.7.0 :param locale: Any locale listed in /usr/share/i18n/locales or /usr/share/i18n/SUPPORTED for Debian and Gentoo based distributions, which require the charmap to be specified as part of the loca...
Parsing template
def _parse_template(tmpl_str): ''' Parsing template ''' tmpl_str = tmpl_str.strip() if tmpl_str.startswith('{'): tpl = salt.utils.json.loads(tmpl_str) else: try: tpl = salt.utils.yaml.safe_load(tmpl_str) except salt.utils.yaml.YAMLError as exc: rai...
Deploy stack with the specified properties
def deployed(name, template=None, environment=None, params=None, poll=5, rollback=False, timeout=60, update=False, profile=None, **connection_args): ''' Deploy stack with the specified properties name The name of the stack template File of template enviro...
Ensure that the named stack is absent
def absent(name, poll=5, timeout=60, profile=None): ''' Ensure that the named stack is absent name The name of the stack to remove poll Poll(in sec.) and report events until stack complete timeout Stack creation timeout in minutes profile Profile to use '...
Grain for the minion username
def _username(): ''' Grain for the minion username ''' if pwd: username = pwd.getpwuid(os.getuid()).pw_name else: username = getpass.getuser() return username
Grain for the minion groupname
def _groupname(): ''' Grain for the minion groupname ''' if grp: try: groupname = grp.getgrgid(os.getgid()).gr_name except KeyError: groupname = '' else: groupname = '' return groupname
Unpackages a payload
def unpackage(package_): ''' Unpackages a payload ''' return salt.utils.msgpack.loads(package_, use_list=True, _msgpack_module=msgpack)
Pass in the required arguments for a payload the enc type and the cmd then a list of keyword args to generate the body of the load dict.
def format_payload(enc, **kwargs): ''' Pass in the required arguments for a payload, the enc type and the cmd, then a list of keyword args to generate the body of the load dict. ''' payload = {'enc': enc} load = {} for key in kwargs: load[key] = kwargs[key] payload['load'] = load...
Run the correct loads serialization format
def loads(self, msg, encoding=None, raw=False): ''' Run the correct loads serialization format :param encoding: Useful for Python 3 support. If the msgpack data was encoded using "use_bin_type=True", this will differentiate between the 'bytes' t...
Run the correct serialization to load a file
def load(self, fn_): ''' Run the correct serialization to load a file ''' data = fn_.read() fn_.close() if data: if six.PY3: return self.loads(data, encoding='utf-8') else: return self.loads(data)
Run the correct dumps serialization format
def dumps(self, msg, use_bin_type=False): ''' Run the correct dumps serialization format :param use_bin_type: Useful for Python 3 support. Tells msgpack to differentiate between 'str' and 'bytes' types by encoding them differently. ...
Serialize the correct data into the named file object
def dump(self, msg, fn_): ''' Serialize the correct data into the named file object ''' if six.PY2: fn_.write(self.dumps(msg)) else: # When using Python 3, write files in such a way # that the 'bytes' and 'str' types are distinguishable ...
Lazily create the socket.
def socket(self): ''' Lazily create the socket. ''' if not hasattr(self, '_socket'): # create a new one self._socket = self.context.socket(zmq.REQ) if hasattr(zmq, 'RECONNECT_IVL_MAX'): self._socket.setsockopt( zmq.R...
delete socket if you have it
def clear_socket(self): ''' delete socket if you have it ''' if hasattr(self, '_socket'): if isinstance(self.poller.sockets, dict): sockets = list(self.poller.sockets.keys()) for socket in sockets: log.trace('Unregistering s...
Takes two arguments the encryption type and the base payload
def send(self, enc, load, tries=1, timeout=60): ''' Takes two arguments, the encryption type and the base payload ''' payload = {'enc': enc} payload['load'] = load pkg = self.serial.dumps(payload) self.socket.send(pkg) self.poller.register(self.socket, zmq...
Detect the encryption type based on the payload
def send_auto(self, payload, tries=1, timeout=60): ''' Detect the encryption type based on the payload ''' enc = payload.get('enc', 'clear') load = payload.get('load', {}) return self.send(enc, load, tries, timeout)
Creates or updates LXD profiles
def present(name, description=None, config=None, devices=None, remote_addr=None, cert=None, key=None, verify_cert=True): ''' Creates or updates LXD profiles name : The name of the profile to create/update description : A description string config : A config dic...
Ensure a LXD profile is not present removing it if present.
def absent(name, remote_addr=None, cert=None, key=None, verify_cert=True): ''' Ensure a LXD profile is not present, removing it if present. name : The name of the profile to remove. remote_addr : An URL to a remote Server, you also have to give cert and key if you pr...
Returns a list of modules in loader. conf that load on boot.
def _get_persistent_modules(): ''' Returns a list of modules in loader.conf that load on boot. ''' mods = set() with salt.utils.files.fopen(_LOADER_CONF, 'r') as loader_conf: for line in loader_conf: line = salt.utils.stringutils.to_unicode(line) line = line.strip() ...
Add a module to loader. conf to make it persistent.
def _set_persistent_module(mod): ''' Add a module to loader.conf to make it persistent. ''' if not mod or mod in mod_list(True) or mod not in \ available(): return set() __salt__['file.append'](_LOADER_CONF, _LOAD_MODULE.format(mod)) return set([mod])
Remove module from loader. conf. If comment is true only comment line where module is.
def _remove_persistent_module(mod, comment): ''' Remove module from loader.conf. If comment is true only comment line where module is. ''' if not mod or mod not in mod_list(True): return set() if comment: __salt__['file.comment'](_LOADER_CONF, _MODULE_RE.format(mod)) else: ...
Return a list of all available kernel modules
def available(): ''' Return a list of all available kernel modules CLI Example: .. code-block:: bash salt '*' kmod.available ''' ret = [] for path in __salt__['file.find']('/boot/kernel', name='*.ko$'): bpath = os.path.basename(path) comps = bpath.split('.') ...
Return a dict containing information about currently loaded modules
def lsmod(): ''' Return a dict containing information about currently loaded modules CLI Example: .. code-block:: bash salt '*' kmod.lsmod ''' ret = [] for line in __salt__['cmd.run']('kldstat').splitlines(): comps = line.split() if not len(comps) > 2: ...
Return a list of the loaded module names
def mod_list(only_persist=False): ''' Return a list of the loaded module names CLI Example: .. code-block:: bash salt '*' kmod.mod_list ''' mods = set() if only_persist: if not _get_persistent_modules(): return mods for mod in _get_persistent_modules():...
Load the specified kernel module
def load(mod, persist=False): ''' Load the specified kernel module mod Name of the module to add persist Write the module to sysrc kld_modules to make it load on system reboot CLI Example: .. code-block:: bash salt '*' kmod.load bhyve ''' pre_mods = lsmod() ...
Remove the specified kernel module
def remove(mod, persist=False, comment=True): ''' Remove the specified kernel module mod Name of module to remove persist Also remove module from /boot/loader.conf comment If persist is set don't remove line from /boot/loader.conf but only comment it CLI Examp...
Returns requested Server Density authentication value from pillar.
def get_sd_auth(val, sd_auth_pillar_name='serverdensity'): ''' Returns requested Server Density authentication value from pillar. CLI Example: .. code-block:: bash salt '*' serverdensity_device.get_sd_auth <val> ''' sd_pillar = __pillar__.get(sd_auth_pillar_name) log.debug('Server...
Pops out variables from params which starts with variable_prefix.
def _clean_salt_variables(params, variable_prefix="__"): ''' Pops out variables from params which starts with `variable_prefix`. ''' list(list(map(params.pop, [k for k in params if k.startswith(variable_prefix)]))) return params
Function to create device in Server Density. For more info see the API docs __.
def create(name, **params): ''' Function to create device in Server Density. For more info, see the `API docs`__. .. __: https://apidocs.serverdensity.com/Inventory/Devices/Creating CLI Example: .. code-block:: bash salt '*' serverdensity_device.create lama salt '*' serverden...
Delete a device from Server Density. For more information see the API docs __.
def delete(device_id): ''' Delete a device from Server Density. For more information, see the `API docs`__. .. __: https://apidocs.serverdensity.com/Inventory/Devices/Deleting CLI Example: .. code-block:: bash salt '*' serverdensity_device.delete 51f7eafcdba4bb235e000ae4 ''' ...
List devices in Server Density
def ls(**params): ''' List devices in Server Density Results will be filtered by any params passed to this function. For more information, see the API docs on listing_ and searching_. .. _listing: https://apidocs.serverdensity.com/Inventory/Devices/Listing .. _searching: https://apidocs.server...
Updates device information in Server Density. For more information see the API docs __.
def update(device_id, **params): ''' Updates device information in Server Density. For more information see the `API docs`__. .. __: https://apidocs.serverdensity.com/Inventory/Devices/Updating CLI Example: .. code-block:: bash salt '*' serverdensity_device.update 51f7eafcdba4bb235e0...
Function downloads Server Density installation agent and installs sd - agent with agent_key. Optionally the agent_version would select the series to use ( defaults on the v1 one ).
def install_agent(agent_key, agent_version=1): ''' Function downloads Server Density installation agent, and installs sd-agent with agent_key. Optionally the agent_version would select the series to use (defaults on the v1 one). CLI Example: .. code-block:: bash salt '*' serverdensity...
Setup client and init datastore.
def _init_client(): '''Setup client and init datastore. ''' global client, path_prefix if client is not None: return etcd_kwargs = { 'host': __opts__.get('etcd.host', '127.0.0.1'), 'port': __opts__.get('etcd.port', 2379), 'protocol': __opts__.get('etcd.pr...
Store a key value.
def store(bank, key, data): ''' Store a key value. ''' _init_client() etcd_key = '{0}/{1}/{2}'.format(path_prefix, bank, key) try: value = __context__['serial'].dumps(data) client.write(etcd_key, base64.b64encode(value)) except Exception as exc: raise SaltCacheError( ...
Fetch a key value.
def fetch(bank, key): ''' Fetch a key value. ''' _init_client() etcd_key = '{0}/{1}/{2}'.format(path_prefix, bank, key) try: value = client.read(etcd_key).value return __context__['serial'].loads(base64.b64decode(value)) except etcd.EtcdKeyNotFound: return {} exce...
Remove the key from the cache bank with all the key content.
def flush(bank, key=None): ''' Remove the key from the cache bank with all the key content. ''' _init_client() if key is None: etcd_key = '{0}/{1}'.format(path_prefix, bank) else: etcd_key = '{0}/{1}/{2}'.format(path_prefix, bank, key) try: client.read(etcd_key) e...
Recursively walk dirs. Return flattened list of keys. r: etcd. EtcdResult
def _walk(r): ''' Recursively walk dirs. Return flattened list of keys. r: etcd.EtcdResult ''' if not r.dir: return [r.key.split('/', 3)[3]] keys = [] for c in client.read(r.key).children: keys.extend(_walk(c)) return keys
Return an iterable object containing all entries stored in the specified bank.
def ls(bank): ''' Return an iterable object containing all entries stored in the specified bank. ''' _init_client() path = '{0}/{1}'.format(path_prefix, bank) try: return _walk(client.read(path)) except Exception as exc: raise SaltCacheError( 'There was an err...
Checks if the specified bank contains the specified key.
def contains(bank, key): ''' Checks if the specified bank contains the specified key. ''' _init_client() etcd_key = '{0}/{1}/{2}'.format(path_prefix, bank, key) try: r = client.read(etcd_key) # return True for keys, not dirs return r.dir is False except etcd.EtcdKeyNo...