INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
.. versionadded:: 2015. 5. 0
def upgrade_available(pkg, bin_env=None, user=None, cwd=None): ''' .. versionadded:: 2015.5.0 Check whether or not an upgrade is available for a given package CLI Example: .. code-block:: bash salt '*' pip.upgrade_availabl...
.. versionadded:: 2015. 5. 0
def upgrade(bin_env=None, user=None, cwd=None, use_vt=False): ''' .. versionadded:: 2015.5.0 Upgrades outdated pip packages. .. note:: On Windows you can't update salt from pip using salt, so salt will be skipped Returns a dict containing the ch...
.. versionadded:: 2017. 7. 3
def list_all_versions(pkg, bin_env=None, include_alpha=False, include_beta=False, include_rc=False, user=None, cwd=None, index_url=None, extra_i...
Sanity checking for the specified SSL certificates
def verify_certs(*args): ''' Sanity checking for the specified SSL certificates ''' msg = ("Could not find a certificate: {0}\n" "If you want to quickly generate a self-signed certificate, " "use the tls.create_self_signed_cert function in Salt") for arg in args: if ...
Start the server loop
def start(): ''' Start the server loop ''' from . import app root, apiopts, conf = app.get_app(__opts__) if not apiopts.get('disable_ssl', False): if 'ssl_crt' not in apiopts or 'ssl_key' not in apiopts: logger.error("Not starting '%s'. Options 'ssl_crt' and " ...
Get the os architecture using rpm -- eval
def get_osarch(): ''' Get the os architecture using rpm --eval ''' if salt.utils.path.which('rpm'): ret = subprocess.Popen( 'rpm --eval "%{_host_cpu}"', shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communi...
Returns True if both the OS arch and the passed arch are 32 - bit
def check_32(arch, osarch=None): ''' Returns True if both the OS arch and the passed arch are 32-bit ''' if osarch is None: osarch = get_osarch() return all(x in ARCHES_32 for x in (osarch, arch))
Build and return a pkginfo namedtuple
def pkginfo(name, version, arch, repoid, install_date=None, install_date_time_t=None): ''' Build and return a pkginfo namedtuple ''' pkginfo_tuple = collections.namedtuple( 'PkgInfo', ('name', 'version', 'arch', 'repoid', 'install_date', 'install_date_time_t') ) return p...
Resolve the package name and arch into a unique name referred to by salt. For example on a 64 - bit OS a 32 - bit package will be pkgname. i386.
def resolve_name(name, arch, osarch=None): ''' Resolve the package name and arch into a unique name referred to by salt. For example, on a 64-bit OS, a 32-bit package will be pkgname.i386. ''' if osarch is None: osarch = get_osarch() if not check_32(arch, osarch) and arch not in (ARCHMA...
A small helper to parse an rpm/ repoquery command s output. Returns a pkginfo namedtuple.
def parse_pkginfo(line, osarch=None): ''' A small helper to parse an rpm/repoquery command's output. Returns a pkginfo namedtuple. ''' try: name, epoch, version, release, arch, repoid, install_time = line.split('_|-') # Handle unpack errors (should never happen with the queryformat we ar...
Given a list of comments strings a single comment or a single string return a single string of text containing all of the comments prepending the # and joining with newlines as necessary.
def combine_comments(comments): ''' Given a list of comments, strings, a single comment or a single string, return a single string of text containing all of the comments, prepending the '#' and joining with newlines as necessary. ''' if not isinstance(comments, list): comments = [comment...
Split the package version string into epoch version and release. Return this as tuple.
def version_to_evr(verstring): ''' Split the package version string into epoch, version and release. Return this as tuple. The epoch is always not empty. The version and the release can be an empty string if such a component could not be found in the version string. "2:1.0-1.2" => ('2', '1.0',...
Ensure the security group exists with the specified rules.
def present( name, description, vpc_id=None, vpc_name=None, rules=None, rules_egress=None, delete_ingress_rules=True, delete_egress_rules=True, region=None, key=None, keyid=None, profile=None, tags=None): ''' ...
given a group name or a group name and vpc id ( or vpc name ): 1. determine if the group exists 2. if the group does not exist creates the group 3. return the group s configuration and any changes made
def _security_group_present(name, description, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' given a group name or a group name and vpc id (or vpc name): 1. determine if the group exists 2. if the group does not exist, creates the group ...
Split rules with lists into individual rules.
def _split_rules(rules): ''' Split rules with lists into individual rules. We accept some attributes as lists or strings. The data we get back from the execution module lists rules as individual rules. We need to split the provided rules into individual rules to compare them. ''' split = []...
Check to see if two rules are the same. Needed to compare rules fetched from boto since they may not completely match rules defined in sls files but may be functionally equivalent.
def _check_rule(rule, _rule): ''' Check to see if two rules are the same. Needed to compare rules fetched from boto, since they may not completely match rules defined in sls files but may be functionally equivalent. ''' # We need to alter what Boto returns if no ports are specified # so tha...
given a list of desired rules ( rules ) and existing rules ( _rules ) return a list of rules to delete ( to_delete ) and to create ( to_create )
def _get_rule_changes(rules, _rules): ''' given a list of desired rules (rules) and existing rules (_rules) return a list of rules to delete (to_delete) and to create (to_create) ''' to_delete = [] to_create = [] # for each rule in state file # 1. validate rule # 2. determine if rule...
given a group name or group name and vpc_id ( or vpc name ): 1. get lists of desired rule changes ( using _get_rule_changes ) 2. authorize/ create rules missing rules 3. if delete_ingress_rules is True delete/ revoke non - requested rules 4. return old and new group rules
def _rules_present(name, rules, delete_ingress_rules=True, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' given a group name or group name and vpc_id (or vpc name): 1. get lists of desired rule changes (using _get_rule_changes) 2. authorize/create ru...
Ensure a security group with the specified name does not exist.
def absent( name, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Ensure a security group with the specified name does not exist. name Name of the security group. vpc_id The ID of the VPC to remov...
helper function to validate tags are correct
def _tags_present(name, tags, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' helper function to validate tags are correct ''' ret = {'result': True, 'comment': '', 'changes': {}} if tags: sg = __salt__['boto_secgroup.get_config'](name=name...
Convert ordered dictionary to a dictionary
def _ordereddict2dict(input_ordered_dict): ''' Convert ordered dictionary to a dictionary ''' return salt.utils.json.loads(salt.utils.json.dumps(input_ordered_dict))
Quorum state
def quorum(name, **kwargs): ''' Quorum state This state checks the mon daemons are in quorum. It does not alter the cluster but can be used in formula as a dependency for many cluster operations. Example usage in sls file: .. code-block:: yaml quorum: sesceph.quorum: ...
Check consul for all data
def ext_pillar(minion_id, pillar, # pylint: disable=W0613 conf): ''' Check consul for all data ''' opts = {} temp = conf target_re = re.compile('target="(.*?)"') match = target_re.search(temp) if match: opts['target'] = match.group(1) temp =...
Query consul for all keys/ values within base path
def consul_fetch(client, path): ''' Query consul for all keys/values within base path ''' # Unless the root path is blank, it needs a trailing slash for # the kv get from Consul to work as expected return client.kv.get('' if not path else path.rstrip('/') + '/', recurse=True)
Grab data from consul trim base path and remove any keys which are folders. Take the remaining data and send it to be formatted in such a way as to be used as pillar data.
def fetch_tree(client, path, expand_keys): ''' Grab data from consul, trim base path and remove any keys which are folders. Take the remaining data and send it to be formatted in such a way as to be used as pillar data. ''' _, items = consul_fetch(client, path) ret = {} has_children = re...
Perform data formatting to be used as pillar data and merge it with the current pillar data
def pillar_format(ret, keys, value, expand_keys): ''' Perform data formatting to be used as pillar data and merge it with the current pillar data ''' # if value is empty in Consul then it's None here - skip it if value is None: return ret # If value is not None then it's a string ...
Return a client object for accessing consul
def get_conn(opts, profile): ''' Return a client object for accessing consul ''' opts_pillar = opts.get('pillar', {}) opts_master = opts_pillar.get('master', {}) opts_merged = {} opts_merged.update(opts_master) opts_merged.update(opts_pillar) opts_merged.update(opts) if profil...
If dc is a string - return it as is.
def _resolve_datacenter(dc, pillarenv): ''' If ``dc`` is a string - return it as is. If it's a dict then sort it in descending order by key length and try to use keys as RegEx patterns to match against ``pillarenv``. The value for matched pattern should be a string (that can use ``str.format`` ...
Gather group members
def _gather_group_members(group, groups, users): ''' Gather group members ''' _group = __salt__['group.info'](group) if not _group: log.warning('Group %s does not exist, ignoring.', group) return for member in _group['members']: if member not in users: users...
Check time range
def _check_time_range(time_range, now): ''' Check time range ''' if _TIME_SUPPORTED: _start = dateutil_parser.parse(time_range['start']) _end = dateutil_parser.parse(time_range['end']) return bool(_start <= now <= _end) else: log.error('Dateutil is required.') ...
Read the last btmp file and return information on the failed logins
def beacon(config): ''' Read the last btmp file and return information on the failed logins ''' ret = [] users = {} groups = {} defaults = None for config_item in config: if 'users' in config_item: users = config_item['users'] if 'groups' in config_item: ...
Sprinkle with grains of salt that is convert test { id } test { host } types of strings: param config_str: The string to be sprinkled: return: The string sprinkled
def _sprinkle(config_str): ''' Sprinkle with grains of salt, that is convert 'test {id} test {host} ' types of strings :param config_str: The string to be sprinkled :return: The string sprinkled ''' parts = [x for sub in config_str.split('{') for x in sub.split('}')] for i in range(1, le...
Prepare the payload for Slack: param author_icon: The url for the thumbnail to be displayed: param title: The title of the message: param report: A dictionary with the report of the Salt function: return: The payload ready for Slack
def _generate_payload(author_icon, title, report): ''' Prepare the payload for Slack :param author_icon: The url for the thumbnail to be displayed :param title: The title of the message :param report: A dictionary with the report of the Salt function :return: The payload ready for Slack ''' ...
Generate a report of the Salt function: param ret: The Salt return: param show_tasks: Flag to show the name of the changed and failed states: return: The report
def _generate_report(ret, show_tasks): ''' Generate a report of the Salt function :param ret: The Salt return :param show_tasks: Flag to show the name of the changed and failed states :return: The report ''' returns = ret.get('return') sorted_data = sorted( returns.items(), ...
Send a message to a Slack room through a webhook: param webhook: The url of the incoming webhook: param author_icon: The thumbnail image to be displayed on the right side of the message: param title: The title of the message: param report: The report of the function state: return: Boolean if message was sent successful...
def _post_message(webhook, author_icon, title, report): ''' Send a message to a Slack room through a webhook :param webhook: The url of the incoming webhook :param author_icon: The thumbnail image to be displayed on the right side of the message :param title: The title of the message :...
Send a slack message with the data through a webhook: param ret: The Salt return: return: The result of the post
def returner(ret): ''' Send a slack message with the data through a webhook :param ret: The Salt return :return: The result of the post ''' _options = _get_options(ret) webhook = _options.get('webhook', None) show_tasks = _options.get('show_tasks') author_icon = _options.get('autho...
Checkout git repos containing: ref: Windows Software Package Definitions <windows - package - manager >.
def update_git_repos(clean=False): ''' Checkout git repos containing :ref:`Windows Software Package Definitions <windows-package-manager>`. .. important:: This function requires `Git for Windows`_ to be installed in order to work. When installing, make sure to select an installation opt...
r.. versionadded:: 2015. 8. 0
def show_sls(name, saltenv='base'): r''' .. versionadded:: 2015.8.0 Display the rendered software definition from a specific sls file in the local winrepo cache. This will parse all Jinja. Run pkg.refresh_db to pull the latest software definitions from the master. .. note:: This functi...
Return the actual lxc client version
def version(): ''' Return the actual lxc client version .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' lxc.version ''' k = 'lxc.version' if not __context__.get(k, None): cversion = __salt__['cmd.run_all']('lxc-info --version') if not cv...
Clear any lxc variables set in __context__
def _clear_context(): ''' Clear any lxc variables set in __context__ ''' for var in [x for x in __context__ if x.startswith('lxc.')]: log.trace('Clearing __context__[\'%s\']', var) __context__.pop(var, None)
Ip sorting
def _ip_sort(ip): '''Ip sorting''' idx = '001' if ip == '127.0.0.1': idx = '200' if ip == '::1': idx = '201' elif '::' in ip: idx = '100' return '{0}___{1}'.format(idx, ip)
Search which bridges are potentially available as LXC bridges
def search_lxc_bridges(): ''' Search which bridges are potentially available as LXC bridges CLI Example: .. code-block:: bash salt '*' lxc.search_lxc_bridges ''' bridges = __context__.get('lxc.bridges', None) # either match not yet called or no bridges were found # to handle ...
Interface between salt. cloud. lxc driver and lxc. init vm_ is a mapping of vm opts in the salt. cloud format as documented for the lxc driver.
def cloud_init_interface(name, vm_=None, **kwargs): ''' Interface between salt.cloud.lxc driver and lxc.init ``vm_`` is a mapping of vm opts in the salt.cloud format as documented for the lxc driver. This can be used either: - from the salt cloud driver - because you find the argument to g...
Return a random subset of cpus for the cpuset config
def _rand_cpu_str(cpu): ''' Return a random subset of cpus for the cpuset config ''' cpu = int(cpu) avail = __salt__['status.nproc']() if cpu < avail: return '0-{0}'.format(avail) to_set = set() while len(to_set) < cpu: choice = random.randint(0, avail - 1) if cho...
Network configuration defaults
def _network_conf(conf_tuples=None, **kwargs): ''' Network configuration defaults network_profile as for containers, we can either call this function either with a network_profile dict or network profile name in the kwargs nic_opts overrides or ex...
Return a list of dicts from the salt level configurations
def _config_list(conf_tuples=None, only_net=False, **kwargs): ''' Return a list of dicts from the salt level configurations conf_tuples _LXCConfig compatible list of entries which can contain - string line - tuple (lxc config param,value) - dict of one entry: {l...
Parse the nic setup inside lxc conf tuples back to a dictionary indexed by network interface
def _get_veths(net_data): ''' Parse the nic setup inside lxc conf tuples back to a dictionary indexed by network interface ''' if isinstance(net_data, dict): net_data = list(net_data.items()) nics = salt.utils.odict.OrderedDict() current_nic = salt.utils.odict.OrderedDict() no_na...
If the needed base does not exist then create it if it does exist create nothing and return the name of the base lxc container so it can be cloned.
def _get_base(**kwargs): ''' If the needed base does not exist, then create it, if it does exist create nothing and return the name of the base lxc container so it can be cloned. ''' profile = get_container_profile(copy.deepcopy(kwargs.get('profile'))) kw_overrides = copy.deepcopy(kwargs) ...
Initialize a new container.
def init(name, config=None, cpuset=None, cpushare=None, memory=None, profile=None, network_profile=None, nic_opts=None, cpu=None, autostart=True, password=None, password_encrypted=None, users=None, dnsse...
Thin wrapper to lxc. init to be used from the saltcloud lxc driver
def cloud_init(name, vm_=None, **kwargs): ''' Thin wrapper to lxc.init to be used from the saltcloud lxc driver name Name of the container may be None and then guessed from saltcloud mapping `vm_` saltcloud mapping defaults for the vm CLI Example: .. code-block:: bash ...
.. versionadded:: 2015. 5. 0
def images(dist=None): ''' .. versionadded:: 2015.5.0 List the available images for LXC's ``download`` template. dist : None Filter results to a single Linux distribution CLI Examples: .. code-block:: bash salt myminion lxc.images salt myminion lxc.images dist=centos...
.. versionadded:: 2015. 5. 0
def templates(): ''' .. versionadded:: 2015.5.0 List the available LXC template scripts installed on the minion CLI Examples: .. code-block:: bash salt myminion lxc.templates ''' try: template_scripts = os.listdir('/usr/share/lxc/templates') except OSError: re...
Create a new container.
def create(name, config=None, profile=None, network_profile=None, nic_opts=None, **kwargs): ''' Create a new container. name Name of the container config The config file to use for the container. Defaults to system-wide con...
Create a new container as a clone of another container
def clone(name, orig, profile=None, network_profile=None, nic_opts=None, **kwargs): ''' Create a new container as a clone of another container name Name of the container orig Name of the original container to be cloned profile ...
Return a list of the containers available on the minion
def ls_(active=None, cache=True, path=None): ''' Return a list of the containers available on the minion path path to the container parent directory default: /var/lib/lxc (system) .. versionadded:: 2015.8.0 active If ``True``, return only active (i.e. running) containe...
List containers classified by state
def list_(extra=False, limit=None, path=None): ''' List containers classified by state extra Also get per-container specific info. This will change the return data. Instead of returning a list of containers, a dictionary of containers and each container's output from :mod:`lxc.info ...
Raise an exception if the container does not exist
def _ensure_exists(name, path=None): ''' Raise an exception if the container does not exist ''' if not exists(name, path=path): raise CommandExecutionError( 'Container \'{0}\' does not exist'.format(name) )
If the container is not currently running start it. This function returns the state that the container was in before changing
def _ensure_running(name, no_start=False, path=None): ''' If the container is not currently running, start it. This function returns the state that the container was in before changing path path to the container parent directory default: /var/lib/lxc (system) .. versionadded:: ...
.. versionadded:: 2015. 5. 0
def restart(name, path=None, lxc_config=None, force=False): ''' .. versionadded:: 2015.5.0 Restart the named container. If the container was not running, the container will merely be started. name The name of the container path path to the container parent directory de...
Start the named container
def start(name, **kwargs): ''' Start the named container path path to the container parent directory default: /var/lib/lxc (system) .. versionadded:: 2015.8.0 lxc_config path to a lxc config file config file will be guessed from container name otherwise ...
Stop the named container
def stop(name, kill=False, path=None, use_vt=None): ''' Stop the named container path path to the container parent directory default: /var/lib/lxc (system) .. versionadded:: 2015.8.0 kill: False Do not wait for the container to stop, kill all tasks in the container. ...
Freeze the named container
def freeze(name, **kwargs): ''' Freeze the named container path path to the container parent directory default: /var/lib/lxc (system) .. versionadded:: 2015.8.0 start : False If ``True`` and the container is stopped, the container will be started before attempt...
Unfreeze the named container.
def unfreeze(name, path=None, use_vt=None): ''' Unfreeze the named container. path path to the container parent directory default: /var/lib/lxc (system) .. versionadded:: 2015.8.0 use_vt run the command through VT .. versionadded:: 2015.8.0 CLI Example: ...
Destroy the named container.
def destroy(name, stop=False, path=None): ''' Destroy the named container. .. warning:: Destroys all data associated with the container. path path to the container parent directory (default: /var/lib/lxc) .. versionadded:: 2015.8.0 stop : False If ``True``, the c...
Returns whether the named container exists.
def exists(name, path=None): ''' Returns whether the named container exists. path path to the container parent directory (default: /var/lib/lxc) .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' lxc.exists name ''' _exists = name in ls_(path...
Returns the state of a container.
def state(name, path=None): ''' Returns the state of a container. path path to the container parent directory (default: /var/lib/lxc) .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' lxc.state name ''' # Don't use _ensure_exists() here, it wi...
Returns the value of a cgroup parameter for a container
def get_parameter(name, parameter, path=None): ''' Returns the value of a cgroup parameter for a container path path to the container parent directory default: /var/lib/lxc (system) .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' lxc.get_par...
Set the value of a cgroup parameter for a container.
def set_parameter(name, parameter, value, path=None): ''' Set the value of a cgroup parameter for a container. path path to the container parent directory default: /var/lib/lxc (system) .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' lxc.set...
Returns information about a container
def info(name, path=None): ''' Returns information about a container path path to the container parent directory default: /var/lib/lxc (system) .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' lxc.info name ''' cachekey = 'lxc.info.{0...
.. versionchanged:: 2015. 5. 0 Function renamed from set_pass to set_password. Additionally this function now supports ( and defaults to using ) a password hash instead of a plaintext password.
def set_password(name, users, password, encrypted=True, path=None): ''' .. versionchanged:: 2015.5.0 Function renamed from ``set_pass`` to ``set_password``. Additionally, this function now supports (and defaults to using) a password hash instead of a plaintext password. Set the pass...
Edit LXC configuration options
def update_lxc_conf(name, lxc_conf, lxc_conf_unset, path=None): ''' Edit LXC configuration options path path to the container parent default: /var/lib/lxc (system default) .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion lxc.update_lxc_c...
.. versionchanged:: 2015. 5. 0 The dnsservers and searchdomains parameters can now be passed as a comma - separated list.
def set_dns(name, dnsservers=None, searchdomains=None, path=None): ''' .. versionchanged:: 2015.5.0 The ``dnsservers`` and ``searchdomains`` parameters can now be passed as a comma-separated list. Update /etc/resolv.confo path path to the container parent default: /var...
Determine if systemD is running
def running_systemd(name, cache=True, path=None): ''' Determine if systemD is running path path to the container parent .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' lxc.running_systemd ubuntu ''' k = 'lxc.systemd.test.{0}{1}'.format(name...
Get the operational state of a systemd based container
def systemd_running_state(name, path=None): ''' Get the operational state of a systemd based container path path to the container parent default: /var/lib/lxc (system default) .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion lxc.systemd_...
Check that the system has fully inited
def wait_started(name, path=None, timeout=300): ''' Check that the system has fully inited This is actually very important for systemD based containers see https://github.com/saltstack/salt/issues/23847 path path to the container parent default: /var/lib/lxc (system default) ...
Return True if the named container can be attached to via the lxc - attach command
def attachable(name, path=None): ''' Return True if the named container can be attached to via the lxc-attach command path path to the container parent default: /var/lib/lxc (system default) .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt 'm...
Common logic for lxc. run functions
def _run(name, cmd, output=None, no_start=False, preserve_state=True, stdin=None, python_shell=True, output_loglevel='debug', use_vt=False, path=None, ignore_retcode=False, chroot_fallback=None, keep_env='http_pr...
.. versionadded:: 2015. 8. 0
def run(name, cmd, no_start=False, preserve_state=True, stdin=None, python_shell=True, output_loglevel='debug', use_vt=False, path=None, ignore_retcode=False, chroot_fallback=False, keep_env='http_proxy,https_proxy,no_proxy'): '...
Get the MD5 checksum of a file from a container
def _get_md5(name, path): ''' Get the MD5 checksum of a file from a container ''' output = run_stdout(name, 'md5sum "{0}"'.format(path), chroot_fallback=True, ignore_retcode=True) try: return output.split()[0] except IndexError: # D...
.. versionchanged:: 2015. 8. 0 Function renamed from lxc. cp to lxc. copy_to for consistency with other container types. lxc. cp will continue to work however. For versions 2015. 2. x and earlier use lxc. cp.
def copy_to(name, source, dest, overwrite=False, makedirs=False, path=None): ''' .. versionchanged:: 2015.8.0 Function renamed from ``lxc.cp`` to ``lxc.copy_to`` for consistency with other container types. ``lxc.cp`` will continue to work, however. For versions 2015.2.x and earlier, use ...
Read in an LXC configuration file. By default returns a simple unsorted dict but can also return a more detailed structure including blank lines and comments.
def read_conf(conf_file, out_format='simple'): ''' Read in an LXC configuration file. By default returns a simple, unsorted dict, but can also return a more detailed structure including blank lines and comments. out_format: set to 'simple' if you need the old and unsupported behavior. ...
Write out an LXC configuration file
def write_conf(conf_file, conf): ''' Write out an LXC configuration file This is normally only used internally. The format of the data structure must match that which is returned from ``lxc.read_conf()``, with ``out_format`` set to ``commented``. An example might look like: .. code-block:...
Edit an LXC configuration file. If a setting is already present inside the file its value will be replaced. If it does not exist it will be appended to the end of the file. Comments and blank lines will be kept in - tact if they already exist in the file.
def edit_conf(conf_file, out_format='simple', read_only=False, lxc_config=None, **kwargs): ''' Edit an LXC configuration file. If a setting is already present inside the file, its value will be replaced. If it does not exist, it will be appended to...
Reboot a container.
def reboot(name, path=None): ''' Reboot a container. path path to the container parent default: /var/lib/lxc (system default) .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt 'minion' lxc.reboot myvm ''' ret = {'result': True, ...
Reconfigure a container.
def reconfigure(name, cpu=None, cpuset=None, cpushare=None, memory=None, profile=None, network_profile=None, nic_opts=None, bridge=None, gateway=None, autostart...
.. versionadded:: 2015. 5. 0
def apply_network_profile(name, network_profile, nic_opts=None, path=None): ''' .. versionadded:: 2015.5.0 Apply a network profile to a container network_profile profile name or default values (dict) nic_opts values to override in defaults (dict) indexed by nic card names ...
Returns a container pid. Throw an exception if the container isn t running.
def get_pid(name, path=None): ''' Returns a container pid. Throw an exception if the container isn't running. CLI Example: .. code-block:: bash salt '*' lxc.get_pid name ''' if name not in list_(limit='running', path=path): raise CommandExecutionError('Container {0} is not...
Add a veth to a container. Note: this function doesn t update the container config just add the interface at runtime
def add_veth(name, interface_name, bridge=None, path=None): ''' Add a veth to a container. Note : this function doesn't update the container config, just add the interface at runtime name Name of the container interface_name Name of the interface in the container bridge ...
Removes parameters which match the pattern from the config data
def _filter_data(self, pattern): ''' Removes parameters which match the pattern from the config data ''' removed = [] filtered = [] for param in self.data: if not param[0].startswith(pattern): filtered.append(param) else: ...
Helper to return known serializer based on pass output argument
def _get_serializer(output): ''' Helper to return known serializer based on pass output argument ''' serializers = salt.loader.serializers(__opts__) try: return getattr(serializers, output) except AttributeError: raise CommandExecutionError( "Unknown serializer '{...
Parse stdout of a command and generate an event
def start(cmd, output='json', interval=1): ''' Parse stdout of a command and generate an event The script engine will scrap stdout of the given script and generate an event based on the presence of the 'tag' key and it's value. If there is a data obj available, that will also be fired alon...
Return Bluez version from bluetoothd - v
def version(): ''' Return Bluez version from bluetoothd -v CLI Example: .. code-block:: bash salt '*' bluetoothd.version ''' cmd = 'bluetoothctl -v' out = __salt__['cmd.run'](cmd).splitlines() bluez_version = out[0] pybluez_version = '<= 0.18 (Unknown, but installed)' ...
Get the many addresses of the Bluetooth adapter
def address_(): ''' Get the many addresses of the Bluetooth adapter CLI Example: .. code-block:: bash salt '*' bluetooth.address ''' ret = {} cmd = 'hciconfig' out = __salt__['cmd.run'](cmd).splitlines() dev = '' for line in out: if line.startswith('hci'): ...
Power a bluetooth device on or off
def power(dev, mode): ''' Power a bluetooth device on or off CLI Examples: .. code-block:: bash salt '*' bluetooth.power hci0 on salt '*' bluetooth.power hci0 off ''' if dev not in address_(): raise CommandExecutionError('Invalid dev passed to bluetooth.power') if...
Enable this bluetooth device to be discoverable.
def discoverable(dev): ''' Enable this bluetooth device to be discoverable. CLI Example: .. code-block:: bash salt '*' bluetooth.discoverable hci0 ''' if dev not in address_(): raise CommandExecutionError( 'Invalid dev passed to bluetooth.discoverable' ) ...
Scan for bluetooth devices in the area
def scan(): ''' Scan for bluetooth devices in the area CLI Example: .. code-block:: bash salt '*' bluetooth.scan ''' ret = [] devices = bluetooth.discover_devices(lookup_names=True) for device in devices: ret.append({device[0]: device[1]}) return ret
Block a specific bluetooth device by BD Address
def block(bdaddr): ''' Block a specific bluetooth device by BD Address CLI Example: .. code-block:: bash salt '*' bluetooth.block DE:AD:BE:EF:CA:FE ''' if not salt.utils.validate.net.mac(bdaddr): raise CommandExecutionError( 'Invalid BD address passed to bluetooth....
Pair the bluetooth adapter with a device
def pair(address, key): ''' Pair the bluetooth adapter with a device CLI Example: .. code-block:: bash salt '*' bluetooth.pair DE:AD:BE:EF:CA:FE 1234 Where DE:AD:BE:EF:CA:FE is the address of the device to pair with, and 1234 is the passphrase. TODO: This function is currently b...
Unpair the bluetooth adapter from a device
def unpair(address): ''' Unpair the bluetooth adapter from a device CLI Example: .. code-block:: bash salt '*' bluetooth.unpair DE:AD:BE:EF:CA:FE Where DE:AD:BE:EF:CA:FE is the address of the device to unpair. TODO: This function is currently broken, as the bluez-simple-agent progra...
Send a message to an MS Teams channel.: param message: The message to send to the MS Teams channel.: param hook_url: The Teams webhook URL if not specified in the configuration.: param title: Optional title for the posted card: param theme_color: Optional hex color highlight for the posted card: return: Boolean if mess...
def post_card(message, hook_url=None, title=None, theme_color=None): ''' Send a message to an MS Teams channel. :param message: The message to send to the MS Teams channel. :param hook_url: The Teams webhook URL, if not specified in the configuration. ...