INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Run: ref: execution modules <all - salt. modules > synchronously | 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 | 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 | 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 | 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 | 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 | 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 | 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 | 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 | 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 | 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. | 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. | 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. | 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 what changes need to be made on a directory | def _check_directory_win(name,
win_owner=None,
win_perms=None,
win_deny_perms=None,
win_inheritance=None,
win_perms_reset=None):
'''
Check what changes need to be made on a directory
... |
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... |
Iterate a list of sources and process them as templates. Returns a list of chunks containing the rendered templates. | def _get_template_texts(source_list=None,
template='jinja',
defaults=None,
context=None,
**kwargs):
'''
Iterate a list of sources and process them as templates.
Returns a list of 'chunks' containing the rendered ... |
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 | 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... |
Create a symbolic link ( symlink soft link ) | def symlink(
name,
target,
force=False,
backupname=None,
makedirs=False,
user=None,
group=None,
copy_target_user=False,
copy_target_group=False,
mode=None,
win_owner=None,
win_perms=None,
win_deny_perms=None,
... |
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. | 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. | 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. | 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. | 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. | 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.... |
r Ensure that a named directory is present and has the right perms | def directory(name,
user=None,
group=None,
recurse=None,
max_depth=None,
dir_mode=None,
file_mode=None,
makedirs=False,
clean=False,
require=None,
exclude_pat=None,
f... |
Recurse through a subdirectory on the master and copy said subdirectory over to the specified path. | 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. | 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. | 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. | 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. | 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 | 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. | 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 | 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. | 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 | 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. | 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. | 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. | 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. | 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. | 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 command will create the necessa... | 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. | 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 | 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 | 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 | 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 | 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. | 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,... |
If the master config was available then we will have a pki_dir key in the opts directory this method places the pub key in the accepted keys dir and removes it from the unaccepted keys dir if that is the case. | def accept_key(pki_dir, pub, id_):
'''
If the master config was available then we will have a pki_dir key in
the opts directory, this method places the pub key in the accepted
keys dir and removes it from the unaccepted keys dir if that is the case.
'''
for key_dir in 'minions', 'minions_pre', '... |
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
... |
Wait until ssh connection can be accessed via password or ssh key | def wait_for_passwd(host, port=22, ssh_timeout=15, username='root',
password=None, key_filename=None, maxtries=15,
trysleep=1, display_ssh_output=True, gateway=None,
known_hosts_file='/dev/null', hard_timeout=None):
'''
Wait until ssh connection can be... |
Copy the install files to a remote Windows box and execute them | def deploy_windows(host,
port=445,
timeout=900,
username='Administrator',
password=None,
name=None,
sock_dir=None,
conf_file=None,
start_action=None,
... |
Copy a deploy script to a remote server execute it and remove it | def deploy_script(host,
port=22,
timeout=900,
username='root',
password=None,
key_filename=None,
script=None,
name=None,
sock_dir=None,
provider=None,
... |
Run the inline script commands one by one: ** kwargs: catch all other things we may get but don t actually need/ use | def run_inline_script(host,
name=None,
port=22,
timeout=900,
username='root',
key_filename=None,
inline_script=None,
ssh_timeout=15,
display_ssh... |
Accept a tag a dict and a list of default keys to return from the dict and check them against the cloud configuration for that tag | def filter_event(tag, data, defaults):
'''
Accept a tag, a dict and a list of default keys to return from the dict, and
check them against the cloud configuration for that tag
'''
ret = {}
keys = []
use_defaults = True
for ktag in __opts__.get('filter_events', {}):
if tag != kta... |
Fire deploy action | def fire_event(key, msg, tag, sock_dir, args=None, transport='zeromq'):
'''
Fire deploy action
'''
event = salt.utils.event.get_event(
'master',
sock_dir,
transport,
listen=False)
try:
event.fire_event(msg, tag)
except ValueError:
# We're using at... |
Use scp or sftp to copy a file to a server | def scp_file(dest_path, contents=None, kwargs=None, local_file=None):
'''
Use scp or sftp to copy a file to a server
'''
file_to_upload = None
try:
if contents is not None:
try:
tmpfd, file_to_upload = tempfile.mkstemp()
os.write(tmpfd, contents)
... |
Copies a file to the remote SSH target using either sftp or scp as configured. | def ssh_file(opts, dest_path, contents=None, kwargs=None, local_file=None):
'''
Copies a file to the remote SSH target using either sftp or scp, as
configured.
'''
if opts.get('file_transport', 'sftp') == 'sftp':
return sftp_file(dest_path, contents, kwargs, local_file)
return scp_file(d... |
Wrapper for commands to be run against Windows boxes | def win_cmd(command, **kwargs):
'''
Wrapper for commands to be run against Windows boxes
'''
logging_command = kwargs.get('logging_command', None)
try:
proc = NonBlockingPopen(
command,
shell=True,
stderr=subprocess.PIPE,
stdout=subprocess.PIP... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.