INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Build and properly escape a zpool command
.. note::
Input is not considered safe and will be passed through
to_auto(from_auto('input_here')), you do not need to do so
your self first. | def zpool_command(command, flags=None, opts=None, property_name=None, property_value=None,
filesystem_properties=None, pool_properties=None, target=None):
'''
Build and properly escape a zpool command
.. note::
Input is not considered safe and will be passed through
to_au... |
Parse the result of a zpool/zfs command
.. note::
Output on failure is rather predicatable.
- retcode > 0
- each 'error' is a line on stderr
- optional 'Usage:' block under those with hits
We simple check those and return a OrderedDict were
we set label = True|Fals... | def parse_command_result(res, label=None):
'''
Parse the result of a zpool/zfs command
.. note::
Output on failure is rather predicatable.
- retcode > 0
- each 'error' is a line on stderr
- optional 'Usage:' block under those with hits
We simple check those and ret... |
Read the log file and return match whole string
.. code-block:: yaml
beacons:
log:
- file: <path>
- tags:
<tag>:
regex: <pattern>
.. note::
regex matching is based on the `re`_ module
.. _re: https://docs.pyth... | def beacon(config):
'''
Read the log file and return match whole string
.. code-block:: yaml
beacons:
log:
- file: <path>
- tags:
<tag>:
regex: <pattern>
.. note::
regex matching is based on the `re`_ modul... |
Convert key/value to tree | def key_value_to_tree(data):
'''
Convert key/value to tree
'''
tree = {}
for flatkey, value in six.iteritems(data):
t = tree
keys = flatkey.split(__opts__['pepa_delimiter'])
for i, key in enumerate(keys, 1):
if i == len(keys):
t[key] = value
... |
Evaluate Pepa templates | def ext_pillar(minion_id, pillar, resource, sequence, subkey=False, subkey_only=False):
'''
Evaluate Pepa templates
'''
roots = __opts__['pepa_roots']
# Default input
inp = {}
inp['default'] = 'default'
inp['hostname'] = minion_id
if 'environment' in pillar:
inp['environmen... |
Validate Pepa templates | def validate(output, resource):
'''
Validate Pepa templates
'''
try:
import cerberus # pylint: disable=import-error
except ImportError:
log.critical('You need module cerberus in order to use validation')
return
roots = __opts__['pepa_roots']
valdir = os.path.join(r... |
Return list of disk devices | def disks():
'''
Return list of disk devices
'''
if salt.utils.platform.is_freebsd():
return _freebsd_geom()
elif salt.utils.platform.is_linux():
return _linux_disks()
elif salt.utils.platform.is_windows():
return _windows_disks()
else:
log.trace('Disk grain d... |
Return list of disk devices and work out if they are SSD or HDD. | def _linux_disks():
'''
Return list of disk devices and work out if they are SSD or HDD.
'''
ret = {'disks': [], 'SSDs': []}
for entry in glob.glob('/sys/block/*/queue/rotational'):
try:
with salt.utils.files.fopen(entry) as entry_fp:
device = entry.split('/')[3]... |
Ensure that the VirtualBox Guest Additions are installed. Uses the CD,
connected by VirtualBox.
name
The name has no functional value and is only used as a tracking
reference.
reboot : False
Restart OS to complete installation.
upgrade_os : False
Upgrade OS (to ensure th... | def additions_installed(name, reboot=False, upgrade_os=False):
'''
Ensure that the VirtualBox Guest Additions are installed. Uses the CD,
connected by VirtualBox.
name
The name has no functional value and is only used as a tracking
reference.
reboot : False
Restart OS to com... |
Ensure that the VirtualBox Guest Additions are removed. Uses the CD,
connected by VirtualBox.
To connect VirtualBox Guest Additions via VirtualBox graphical interface
press 'Host+D' ('Host' is usually 'Right Ctrl').
name
The name has no functional value and is only used as a tracking
r... | def additions_removed(name, force=False):
'''
Ensure that the VirtualBox Guest Additions are removed. Uses the CD,
connected by VirtualBox.
To connect VirtualBox Guest Additions via VirtualBox graphical interface
press 'Host+D' ('Host' is usually 'Right Ctrl').
name
The name has no fun... |
Grant access to auto-mounted shared folders to the users.
User is specified by it's name. To grant access for several users use
argument `users`.
name
Name of the user to grant access to auto-mounted shared folders to.
users
List of names of users to grant access to auto-mounted shared... | def grant_access_to_shared_folders_to(name, users=None):
'''
Grant access to auto-mounted shared folders to the users.
User is specified by it's name. To grant access for several users use
argument `users`.
name
Name of the user to grant access to auto-mounted shared folders to.
users
... |
Perform a lightweight check to see if the master daemon is running
Note, this will return an invalid success if the master crashed or was
not shut down cleanly. | def _is_master_running(self):
'''
Perform a lightweight check to see if the master daemon is running
Note, this will return an invalid success if the master crashed or was
not shut down cleanly.
'''
# Windows doesn't have IPC. Assume the master is running.
# At w... |
Execute the specified function in the specified client by passing the
lowstate | def run(self, low):
'''
Execute the specified function in the specified client by passing the
lowstate
'''
# Eauth currently requires a running daemon and commands run through
# this method require eauth so perform a quick check to raise a
# more meaningful error.... |
Run :ref:`execution modules <all-salt.modules>` asynchronously
Wraps :py:meth:`salt.client.LocalClient.run_job`.
:return: job ID | def local_async(self, *args, **kwargs):
'''
Run :ref:`execution modules <all-salt.modules>` asynchronously
Wraps :py:meth:`salt.client.LocalClient.run_job`.
:return: job ID
'''
local = salt.client.get_local_client(mopts=self.opts)
ret = local.run_job(*args, **kw... |
Run :ref:`execution modules <all-salt.modules>` synchronously
See :py:meth:`salt.client.LocalClient.cmd` for all available
parameters.
Sends a command from the master to the targeted minions. This is the
same interface that Salt's own CLI uses. Note the ``arg`` and ``kwarg``
pa... | def local(self, *args, **kwargs):
'''
Run :ref:`execution modules <all-salt.modules>` synchronously
See :py:meth:`salt.client.LocalClient.cmd` for all available
parameters.
Sends a command from the master to the targeted minions. This is the
same interface that Salt's o... |
Run :ref:`execution modules <all-salt.modules>` against subsets of minions
.. versionadded:: 2016.3.0
Wraps :py:meth:`salt.client.LocalClient.cmd_subset` | def local_subset(self, *args, **kwargs):
'''
Run :ref:`execution modules <all-salt.modules>` against subsets of minions
.. versionadded:: 2016.3.0
Wraps :py:meth:`salt.client.LocalClient.cmd_subset`
'''
local = salt.client.get_local_client(mopts=self.opts)
retur... |
Run :ref:`execution modules <all-salt.modules>` against batches of minions
.. versionadded:: 0.8.4
Wraps :py:meth:`salt.client.LocalClient.cmd_batch`
:return: Returns the result from the exeuction module for each batch of
returns | def local_batch(self, *args, **kwargs):
'''
Run :ref:`execution modules <all-salt.modules>` against batches of minions
.. versionadded:: 0.8.4
Wraps :py:meth:`salt.client.LocalClient.cmd_batch`
:return: Returns the result from the exeuction module for each batch of
... |
Run salt-ssh commands synchronously
Wraps :py:meth:`salt.client.ssh.client.SSHClient.cmd_sync`.
:return: Returns the result from the salt-ssh command | def ssh(self, *args, **kwargs):
'''
Run salt-ssh commands synchronously
Wraps :py:meth:`salt.client.ssh.client.SSHClient.cmd_sync`.
:return: Returns the result from the salt-ssh command
'''
ssh_client = salt.client.ssh.client.SSHClient(mopts=self.opts,
... |
Run `runner modules <all-salt.runners>` synchronously
Wraps :py:meth:`salt.runner.RunnerClient.cmd_sync`.
Note that runner functions must be called using keyword arguments.
Positional arguments are not supported.
:return: Returns the result from the runner module | def runner(self, fun, timeout=None, full_return=False, **kwargs):
'''
Run `runner modules <all-salt.runners>` synchronously
Wraps :py:meth:`salt.runner.RunnerClient.cmd_sync`.
Note that runner functions must be called using keyword arguments.
Positional arguments are not suppor... |
Run `runner modules <all-salt.runners>` asynchronously
Wraps :py:meth:`salt.runner.RunnerClient.cmd_async`.
Note that runner functions must be called using keyword arguments.
Positional arguments are not supported.
:return: event data and a job ID for the executed function. | def runner_async(self, fun, **kwargs):
'''
Run `runner modules <all-salt.runners>` asynchronously
Wraps :py:meth:`salt.runner.RunnerClient.cmd_async`.
Note that runner functions must be called using keyword arguments.
Positional arguments are not supported.
:return: ev... |
Run :ref:`wheel modules <all-salt.wheel>` synchronously
Wraps :py:meth:`salt.wheel.WheelClient.master_call`.
Note that wheel functions must be called using keyword arguments.
Positional arguments are not supported.
:return: Returns the result from the wheel module | def wheel(self, fun, **kwargs):
'''
Run :ref:`wheel modules <all-salt.wheel>` synchronously
Wraps :py:meth:`salt.wheel.WheelClient.master_call`.
Note that wheel functions must be called using keyword arguments.
Positional arguments are not supported.
:return: Returns t... |
Run :ref:`wheel modules <all-salt.wheel>` asynchronously
Wraps :py:meth:`salt.wheel.WheelClient.master_call`.
Note that wheel functions must be called using keyword arguments.
Positional arguments are not supported.
:return: Returns the result from the wheel module | def wheel_async(self, fun, **kwargs):
'''
Run :ref:`wheel modules <all-salt.wheel>` asynchronously
Wraps :py:meth:`salt.wheel.WheelClient.master_call`.
Note that wheel functions must be called using keyword arguments.
Positional arguments are not supported.
:return: Re... |
Pass in a raw string and load the json when it starts. This allows for a
string to start with garbage and end with json but be cleanly loaded | def find_json(raw):
'''
Pass in a raw string and load the json when it starts. This allows for a
string to start with garbage and end with json but be cleanly loaded
'''
ret = {}
lines = __split(raw)
for ind, _ in enumerate(lines):
try:
working = '\n'.join(lines[ind:])
... |
Import a json module, starting with the quick ones and going down the list) | def import_json():
'''
Import a json module, starting with the quick ones and going down the list)
'''
for fast_json in ('ujson', 'yajl', 'json'):
try:
mod = __import__(fast_json)
log.trace('loaded %s json lib', fast_json)
return mod
except ImportError... |
.. versionadded:: 2018.3.0
Wraps json.loads and prevents a traceback in the event that a bytestring is
passed to the function. (Python < 3.6 cannot load bytestrings)
You can pass an alternate json module (loaded via import_json() above)
using the _json_module argument) | def loads(s, **kwargs):
'''
.. versionadded:: 2018.3.0
Wraps json.loads and prevents a traceback in the event that a bytestring is
passed to the function. (Python < 3.6 cannot load bytestrings)
You can pass an alternate json module (loaded via import_json() above)
using the _json_module argume... |
.. versionadded:: 2018.3.0
Wraps json.dump, and assumes that ensure_ascii is False (unless explicitly
passed as True) for unicode compatibility. Note that setting it to True
will mess up any unicode characters, as they will be dumped as the string
literal version of the unicode code point.
On Pyth... | def dump(obj, fp, **kwargs):
'''
.. versionadded:: 2018.3.0
Wraps json.dump, and assumes that ensure_ascii is False (unless explicitly
passed as True) for unicode compatibility. Note that setting it to True
will mess up any unicode characters, as they will be dumped as the string
literal versio... |
User Metadata | def _user_mdata(mdata_list=None, mdata_get=None):
'''
User Metadata
'''
grains = {}
if not mdata_list:
mdata_list = salt.utils.path.which('mdata-list')
if not mdata_get:
mdata_get = salt.utils.path.which('mdata-get')
if not mdata_list or not mdata_get:
return grain... |
SDC Metadata specified by there specs
https://eng.joyent.com/mdata/datadict.html | def _sdc_mdata(mdata_list=None, mdata_get=None):
'''
SDC Metadata specified by there specs
https://eng.joyent.com/mdata/datadict.html
'''
grains = {}
sdc_text_keys = [
'uuid',
'server_uuid',
'datacenter_name',
'hostname',
'dns_domain',
]
sdc_json_k... |
Grains for backwards compatibility
Remove this function in Neon | def _legacy_grains(grains):
'''
Grains for backwards compatibility
Remove this function in Neon
'''
# parse legacy sdc grains
if 'mdata' in grains and 'sdc' in grains['mdata']:
if 'server_uuid' not in grains['mdata']['sdc'] or 'FAILURE' in grains['mdata']['sdc']['server_uuid']:
... |
Provide grains from the SmartOS metadata | def mdata():
'''
Provide grains from the SmartOS metadata
'''
grains = {}
mdata_list = salt.utils.path.which('mdata-list')
mdata_get = salt.utils.path.which('mdata-get')
grains = salt.utils.dictupdate.update(grains, _user_mdata(mdata_list, mdata_get), merge_lists=True)
grains = salt.uti... |
Check xdg locations for config files | def xdg_config_dir():
'''
Check xdg locations for config files
'''
xdg_config = os.getenv('XDG_CONFIG_HOME', os.path.expanduser('~/.config'))
xdg_config_directory = os.path.join(xdg_config, 'salt')
return xdg_config_directory |
Ensure the SNS topic exists.
name
Name of the SNS topic.
subscriptions
List of SNS subscriptions.
Each subscription is a dictionary with a protocol and endpoint key:
.. code-block:: yaml
subscriptions:
- Protocol: https
Endpoint: https:/... | def topic_present(name, subscriptions=None, attributes=None,
region=None, key=None, keyid=None, profile=None):
'''
Ensure the SNS topic exists.
name
Name of the SNS topic.
subscriptions
List of SNS subscriptions.
Each subscription is a dictionary with a proto... |
Ensure the named sns topic is deleted.
name
Name of the SNS topic.
unsubscribe
If True, unsubscribe all subcriptions to the SNS topic before
deleting the SNS topic
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used... | def topic_absent(name, unsubscribe=False, region=None, key=None, keyid=None, profile=None):
'''
Ensure the named sns topic is deleted.
name
Name of the SNS topic.
unsubscribe
If True, unsubscribe all subcriptions to the SNS topic before
deleting the SNS topic
region
... |
Start the saltnado! | def start():
'''
Start the saltnado!
'''
mod_opts = __opts__.get(__virtualname__, {})
if 'num_processes' not in mod_opts:
mod_opts['num_processes'] = 1
if mod_opts['num_processes'] > 1 and mod_opts.get('debug', False) is True:
raise Exception((
'Tornado\'s debug imp... |
Checks if the named user and group are present on the minion | def _check_user(user, group):
'''
Checks if the named user and group are present on the minion
'''
err = ''
if user:
uid = __salt__['file.user_to_uid'](user)
if uid == '':
err += 'User {0} is not available '.format(user)
if group:
gid = __salt__['file.group_to... |
Performs basic sanity checks on a relative path.
Requires POSIX-compatible paths (i.e. the kind obtained through
cp.list_master or other such calls).
Ensures that the path does not contain directory transversal, and
that it does not exceed a stated maximum depth (if specified). | def _is_valid_relpath(
relpath,
maxdepth=None):
'''
Performs basic sanity checks on a relative path.
Requires POSIX-compatible paths (i.e. the kind obtained through
cp.list_master or other such calls).
Ensures that the path does not contain directory transversal, and
that it do... |
Converts a path from the form received via salt master to the OS's native
path format. | def _salt_to_os_path(path):
'''
Converts a path from the form received via salt master to the OS's native
path format.
'''
return os.path.normpath(path.replace(posixpath.sep, os.path.sep)) |
Generate the list of files managed by a recurse state | def _gen_recurse_managed_files(
name,
source,
keep_symlinks=False,
include_pat=None,
exclude_pat=None,
maxdepth=None,
include_empty=False,
**kwargs):
'''
Generate the list of files managed by a recurse state
'''
# Convert a relative path g... |
Generate the list of files that need to be kept when a dir based function
like directory or recurse has a clean. | def _gen_keep_files(name, require, walk_d=None):
'''
Generate the list of files that need to be kept when a dir based function
like directory or recurse has a clean.
'''
def _is_child(path, directory):
'''
Check whether ``path`` is child of ``directory``
'''
path = os... |
Compile a list of valid keep files (and directories).
Used by _clean_dir() | def _find_keep_files(root, keep):
'''
Compile a list of valid keep files (and directories).
Used by _clean_dir()
'''
real_keep = set()
real_keep.add(root)
if isinstance(keep, list):
for fn_ in keep:
if not os.path.isabs(fn_):
continue
fn_ = os.... |
Clean out all of the files and directories in a directory (root) while
preserving the files in a list (keep) and part of exclude_pat | def _clean_dir(root, keep, exclude_pat):
'''
Clean out all of the files and directories in a directory (root) while
preserving the files in a list (keep) and part of exclude_pat
'''
root = os.path.normcase(root)
real_keep = _find_keep_files(root, keep)
removed = set()
def _delete_not_ke... |
Check what changes need to be made on a directory | def _check_directory(name,
user=None,
group=None,
recurse=False,
mode=None,
file_mode=None,
clean=False,
require=False,
exclude_pat=None,
... |
Check the changes in directory metadata | def _check_dir_meta(name,
user,
group,
mode,
follow_symlinks=False):
'''
Check the changes in directory metadata
'''
try:
stats = __salt__['file.stats'](name, None, follow_symlinks)
except CommandExecutionError:
... |
Check to see if a file needs to be updated or created | def _check_touch(name, atime, mtime):
'''
Check to see if a file needs to be updated or created
'''
ret = {
'result': None,
'comment': '',
'changes': {'new': name},
}
if not os.path.exists(name):
ret['comment'] = 'File {0} is set to be created'.format(name)
el... |
Check if the symlink ownership matches the specified user and group | def _check_symlink_ownership(path, user, group, win_owner):
'''
Check if the symlink ownership matches the specified user and group
'''
cur_user, cur_group = _get_symlink_ownership(path)
if salt.utils.platform.is_windows():
return win_owner == cur_user
else:
return (cur_user == u... |
Set the ownership of a symlink and return a boolean indicating
success/failure | def _set_symlink_ownership(path, user, group, win_owner):
'''
Set the ownership of a symlink and return a boolean indicating
success/failure
'''
if salt.utils.platform.is_windows():
try:
salt.utils.win_dacl.set_owner(path, win_owner)
except CommandExecutionError:
... |
Check the symlink function | def _symlink_check(name, target, force, user, group, win_owner):
'''
Check the symlink function
'''
changes = {}
if not os.path.exists(name) and not __salt__['file.is_link'](name):
changes['new'] = name
return None, 'Symlink {0} to {1} is set for creation'.format(
name, t... |
Silly little function to give us a standard tuple list for sources and
source_hashes | def _unify_sources_and_hashes(source=None, source_hash=None,
sources=None, source_hashes=None):
'''
Silly little function to give us a standard tuple list for sources and
source_hashes
'''
if sources is None:
sources = []
if source_hashes is None:
s... |
ensure ``arg`` is a list of strings | def _validate_str_list(arg):
'''
ensure ``arg`` is a list of strings
'''
if isinstance(arg, six.binary_type):
ret = [salt.utils.stringutils.to_unicode(arg)]
elif isinstance(arg, six.string_types):
ret = [arg]
elif isinstance(arg, Iterable) and not isinstance(arg, Mapping):
... |
Set the ownership of a shortcut and return a boolean indicating
success/failure | def _set_shortcut_ownership(path, user):
'''
Set the ownership of a shortcut and return a boolean indicating
success/failure
'''
try:
__salt__['file.lchown'](path, user)
except OSError:
pass
return _check_shortcut_ownership(path, user) |
Check the shortcut function | def _shortcut_check(name,
target,
arguments,
working_dir,
description,
icon_location,
force,
user):
'''
Check the shortcut function
'''
changes = {}
if not os.p... |
Helper function for creating directories when the ``makedirs`` option is set
to ``True``. Handles Unix and Windows based systems
.. versionadded:: 2017.7.8
Args:
name (str): The directory path to create
user (str): The linux user to own the directory
group (str): The linux group to... | def _makedirs(name,
user=None,
group=None,
dir_mode=None,
win_owner=None,
win_perms=None,
win_deny_perms=None,
win_inheritance=None):
'''
Helper function for creating directories when the ``makedirs`` option is set... |
Make sure that the named file or directory is absent. If it exists, it will
be deleted. This will work to reverse any of the functions in the file
state module. If a directory is supplied, it will be recursively deleted.
name
The path which should be deleted | def absent(name,
**kwargs):
'''
Make sure that the named file or directory is absent. If it exists, it will
be deleted. This will work to reverse any of the functions in the file
state module. If a directory is supplied, it will be recursively deleted.
name
The path which should ... |
Remove unwanted files based on specific criteria. Multiple criteria
are OR’d together, so a file that is too large but is not old enough
will still get tidied.
If neither age nor size is given all files which match a pattern in
matches will be removed.
name
The directory tree that should b... | def tidied(name,
age=0,
matches=None,
rmdirs=False,
size=0,
**kwargs):
'''
Remove unwanted files based on specific criteria. Multiple criteria
are OR’d together, so a file that is too large but is not old enough
will still get tidied.
If neithe... |
Verify that the named file or directory is present or exists.
Ensures pre-requisites outside of Salt's purview
(e.g., keytabs, private keys, etc.) have been previously satisfied before
deployment.
This function does not create the file if it doesn't exist, it will return
an error.
name
... | def exists(name,
**kwargs):
'''
Verify that the named file or directory is present or exists.
Ensures pre-requisites outside of Salt's purview
(e.g., keytabs, private keys, etc.) have been previously satisfied before
deployment.
This function does not create the file if it doesn't ex... |
r'''
Manage a given file, this function allows for a file to be downloaded from
the salt master and potentially run through a templating system.
name
The location of the file to manage, as an absolute path.
source
The source file to download to the minion, this source file can be
... | def managed(name,
source=None,
source_hash='',
source_hash_name=None,
keep_source=True,
user=None,
group=None,
mode=None,
attrs=None,
template=None,
makedirs=False,
dir_mode=None,
... |
Converse *recurse* definition to a set of strings.
Raises TypeError or ValueError when *recurse* has wrong structure. | def _get_recurse_set(recurse):
'''
Converse *recurse* definition to a set of strings.
Raises TypeError or ValueError when *recurse* has wrong structure.
'''
if not recurse:
return set()
if not isinstance(recurse, list):
raise TypeError('"recurse" must be formed as a list of stri... |
Walk the directory tree under root up till reaching max_depth.
With max_depth=None (default), do not limit depth. | def _depth_limited_walk(top, max_depth=None):
'''
Walk the directory tree under root up till reaching max_depth.
With max_depth=None (default), do not limit depth.
'''
for root, dirs, files in salt.utils.path.os_walk(top):
if max_depth is not None:
rel_depth = root.count(os.path.... |
Recurse through a subdirectory on the master and copy said subdirectory
over to the specified path.
name
The directory to set the recursion in
source
The source directory, this directory is located on the salt master file
server and is specified with the salt:// protocol. If the di... | def recurse(name,
source,
keep_source=True,
clean=False,
require=None,
user=None,
group=None,
dir_mode=None,
file_mode=None,
sym_mode=None,
template=None,
context=None,
replace... |
Apply retention scheduling to backup storage directory.
.. versionadded:: 2016.11.0
:param name:
The filesystem path to the directory containing backups to be managed.
:param retain:
Delete the backups, except for the ones we want to keep.
The N below should be an integer but may ... | def retention_schedule(name, retain, strptime_format=None, timezone=None):
'''
Apply retention scheduling to backup storage directory.
.. versionadded:: 2016.11.0
:param name:
The filesystem path to the directory containing backups to be managed.
:param retain:
Delete the backups,... |
Line-based editing of a file.
.. versionadded:: 2015.8.0
:param name:
Filesystem path to the file to be edited.
:param content:
Content of the line. Allowed to be empty if mode=delete.
:param match:
Match the target line for an action by
a fragment of a string or regu... | def line(name, content=None, match=None, mode=None, location=None,
before=None, after=None, show_changes=True, backup=False,
quiet=False, indent=True, create=False, user=None,
group=None, file_mode=None):
'''
Line-based editing of a file.
.. versionadded:: 2015.8.0
:param na... |
r'''
Maintain an edit in a file.
.. versionadded:: 0.17.0
name
Filesystem path to the file to be edited. If a symlink is specified, it
will be resolved to its target.
pattern
A regular expression, to be matched using Python's
:py:func:`re.search`.
.. note::
... | def replace(name,
pattern,
repl,
count=0,
flags=8,
bufsize=1,
append_if_not_found=False,
prepend_if_not_found=False,
not_found_content=None,
backup='.bak',
show_changes=True,
ignore_if_mis... |
Key/Value based editing of a file.
.. versionadded:: Neon
This function differs from ``file.replace`` in that it is able to search for
keys, followed by a customizable separator, and replace the value with the
given value. Should the value be the same as the one already in the file, no
changes wil... | def keyvalue(
name,
key=None,
value=None,
key_values=None,
separator="=",
append_if_not_found=False,
prepend_if_not_found=False,
search_only=False,
show_changes=True,
ignore_if_missing=False,
count=1,
uncomment=None,
... |
Maintain an edit in a file in a zone delimited by two line markers
.. versionadded:: 2014.1.0
.. versionchanged:: 2017.7.5,2018.3.1
``append_newline`` argument added. Additionally, to improve
idempotence, if the string represented by ``marker_end`` is found in
the middle of the line, th... | def blockreplace(
name,
marker_start='#-- start managed zone --',
marker_end='#-- end managed zone --',
source=None,
source_hash=None,
template='jinja',
sources=None,
source_hashes=None,
defaults=None,
context=None,
content='',
... |
Comment out specified lines in a file.
name
The full path to the file to be edited
regex
A regular expression used to find the lines that are to be commented;
this pattern will be wrapped in parenthesis and will move any
preceding/trailing ``^`` or ``$`` characters outside the p... | def comment(name, regex, char='#', backup='.bak'):
'''
Comment out specified lines in a file.
name
The full path to the file to be edited
regex
A regular expression used to find the lines that are to be commented;
this pattern will be wrapped in parenthesis and will move any
... |
Uncomment specified commented lines in a file
name
The full path to the file to be edited
regex
A regular expression used to find the lines that are to be uncommented.
This regex should not include the comment character. A leading ``^``
character will be stripped for convenience... | def uncomment(name, regex, char='#', backup='.bak'):
'''
Uncomment specified commented lines in a file
name
The full path to the file to be edited
regex
A regular expression used to find the lines that are to be uncommented.
This regex should not include the comment character. A... |
Ensure that some text appears at the end of a file.
The text will not be appended if it already exists in the file.
A single string of text or a list of strings may be appended.
name
The location of the file to append to.
text
The text to be appended, which can be a single string or a... | def append(name,
text=None,
makedirs=False,
source=None,
source_hash=None,
template='jinja',
sources=None,
source_hashes=None,
defaults=None,
context=None,
ignore_whitespace=True):
'''
Ensure that some ... |
Ensure that a patch has been applied to the specified file or directory
.. versionchanged:: 2019.2.0
The ``hash`` and ``dry_run_first`` options are now ignored, as the
logic which determines whether or not the patch has already been
applied no longer requires them. Additionally, this state ... | def patch(name,
source=None,
source_hash=None,
source_hash_name=None,
skip_verify=False,
template=None,
context=None,
defaults=None,
options='',
reject_file=None,
strip=None,
saltenv=None,
**kwargs):
... |
Replicate the 'nix "touch" command to create a new empty
file or update the atime and mtime of an existing file.
Note that if you just want to create a file and don't care about atime or
mtime, you should use ``file.managed`` instead, as it is more
feature-complete. (Just leave out the ``source``/``te... | def touch(name, atime=None, mtime=None, makedirs=False):
'''
Replicate the 'nix "touch" command to create a new empty
file or update the atime and mtime of an existing file.
Note that if you just want to create a file and don't care about atime or
mtime, you should use ``file.managed`` instead, as ... |
If the file defined by the ``source`` option exists on the minion, copy it
to the named path. The file will not be overwritten if it already exists,
unless the ``force`` option is set to ``True``.
.. note::
This state only copies files from one location on a minion to another
location on th... | def copy_(name,
source,
force=False,
makedirs=False,
preserve=False,
user=None,
group=None,
mode=None,
subdir=False,
**kwargs):
'''
If the file defined by the ``source`` option exists on the minion, copy it
to the name... |
If the source file exists on the system, rename it to the named file. The
named file will not be overwritten if it already exists unless the force
option is set to True.
name
The location of the file to rename to
source
The location of the file to move to the location specified with na... | def rename(name, source, force=False, makedirs=False, **kwargs):
'''
If the source file exists on the system, rename it to the named file. The
named file will not be overwritten if it already exists unless the force
option is set to True.
name
The location of the file to rename to
sour... |
Prepare accumulator which can be used in template in file.managed state.
Accumulator dictionary becomes available in template. It can also be used
in file.blockreplace.
name
Accumulator name
filename
Filename which would receive this accumulator (see file.managed state
document... | def accumulated(name, filename, text, **kwargs):
'''
Prepare accumulator which can be used in template in file.managed state.
Accumulator dictionary becomes available in template. It can also be used
in file.blockreplace.
name
Accumulator name
filename
Filename which would rece... |
Serializes dataset and store it into managed file. Useful for sharing
simple configuration files.
name
The location of the file to create
dataset
The dataset that will be serialized
dataset_pillar
Operates like ``dataset``, but draws from a value stored in pillar,
usin... | def serialize(name,
dataset=None,
dataset_pillar=None,
user=None,
group=None,
mode=None,
backup='',
makedirs=False,
show_changes=True,
create=True,
merge_if_exists=False,
... |
Create a special file similar to the 'nix mknod command. The supported
device types are ``p`` (fifo pipe), ``c`` (character device), and ``b``
(block device). Provide the major and minor numbers when specifying a
character device or block device. A fifo pipe does not require this
information. The comman... | def mknod(name, ntype, major=0, minor=0, user=None, group=None, mode='0600'):
'''
Create a special file similar to the 'nix mknod command. The supported
device types are ``p`` (fifo pipe), ``c`` (character device), and ``b``
(block device). Provide the major and minor numbers when specifying a
chara... |
Execute the check_cmd logic.
Return a result dict if ``check_cmd`` succeeds (check_cmd == 0)
otherwise return True | def mod_run_check_cmd(cmd, filename, **check_cmd_opts):
'''
Execute the check_cmd logic.
Return a result dict if ``check_cmd`` succeeds (check_cmd == 0)
otherwise return True
'''
log.debug('running our check_cmd')
_cmd = '{0} {1}'.format(cmd, filename)
cret = __salt__['cmd.run_all'](_c... |
Decode an encoded file and write it to disk
.. versionadded:: 2016.3.0
name
Path of the file to be written.
encoded_data
The encoded file. Either this option or ``contents_pillar`` must be
specified.
contents_pillar
A Pillar path to the encoded file. Uses the same path ... | def decode(name,
encoded_data=None,
contents_pillar=None,
encoding_type='base64',
checksum='md5'):
'''
Decode an encoded file and write it to disk
.. versionadded:: 2016.3.0
name
Path of the file to be written.
encoded_data
The encoded file. Either t... |
Create a Windows shortcut
If the file already exists and is a shortcut pointing to any location other
than the specified target, the shortcut will be replaced. If it is
a regular file or directory then the state will return False. If the
regular file or directory is desired to be replaced with a shortc... | def shortcut(
name,
target,
arguments=None,
working_dir=None,
description=None,
icon_location=None,
force=False,
backupname=None,
makedirs=False,
user=None,
**kwargs):
'''
Create a Windows shortcut
If the file already e... |
.. versionadded:: 2017.7.3
Ensures that a file is saved to the minion's cache. This state is primarily
invoked by other states to ensure that we do not re-download a source file
if we do not need to.
name
The URL of the file to be cached. To cache a file from an environment
other than ... | def cached(name,
source_hash='',
source_hash_name=None,
skip_verify=False,
saltenv='base'):
'''
.. versionadded:: 2017.7.3
Ensures that a file is saved to the minion's cache. This state is primarily
invoked by other states to ensure that we do not re-download... |
.. versionadded:: 2017.7.3
Ensures that a file is not present in the minion's cache, deleting it
if found. This state is primarily invoked by other states to ensure
that a fresh copy is fetched.
name
The URL of the file to be removed from cache. To remove a file from
cache in an enviro... | def not_cached(name, saltenv='base'):
'''
.. versionadded:: 2017.7.3
Ensures that a file is not present in the minion's cache, deleting it
if found. This state is primarily invoked by other states to ensure
that a fresh copy is fetched.
name
The URL of the file to be removed from cache... |
Return the rendered script | def __render_script(path, vm_=None, opts=None, minion=''):
'''
Return the rendered script
'''
log.info('Rendering deploy script: %s', path)
try:
with salt.utils.files.fopen(path, 'r') as fp_:
template = Template(salt.utils.stringutils.to_unicode(fp_.read()))
return si... |
Return a dictionary with gateway options. The result is used
to provide arguments to __ssh_gateway_arguments method. | def __ssh_gateway_config_dict(gateway):
'''
Return a dictionary with gateway options. The result is used
to provide arguments to __ssh_gateway_arguments method.
'''
extended_kwargs = {}
if gateway:
extended_kwargs['ssh_gateway'] = gateway['ssh_gateway']
extended_kwargs['ssh_gatew... |
Return ProxyCommand configuration string for ssh/scp command.
All gateway options should not include quotes (' or "). To support
future user configuration, please make sure to update the dictionary
from __ssh_gateway_config_dict and get_ssh_gateway_config (ec2.py) | def __ssh_gateway_arguments(kwargs):
'''
Return ProxyCommand configuration string for ssh/scp command.
All gateway options should not include quotes (' or "). To support
future user configuration, please make sure to update the dictionary
from __ssh_gateway_config_dict and get_ssh_gateway_config (e... |
Return the script as a string for the specific os | def os_script(os_, vm_=None, opts=None, minion=''):
'''
Return the script as a string for the specific os
'''
if minion:
minion = salt_config_to_yaml(minion)
if os.path.isabs(os_):
# The user provided an absolute path to the deploy script, let's use it
return __render_script... |
Generate Salt minion keys and return them as PEM file strings | def gen_keys(keysize=2048):
'''
Generate Salt minion keys and return them as PEM file strings
'''
# Mandate that keys are at least 2048 in size
if keysize < 2048:
keysize = 2048
tdir = tempfile.mkdtemp()
salt.crypt.gen_keys(tdir, 'minion', keysize)
priv_path = os.path.join(tdir,... |
This method removes a specified key from the accepted keys dir | def remove_key(pki_dir, id_):
'''
This method removes a specified key from the accepted keys dir
'''
key = os.path.join(pki_dir, 'minions', id_)
if os.path.isfile(key):
os.remove(key)
log.debug('Deleted \'%s\'', key) |
Rename a key, when an instance has also been renamed | def rename_key(pki_dir, id_, new_id):
'''
Rename a key, when an instance has also been renamed
'''
oldkey = os.path.join(pki_dir, 'minions', id_)
newkey = os.path.join(pki_dir, 'minions', new_id)
if os.path.isfile(oldkey):
os.rename(oldkey, newkey) |
Return a minion's configuration for the provided options and VM | def minion_config(opts, vm_):
'''
Return a minion's configuration for the provided options and VM
'''
# Don't start with a copy of the default minion opts; they're not always
# what we need. Some default options are Null, let's set a reasonable default
minion = {
'master': 'salt',
... |
Return a master's configuration for the provided options and VM | def master_config(opts, vm_):
'''
Return a master's configuration for the provided options and VM
'''
# Let's get a copy of the salt master default options
master = copy.deepcopy(salt.config.DEFAULT_MASTER_OPTS)
# Some default options are Null, let's set a reasonable default
master.update(
... |
Return a salt configuration dictionary, master or minion, as a yaml dump | def salt_config_to_yaml(configuration, line_break='\n'):
'''
Return a salt configuration dictionary, master or minion, as a yaml dump
'''
return salt.utils.yaml.safe_dump(
configuration,
line_break=line_break,
default_flow_style=False) |
This is the primary entry point for logging into any system (POSIX or
Windows) to install Salt. It will make the decision on its own as to which
deploy function to call. | def bootstrap(vm_, opts=None):
'''
This is the primary entry point for logging into any system (POSIX or
Windows) to install Salt. It will make the decision on its own as to which
deploy function to call.
'''
if opts is None:
opts = __opts__
deploy_config = salt.config.get_cloud_conf... |
Return the ssh_usernames. Defaults to a built-in list of users for trying. | def ssh_usernames(vm_, opts, default_users=None):
'''
Return the ssh_usernames. Defaults to a built-in list of users for trying.
'''
if default_users is None:
default_users = ['root']
usernames = salt.config.get_cloud_config_value(
'ssh_username', vm_, opts
)
if not isinsta... |
Wait until a function finishes, or times out | def wait_for_fun(fun, timeout=900, **kwargs):
'''
Wait until a function finishes, or times out
'''
start = time.time()
log.debug('Attempting function %s', fun)
trycount = 0
while True:
trycount += 1
try:
response = fun(**kwargs)
if not isinstance(respo... |
Wait until a connection to the specified port can be made on a specified
host. This is usually port 22 (for SSH), but in the case of Windows
installations, it might be port 445 (for psexec). It may also be an
alternate port for SSH, depending on the base image. | def wait_for_port(host, port=22, timeout=900, gateway=None):
'''
Wait until a connection to the specified port can be made on a specified
host. This is usually port 22 (for SSH), but in the case of Windows
installations, it might be port 445 (for psexec). It may also be an
alternate port for SSH, de... |
Run a command remotly via the winexe executable | def run_winexe_command(cmd, args, host, username, password, port=445):
'''
Run a command remotly via the winexe executable
'''
creds = "-U '{0}%{1}' //{2}".format(
username,
password,
host
)
logging_creds = "-U '{0}%XXX-REDACTED-XXX' //{1}".format(
username,
... |
Run a command remotly using the psexec protocol | def run_psexec_command(cmd, args, host, username, password, port=445):
'''
Run a command remotly using the psexec protocol
'''
if has_winexe() and not HAS_PSEXEC:
ret_code = run_winexe_command(cmd, args, host, username, password, port)
return None, None, ret_code
service_name = 'PS-E... |
Wait until winexe connection can be established. | def wait_for_winexe(host, port, username, password, timeout=900):
'''
Wait until winexe connection can be established.
'''
start = time.time()
log.debug(
'Attempting winexe connection to host %s on port %s',
host, port
)
try_count = 0
while True:
try_count += 1
... |
Wait until psexec connection can be established. | def wait_for_psexecsvc(host, port, username, password, timeout=900):
'''
Wait until psexec connection can be established.
'''
if has_winexe() and not HAS_PSEXEC:
return wait_for_winexe(host, port, username, password, timeout)
start = time.time()
try_count = 0
while True:
try_... |
Wait until WinRM connection can be established. | def wait_for_winrm(host, port, username, password, timeout=900, use_ssl=True, verify=True):
'''
Wait until WinRM connection can be established.
'''
# Ensure the winrm service is listening before attempting to connect
wait_for_port(host=host, port=port, timeout=timeout)
start = time.time()
l... |
Check if the windows credentials are valid | def validate_windows_cred_winexe(host,
username='Administrator',
password=None,
retries=10,
retry_delay=1):
'''
Check if the windows credentials are valid
'''
cmd = "winexe -U '{0}%{1}' //{2} \"hostna... |
Check if the windows credentials are valid | def validate_windows_cred(host,
username='Administrator',
password=None,
retries=10,
retry_delay=1):
'''
Check if the windows credentials are valid
'''
for i in range(retries):
ret_code = 1
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.