repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1 value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
saltstack/salt | salt/fileserver/hgfs.py | file_hash | def file_hash(load, fnd):
'''
Return a file hash, the hash type is set in the master config file
'''
if 'env' in load:
# "env" is not supported; Use "saltenv".
load.pop('env')
if not all(x in load for x in ('path', 'saltenv')):
return ''
ret = {'hash_type': __opts__['hash_type']}
relpath = fnd['rel']
path = fnd['path']
hashdest = os.path.join(__opts__['cachedir'],
'hgfs/hash',
load['saltenv'],
'{0}.hash.{1}'.format(relpath,
__opts__['hash_type']))
if not os.path.isfile(hashdest):
ret['hsum'] = salt.utils.hashutils.get_hash(path, __opts__['hash_type'])
with salt.utils.files.fopen(hashdest, 'w+') as fp_:
fp_.write(ret['hsum'])
return ret
else:
with salt.utils.files.fopen(hashdest, 'rb') as fp_:
ret['hsum'] = salt.utils.stringutils.to_unicode(fp_.read())
return ret | python | def file_hash(load, fnd):
'''
Return a file hash, the hash type is set in the master config file
'''
if 'env' in load:
# "env" is not supported; Use "saltenv".
load.pop('env')
if not all(x in load for x in ('path', 'saltenv')):
return ''
ret = {'hash_type': __opts__['hash_type']}
relpath = fnd['rel']
path = fnd['path']
hashdest = os.path.join(__opts__['cachedir'],
'hgfs/hash',
load['saltenv'],
'{0}.hash.{1}'.format(relpath,
__opts__['hash_type']))
if not os.path.isfile(hashdest):
ret['hsum'] = salt.utils.hashutils.get_hash(path, __opts__['hash_type'])
with salt.utils.files.fopen(hashdest, 'w+') as fp_:
fp_.write(ret['hsum'])
return ret
else:
with salt.utils.files.fopen(hashdest, 'rb') as fp_:
ret['hsum'] = salt.utils.stringutils.to_unicode(fp_.read())
return ret | [
"def",
"file_hash",
"(",
"load",
",",
"fnd",
")",
":",
"if",
"'env'",
"in",
"load",
":",
"# \"env\" is not supported; Use \"saltenv\".",
"load",
".",
"pop",
"(",
"'env'",
")",
"if",
"not",
"all",
"(",
"x",
"in",
"load",
"for",
"x",
"in",
"(",
"'path'",
... | Return a file hash, the hash type is set in the master config file | [
"Return",
"a",
"file",
"hash",
"the",
"hash",
"type",
"is",
"set",
"in",
"the",
"master",
"config",
"file"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileserver/hgfs.py#L774-L800 | train |
saltstack/salt | salt/fileserver/hgfs.py | _file_lists | def _file_lists(load, form):
'''
Return a dict containing the file lists for files and dirs
'''
if 'env' in load:
# "env" is not supported; Use "saltenv".
load.pop('env')
list_cachedir = os.path.join(__opts__['cachedir'], 'file_lists/hgfs')
if not os.path.isdir(list_cachedir):
try:
os.makedirs(list_cachedir)
except os.error:
log.critical('Unable to make cachedir %s', list_cachedir)
return []
list_cache = os.path.join(list_cachedir, '{0}.p'.format(load['saltenv']))
w_lock = os.path.join(list_cachedir, '.{0}.w'.format(load['saltenv']))
cache_match, refresh_cache, save_cache = \
salt.fileserver.check_file_list_cache(
__opts__, form, list_cache, w_lock
)
if cache_match is not None:
return cache_match
if refresh_cache:
ret = {}
ret['files'] = _get_file_list(load)
ret['dirs'] = _get_dir_list(load)
if save_cache:
salt.fileserver.write_file_list_cache(
__opts__, ret, list_cache, w_lock
)
return ret.get(form, [])
# Shouldn't get here, but if we do, this prevents a TypeError
return [] | python | def _file_lists(load, form):
'''
Return a dict containing the file lists for files and dirs
'''
if 'env' in load:
# "env" is not supported; Use "saltenv".
load.pop('env')
list_cachedir = os.path.join(__opts__['cachedir'], 'file_lists/hgfs')
if not os.path.isdir(list_cachedir):
try:
os.makedirs(list_cachedir)
except os.error:
log.critical('Unable to make cachedir %s', list_cachedir)
return []
list_cache = os.path.join(list_cachedir, '{0}.p'.format(load['saltenv']))
w_lock = os.path.join(list_cachedir, '.{0}.w'.format(load['saltenv']))
cache_match, refresh_cache, save_cache = \
salt.fileserver.check_file_list_cache(
__opts__, form, list_cache, w_lock
)
if cache_match is not None:
return cache_match
if refresh_cache:
ret = {}
ret['files'] = _get_file_list(load)
ret['dirs'] = _get_dir_list(load)
if save_cache:
salt.fileserver.write_file_list_cache(
__opts__, ret, list_cache, w_lock
)
return ret.get(form, [])
# Shouldn't get here, but if we do, this prevents a TypeError
return [] | [
"def",
"_file_lists",
"(",
"load",
",",
"form",
")",
":",
"if",
"'env'",
"in",
"load",
":",
"# \"env\" is not supported; Use \"saltenv\".",
"load",
".",
"pop",
"(",
"'env'",
")",
"list_cachedir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"__opts__",
"[",
"... | Return a dict containing the file lists for files and dirs | [
"Return",
"a",
"dict",
"containing",
"the",
"file",
"lists",
"for",
"files",
"and",
"dirs"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileserver/hgfs.py#L803-L836 | train |
saltstack/salt | salt/fileserver/hgfs.py | _get_file_list | def _get_file_list(load):
'''
Get a list of all files on the file server in a specified environment
'''
if 'env' in load:
# "env" is not supported; Use "saltenv".
load.pop('env')
if 'saltenv' not in load or load['saltenv'] not in envs():
return []
ret = set()
for repo in init():
repo['repo'].open()
ref = _get_ref(repo, load['saltenv'])
if ref:
manifest = repo['repo'].manifest(rev=ref[1])
for tup in manifest:
relpath = os.path.relpath(tup[4], repo['root'])
# Don't add files outside the hgfs_root
if not relpath.startswith('../'):
ret.add(os.path.join(repo['mountpoint'], relpath))
repo['repo'].close()
return sorted(ret) | python | def _get_file_list(load):
'''
Get a list of all files on the file server in a specified environment
'''
if 'env' in load:
# "env" is not supported; Use "saltenv".
load.pop('env')
if 'saltenv' not in load or load['saltenv'] not in envs():
return []
ret = set()
for repo in init():
repo['repo'].open()
ref = _get_ref(repo, load['saltenv'])
if ref:
manifest = repo['repo'].manifest(rev=ref[1])
for tup in manifest:
relpath = os.path.relpath(tup[4], repo['root'])
# Don't add files outside the hgfs_root
if not relpath.startswith('../'):
ret.add(os.path.join(repo['mountpoint'], relpath))
repo['repo'].close()
return sorted(ret) | [
"def",
"_get_file_list",
"(",
"load",
")",
":",
"if",
"'env'",
"in",
"load",
":",
"# \"env\" is not supported; Use \"saltenv\".",
"load",
".",
"pop",
"(",
"'env'",
")",
"if",
"'saltenv'",
"not",
"in",
"load",
"or",
"load",
"[",
"'saltenv'",
"]",
"not",
"in",... | Get a list of all files on the file server in a specified environment | [
"Get",
"a",
"list",
"of",
"all",
"files",
"on",
"the",
"file",
"server",
"in",
"a",
"specified",
"environment"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileserver/hgfs.py#L846-L868 | train |
saltstack/salt | salt/fileserver/hgfs.py | _get_dir_list | def _get_dir_list(load):
'''
Get a list of all directories on the master
'''
if 'env' in load:
# "env" is not supported; Use "saltenv".
load.pop('env')
if 'saltenv' not in load or load['saltenv'] not in envs():
return []
ret = set()
for repo in init():
repo['repo'].open()
ref = _get_ref(repo, load['saltenv'])
if ref:
manifest = repo['repo'].manifest(rev=ref[1])
for tup in manifest:
filepath = tup[4]
split = filepath.rsplit('/', 1)
while len(split) > 1:
relpath = os.path.relpath(split[0], repo['root'])
# Don't add '.'
if relpath != '.':
# Don't add files outside the hgfs_root
if not relpath.startswith('../'):
ret.add(os.path.join(repo['mountpoint'], relpath))
split = split[0].rsplit('/', 1)
repo['repo'].close()
if repo['mountpoint']:
ret.add(repo['mountpoint'])
return sorted(ret) | python | def _get_dir_list(load):
'''
Get a list of all directories on the master
'''
if 'env' in load:
# "env" is not supported; Use "saltenv".
load.pop('env')
if 'saltenv' not in load or load['saltenv'] not in envs():
return []
ret = set()
for repo in init():
repo['repo'].open()
ref = _get_ref(repo, load['saltenv'])
if ref:
manifest = repo['repo'].manifest(rev=ref[1])
for tup in manifest:
filepath = tup[4]
split = filepath.rsplit('/', 1)
while len(split) > 1:
relpath = os.path.relpath(split[0], repo['root'])
# Don't add '.'
if relpath != '.':
# Don't add files outside the hgfs_root
if not relpath.startswith('../'):
ret.add(os.path.join(repo['mountpoint'], relpath))
split = split[0].rsplit('/', 1)
repo['repo'].close()
if repo['mountpoint']:
ret.add(repo['mountpoint'])
return sorted(ret) | [
"def",
"_get_dir_list",
"(",
"load",
")",
":",
"if",
"'env'",
"in",
"load",
":",
"# \"env\" is not supported; Use \"saltenv\".",
"load",
".",
"pop",
"(",
"'env'",
")",
"if",
"'saltenv'",
"not",
"in",
"load",
"or",
"load",
"[",
"'saltenv'",
"]",
"not",
"in",
... | Get a list of all directories on the master | [
"Get",
"a",
"list",
"of",
"all",
"directories",
"on",
"the",
"master"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileserver/hgfs.py#L886-L916 | train |
saltstack/salt | salt/cache/__init__.py | factory | def factory(opts, **kwargs):
'''
Creates and returns the cache class.
If memory caching is enabled by opts MemCache class will be instantiated.
If not Cache class will be returned.
'''
if opts.get('memcache_expire_seconds', 0):
cls = MemCache
else:
cls = Cache
return cls(opts, **kwargs) | python | def factory(opts, **kwargs):
'''
Creates and returns the cache class.
If memory caching is enabled by opts MemCache class will be instantiated.
If not Cache class will be returned.
'''
if opts.get('memcache_expire_seconds', 0):
cls = MemCache
else:
cls = Cache
return cls(opts, **kwargs) | [
"def",
"factory",
"(",
"opts",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"opts",
".",
"get",
"(",
"'memcache_expire_seconds'",
",",
"0",
")",
":",
"cls",
"=",
"MemCache",
"else",
":",
"cls",
"=",
"Cache",
"return",
"cls",
"(",
"opts",
",",
"*",
"*",... | Creates and returns the cache class.
If memory caching is enabled by opts MemCache class will be instantiated.
If not Cache class will be returned. | [
"Creates",
"and",
"returns",
"the",
"cache",
"class",
".",
"If",
"memory",
"caching",
"is",
"enabled",
"by",
"opts",
"MemCache",
"class",
"will",
"be",
"instantiated",
".",
"If",
"not",
"Cache",
"class",
"will",
"be",
"returned",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cache/__init__.py#L24-L34 | train |
saltstack/salt | salt/cache/__init__.py | Cache.cache | def cache(self, bank, key, fun, loop_fun=None, **kwargs):
'''
Check cache for the data. If it is there, check to see if it needs to
be refreshed.
If the data is not there, or it needs to be refreshed, then call the
callback function (``fun``) with any given ``**kwargs``.
In some cases, the callback function returns a list of objects which
need to be processed by a second function. If that is the case, then
the second function is passed in as ``loop_fun``. Each item in the
return list from the first function will be the only argument for the
second function.
'''
expire_seconds = kwargs.get('expire', 86400) # 1 day
updated = self.updated(bank, key)
update_cache = False
if updated is None:
update_cache = True
else:
if int(time.time()) - updated > expire_seconds:
update_cache = True
data = self.fetch(bank, key)
if not data or update_cache is True:
if loop_fun is not None:
data = []
items = fun(**kwargs)
for item in items:
data.append(loop_fun(item))
else:
data = fun(**kwargs)
self.store(bank, key, data)
return data | python | def cache(self, bank, key, fun, loop_fun=None, **kwargs):
'''
Check cache for the data. If it is there, check to see if it needs to
be refreshed.
If the data is not there, or it needs to be refreshed, then call the
callback function (``fun``) with any given ``**kwargs``.
In some cases, the callback function returns a list of objects which
need to be processed by a second function. If that is the case, then
the second function is passed in as ``loop_fun``. Each item in the
return list from the first function will be the only argument for the
second function.
'''
expire_seconds = kwargs.get('expire', 86400) # 1 day
updated = self.updated(bank, key)
update_cache = False
if updated is None:
update_cache = True
else:
if int(time.time()) - updated > expire_seconds:
update_cache = True
data = self.fetch(bank, key)
if not data or update_cache is True:
if loop_fun is not None:
data = []
items = fun(**kwargs)
for item in items:
data.append(loop_fun(item))
else:
data = fun(**kwargs)
self.store(bank, key, data)
return data | [
"def",
"cache",
"(",
"self",
",",
"bank",
",",
"key",
",",
"fun",
",",
"loop_fun",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"expire_seconds",
"=",
"kwargs",
".",
"get",
"(",
"'expire'",
",",
"86400",
")",
"# 1 day",
"updated",
"=",
"self",
"... | Check cache for the data. If it is there, check to see if it needs to
be refreshed.
If the data is not there, or it needs to be refreshed, then call the
callback function (``fun``) with any given ``**kwargs``.
In some cases, the callback function returns a list of objects which
need to be processed by a second function. If that is the case, then
the second function is passed in as ``loop_fun``. Each item in the
return list from the first function will be the only argument for the
second function. | [
"Check",
"cache",
"for",
"the",
"data",
".",
"If",
"it",
"is",
"there",
"check",
"to",
"see",
"if",
"it",
"needs",
"to",
"be",
"refreshed",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cache/__init__.py#L96-L132 | train |
saltstack/salt | salt/cache/__init__.py | Cache.store | def store(self, bank, key, data):
'''
Store data using the specified module
:param bank:
The name of the location inside the cache which will hold the key
and its associated data.
:param key:
The name of the key (or file inside a directory) which will hold
the data. File extensions should not be provided, as they will be
added by the driver itself.
:param data:
The data which will be stored in the cache. This data should be
in a format which can be serialized by msgpack/json/yaml/etc.
:raises SaltCacheError:
Raises an exception if cache driver detected an error accessing data
in the cache backend (auth, permissions, etc).
'''
fun = '{0}.store'.format(self.driver)
return self.modules[fun](bank, key, data, **self._kwargs) | python | def store(self, bank, key, data):
'''
Store data using the specified module
:param bank:
The name of the location inside the cache which will hold the key
and its associated data.
:param key:
The name of the key (or file inside a directory) which will hold
the data. File extensions should not be provided, as they will be
added by the driver itself.
:param data:
The data which will be stored in the cache. This data should be
in a format which can be serialized by msgpack/json/yaml/etc.
:raises SaltCacheError:
Raises an exception if cache driver detected an error accessing data
in the cache backend (auth, permissions, etc).
'''
fun = '{0}.store'.format(self.driver)
return self.modules[fun](bank, key, data, **self._kwargs) | [
"def",
"store",
"(",
"self",
",",
"bank",
",",
"key",
",",
"data",
")",
":",
"fun",
"=",
"'{0}.store'",
".",
"format",
"(",
"self",
".",
"driver",
")",
"return",
"self",
".",
"modules",
"[",
"fun",
"]",
"(",
"bank",
",",
"key",
",",
"data",
",",
... | Store data using the specified module
:param bank:
The name of the location inside the cache which will hold the key
and its associated data.
:param key:
The name of the key (or file inside a directory) which will hold
the data. File extensions should not be provided, as they will be
added by the driver itself.
:param data:
The data which will be stored in the cache. This data should be
in a format which can be serialized by msgpack/json/yaml/etc.
:raises SaltCacheError:
Raises an exception if cache driver detected an error accessing data
in the cache backend (auth, permissions, etc). | [
"Store",
"data",
"using",
"the",
"specified",
"module"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cache/__init__.py#L134-L156 | train |
saltstack/salt | salt/cache/__init__.py | Cache.fetch | def fetch(self, bank, key):
'''
Fetch data using the specified module
:param bank:
The name of the location inside the cache which will hold the key
and its associated data.
:param key:
The name of the key (or file inside a directory) which will hold
the data. File extensions should not be provided, as they will be
added by the driver itself.
:return:
Return a python object fetched from the cache or an empty dict if
the given path or key not found.
:raises SaltCacheError:
Raises an exception if cache driver detected an error accessing data
in the cache backend (auth, permissions, etc).
'''
fun = '{0}.fetch'.format(self.driver)
return self.modules[fun](bank, key, **self._kwargs) | python | def fetch(self, bank, key):
'''
Fetch data using the specified module
:param bank:
The name of the location inside the cache which will hold the key
and its associated data.
:param key:
The name of the key (or file inside a directory) which will hold
the data. File extensions should not be provided, as they will be
added by the driver itself.
:return:
Return a python object fetched from the cache or an empty dict if
the given path or key not found.
:raises SaltCacheError:
Raises an exception if cache driver detected an error accessing data
in the cache backend (auth, permissions, etc).
'''
fun = '{0}.fetch'.format(self.driver)
return self.modules[fun](bank, key, **self._kwargs) | [
"def",
"fetch",
"(",
"self",
",",
"bank",
",",
"key",
")",
":",
"fun",
"=",
"'{0}.fetch'",
".",
"format",
"(",
"self",
".",
"driver",
")",
"return",
"self",
".",
"modules",
"[",
"fun",
"]",
"(",
"bank",
",",
"key",
",",
"*",
"*",
"self",
".",
"... | Fetch data using the specified module
:param bank:
The name of the location inside the cache which will hold the key
and its associated data.
:param key:
The name of the key (or file inside a directory) which will hold
the data. File extensions should not be provided, as they will be
added by the driver itself.
:return:
Return a python object fetched from the cache or an empty dict if
the given path or key not found.
:raises SaltCacheError:
Raises an exception if cache driver detected an error accessing data
in the cache backend (auth, permissions, etc). | [
"Fetch",
"data",
"using",
"the",
"specified",
"module"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cache/__init__.py#L158-L180 | train |
saltstack/salt | salt/cache/__init__.py | Cache.list | def list(self, bank):
'''
Lists entries stored in the specified bank.
:param bank:
The name of the location inside the cache which will hold the key
and its associated data.
:return:
An iterable object containing all bank entries. Returns an empty
iterator if the bank doesn't exists.
:raises SaltCacheError:
Raises an exception if cache driver detected an error accessing data
in the cache backend (auth, permissions, etc).
'''
fun = '{0}.list'.format(self.driver)
return self.modules[fun](bank, **self._kwargs) | python | def list(self, bank):
'''
Lists entries stored in the specified bank.
:param bank:
The name of the location inside the cache which will hold the key
and its associated data.
:return:
An iterable object containing all bank entries. Returns an empty
iterator if the bank doesn't exists.
:raises SaltCacheError:
Raises an exception if cache driver detected an error accessing data
in the cache backend (auth, permissions, etc).
'''
fun = '{0}.list'.format(self.driver)
return self.modules[fun](bank, **self._kwargs) | [
"def",
"list",
"(",
"self",
",",
"bank",
")",
":",
"fun",
"=",
"'{0}.list'",
".",
"format",
"(",
"self",
".",
"driver",
")",
"return",
"self",
".",
"modules",
"[",
"fun",
"]",
"(",
"bank",
",",
"*",
"*",
"self",
".",
"_kwargs",
")"
] | Lists entries stored in the specified bank.
:param bank:
The name of the location inside the cache which will hold the key
and its associated data.
:return:
An iterable object containing all bank entries. Returns an empty
iterator if the bank doesn't exists.
:raises SaltCacheError:
Raises an exception if cache driver detected an error accessing data
in the cache backend (auth, permissions, etc). | [
"Lists",
"entries",
"stored",
"in",
"the",
"specified",
"bank",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cache/__init__.py#L227-L244 | train |
saltstack/salt | salt/wheel/error.py | error | def error(name=None, message=''):
'''
If name is None Then return empty dict
Otherwise raise an exception with __name__ from name, message from message
CLI Example:
.. code-block:: bash
salt-wheel error
salt-wheel error.error name="Exception" message="This is an error."
'''
ret = {}
if name is not None:
salt.utils.error.raise_error(name=name, message=message)
return ret | python | def error(name=None, message=''):
'''
If name is None Then return empty dict
Otherwise raise an exception with __name__ from name, message from message
CLI Example:
.. code-block:: bash
salt-wheel error
salt-wheel error.error name="Exception" message="This is an error."
'''
ret = {}
if name is not None:
salt.utils.error.raise_error(name=name, message=message)
return ret | [
"def",
"error",
"(",
"name",
"=",
"None",
",",
"message",
"=",
"''",
")",
":",
"ret",
"=",
"{",
"}",
"if",
"name",
"is",
"not",
"None",
":",
"salt",
".",
"utils",
".",
"error",
".",
"raise_error",
"(",
"name",
"=",
"name",
",",
"message",
"=",
... | If name is None Then return empty dict
Otherwise raise an exception with __name__ from name, message from message
CLI Example:
.. code-block:: bash
salt-wheel error
salt-wheel error.error name="Exception" message="This is an error." | [
"If",
"name",
"is",
"None",
"Then",
"return",
"empty",
"dict"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/wheel/error.py#L15-L31 | train |
saltstack/salt | salt/states/boto_asg.py | present | def present(
name,
launch_config_name,
availability_zones,
min_size,
max_size,
launch_config=None,
desired_capacity=None,
load_balancers=None,
default_cooldown=None,
health_check_type=None,
health_check_period=None,
placement_group=None,
vpc_zone_identifier=None,
subnet_names=None,
tags=None,
termination_policies=None,
termination_policies_from_pillar='boto_asg_termination_policies',
suspended_processes=None,
scaling_policies=None,
scaling_policies_from_pillar='boto_asg_scaling_policies',
scheduled_actions=None,
scheduled_actions_from_pillar='boto_asg_scheduled_actions',
alarms=None,
alarms_from_pillar='boto_asg_alarms',
region=None,
key=None,
keyid=None,
profile=None,
notification_arn=None,
notification_arn_from_pillar='boto_asg_notification_arn',
notification_types=None,
notification_types_from_pillar='boto_asg_notification_types'):
'''
Ensure the autoscale group exists.
name
Name of the autoscale group.
launch_config_name
Name of the launch config to use for the group. Or, if
``launch_config`` is specified, this will be the launch config
name's prefix. (see below)
launch_config
A dictionary of launch config attributes. If specified, a
launch config will be used or created, matching this set
of attributes, and the autoscale group will be set to use
that launch config. The launch config name will be the
``launch_config_name`` followed by a hyphen followed by a hash
of the ``launch_config`` dict contents.
Example:
.. code-block:: yaml
my_asg:
boto_asg.present:
- launch_config:
- ebs_optimized: false
- instance_profile_name: my_iam_profile
- kernel_id: ''
- ramdisk_id: ''
- key_name: my_ssh_key
- image_name: aws2015091-hvm
- instance_type: c3.xlarge
- instance_monitoring: false
- security_groups:
- my_sec_group_01
- my_sec_group_02
availability_zones
List of availability zones for the group.
min_size
Minimum size of the group.
max_size
Maximum size of the group.
desired_capacity
The desired capacity of the group.
load_balancers
List of load balancers for the group. Once set this can not be
updated (Amazon restriction).
default_cooldown
Number of seconds after a Scaling Activity completes before any further
scaling activities can start.
health_check_type
The service you want the health status from, Amazon EC2 or Elastic Load
Balancer (EC2 or ELB).
health_check_period
Length of time in seconds after a new EC2 instance comes into service
that Auto Scaling starts checking its health.
placement_group
Physical location of your cluster placement group created in Amazon
EC2. Once set this can not be updated (Amazon restriction).
vpc_zone_identifier
A list of the subnet identifiers of the Virtual Private Cloud.
subnet_names
For VPC, a list of subnet names (NOT subnet IDs) to deploy into.
Exclusive with vpc_zone_identifier.
tags
A list of tags. Example:
.. code-block:: yaml
- key: 'key'
value: 'value'
propagate_at_launch: true
termination_policies
A list of termination policies. Valid values are:
* ``OldestInstance``
* ``NewestInstance``
* ``OldestLaunchConfiguration``
* ``ClosestToNextInstanceHour``
* ``Default``
If no value is specified, the ``Default`` value is used.
termination_policies_from_pillar:
name of pillar dict that contains termination policy settings. Termination policies
defined for this specific state will override those from pillar.
suspended_processes
List of processes to be suspended. see
http://docs.aws.amazon.com/AutoScaling/latest/DeveloperGuide/US_SuspendResume.html
scaling_policies
List of scaling policies. Each policy is a dict of key-values described by
https://boto.readthedocs.io/en/latest/ref/autoscale.html#boto.ec2.autoscale.policy.ScalingPolicy
scaling_policies_from_pillar:
name of pillar dict that contains scaling policy settings. Scaling policies defined for
this specific state will override those from pillar.
scheduled_actions:
a dictionary of scheduled actions. Each key is the name of scheduled action and each value
is dictionary of options. For example:
.. code-block:: yaml
- scheduled_actions:
scale_up_at_10:
desired_capacity: 4
min_size: 3
max_size: 5
recurrence: "0 9 * * 1-5"
scale_down_at_7:
desired_capacity: 1
min_size: 1
max_size: 1
recurrence: "0 19 * * 1-5"
scheduled_actions_from_pillar:
name of pillar dict that contains scheduled_actions settings. Scheduled actions
for this specific state will override those from pillar.
alarms:
a dictionary of name->boto_cloudwatch_alarm sections to be associated with this ASG.
All attributes should be specified except for dimension which will be
automatically set to this ASG.
See the :mod:`salt.states.boto_cloudwatch_alarm` state for information
about these attributes.
If any alarm actions include ":self:" this will be replaced with the asg name.
For example, alarm_actions reading "['scaling_policy:self:ScaleUp']" will
map to the arn for this asg's scaling policy named "ScaleUp".
In addition, any alarms that have only scaling_policy as actions will be ignored if
min_size is equal to max_size for this ASG.
alarms_from_pillar:
name of pillar dict that contains alarm settings. Alarms defined for this specific
state will override those from pillar.
region
The region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
notification_arn
The AWS arn that notifications will be sent to
notification_arn_from_pillar
name of the pillar dict that contains ``notifcation_arn`` settings. A
``notification_arn`` defined for this specific state will override the
one from pillar.
notification_types
A list of event names that will trigger a notification. The list of valid
notification types is:
* ``autoscaling:EC2_INSTANCE_LAUNCH``
* ``autoscaling:EC2_INSTANCE_LAUNCH_ERROR``
* ``autoscaling:EC2_INSTANCE_TERMINATE``
* ``autoscaling:EC2_INSTANCE_TERMINATE_ERROR``
* ``autoscaling:TEST_NOTIFICATION``
notification_types_from_pillar
name of the pillar dict that contains ``notifcation_types`` settings.
``notification_types`` defined for this specific state will override those
from the pillar.
'''
if vpc_zone_identifier and subnet_names:
raise SaltInvocationError('vpc_zone_identifier and subnet_names are '
'mutually exclusive options.')
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
if subnet_names:
vpc_zone_identifier = []
for i in subnet_names:
r = __salt__['boto_vpc.get_resource_id']('subnet', name=i, region=region,
key=key, keyid=keyid, profile=profile)
if 'error' in r:
ret['comment'] = 'Error looking up subnet ids: {0}'.format(r['error'])
ret['result'] = False
return ret
if 'id' not in r:
ret['comment'] = 'Subnet {0} does not exist.'.format(i)
ret['result'] = False
return ret
vpc_zone_identifier.append(r['id'])
if vpc_zone_identifier:
vpc_id = __salt__['boto_vpc.get_subnet_association'](
vpc_zone_identifier,
region,
key,
keyid,
profile
)
vpc_id = vpc_id.get('vpc_id')
log.debug('Auto Scaling Group %s is associated with VPC ID %s',
name, vpc_id)
else:
vpc_id = None
log.debug('Auto Scaling Group %s has no VPC Association', name)
# if launch_config is defined, manage the launch config first.
# hash the launch_config dict to create a unique name suffix and then
# ensure it is present
if launch_config:
launch_config_bytes = salt.utils.stringutils.to_bytes(str(launch_config)) # future lint: disable=blacklisted-function
launch_config_name = launch_config_name + '-' + hashlib.md5(launch_config_bytes).hexdigest()
args = {
'name': launch_config_name,
'region': region,
'key': key,
'keyid': keyid,
'profile': profile
}
for index, item in enumerate(launch_config):
if 'image_name' in item:
image_name = item['image_name']
iargs = {'ami_name': image_name, 'region': region, 'key': key,
'keyid': keyid, 'profile': profile}
image_ids = __salt__['boto_ec2.find_images'](**iargs)
if image_ids: # find_images() returns False on failure
launch_config[index]['image_id'] = image_ids[0]
else:
log.warning("Couldn't find AMI named `%s`, passing literally.", image_name)
launch_config[index]['image_id'] = image_name
del launch_config[index]['image_name']
break
if vpc_id:
log.debug('Auto Scaling Group {0} is a associated with a vpc')
# locate the security groups attribute of a launch config
sg_index = None
for index, item in enumerate(launch_config):
if 'security_groups' in item:
sg_index = index
break
# if security groups exist within launch_config then convert
# to group ids
if sg_index is not None:
log.debug('security group associations found in launch config')
_group_ids = __salt__['boto_secgroup.convert_to_group_ids'](
launch_config[sg_index]['security_groups'], vpc_id=vpc_id,
region=region, key=key, keyid=keyid, profile=profile
)
launch_config[sg_index]['security_groups'] = _group_ids
for d in launch_config:
args.update(d)
if not __opts__['test']:
lc_ret = __states__['boto_lc.present'](**args)
if lc_ret['result'] is True and lc_ret['changes']:
if 'launch_config' not in ret['changes']:
ret['changes']['launch_config'] = {}
ret['changes']['launch_config'] = lc_ret['changes']
asg = __salt__['boto_asg.get_config'](name, region, key, keyid, profile)
termination_policies = _determine_termination_policies(
termination_policies,
termination_policies_from_pillar
)
scaling_policies = _determine_scaling_policies(
scaling_policies,
scaling_policies_from_pillar
)
scheduled_actions = _determine_scheduled_actions(
scheduled_actions,
scheduled_actions_from_pillar
)
if asg is None:
ret['result'] = False
ret['comment'] = 'Failed to check autoscale group existence.'
elif not asg:
if __opts__['test']:
msg = 'Autoscale group set to be created.'
ret['comment'] = msg
ret['result'] = None
return ret
notification_arn, notification_types = _determine_notification_info(
notification_arn,
notification_arn_from_pillar,
notification_types,
notification_types_from_pillar
)
created = __salt__['boto_asg.create'](name, launch_config_name,
availability_zones, min_size,
max_size, desired_capacity,
load_balancers, default_cooldown,
health_check_type,
health_check_period,
placement_group,
vpc_zone_identifier, tags,
termination_policies,
suspended_processes,
scaling_policies, scheduled_actions,
region, notification_arn,
notification_types,
key, keyid, profile)
if created:
ret['changes']['old'] = None
asg = __salt__['boto_asg.get_config'](name, region, key, keyid,
profile)
ret['changes']['new'] = asg
else:
ret['result'] = False
ret['comment'] = 'Failed to create autoscale group'
else:
need_update = False
# If any of these attributes can't be modified after creation
# time, we should remove them from the dict.
if scaling_policies:
for policy in scaling_policies:
if 'min_adjustment_step' not in policy:
policy['min_adjustment_step'] = None
if scheduled_actions:
for s_name, action in six.iteritems(scheduled_actions):
if 'end_time' not in action:
action['end_time'] = None
config = {
'launch_config_name': launch_config_name,
'availability_zones': availability_zones,
'min_size': min_size,
'max_size': max_size,
'desired_capacity': desired_capacity,
'default_cooldown': default_cooldown,
'health_check_type': health_check_type,
'health_check_period': health_check_period,
'vpc_zone_identifier': vpc_zone_identifier,
'tags': tags,
'termination_policies': termination_policies,
'suspended_processes': suspended_processes,
'scaling_policies': scaling_policies,
'scheduled_actions': scheduled_actions
}
#ensure that we reset termination_policies to default if none are specified
if not termination_policies:
config['termination_policies'] = ['Default']
if suspended_processes is None:
config['suspended_processes'] = []
# ensure that we delete scaling_policies if none are specified
if scaling_policies is None:
config['scaling_policies'] = []
# ensure that we delete scheduled_actions if none are specified
if scheduled_actions is None:
config['scheduled_actions'] = {}
# allow defaults on start_time
for s_name, action in six.iteritems(scheduled_actions):
if 'start_time' not in action:
asg_action = asg['scheduled_actions'].get(s_name, {})
if 'start_time' in asg_action:
del asg_action['start_time']
proposed = {}
# note: do not loop using "key, value" - this can modify the value of
# the aws access key
for asg_property, value in six.iteritems(config):
# Only modify values being specified; introspection is difficult
# otherwise since it's hard to track default values, which will
# always be returned from AWS.
if value is None:
continue
value = __utils__['boto3.ordered'](value)
if asg_property in asg:
_value = __utils__['boto3.ordered'](asg[asg_property])
if not value == _value:
log.debug('%s asg_property differs from %s', value, _value)
proposed.setdefault('old', {}).update({asg_property: _value})
proposed.setdefault('new', {}).update({asg_property: value})
need_update = True
if need_update:
if __opts__['test']:
msg = 'Autoscale group set to be updated.'
ret['comment'] = msg
ret['result'] = None
ret['changes'] = proposed
return ret
# add in alarms
notification_arn, notification_types = _determine_notification_info(
notification_arn,
notification_arn_from_pillar,
notification_types,
notification_types_from_pillar
)
updated, msg = __salt__['boto_asg.update'](
name,
launch_config_name,
availability_zones,
min_size,
max_size,
desired_capacity=desired_capacity,
load_balancers=load_balancers,
default_cooldown=default_cooldown,
health_check_type=health_check_type,
health_check_period=health_check_period,
placement_group=placement_group,
vpc_zone_identifier=vpc_zone_identifier,
tags=tags,
termination_policies=termination_policies,
suspended_processes=suspended_processes,
scaling_policies=scaling_policies,
scheduled_actions=scheduled_actions,
region=region,
notification_arn=notification_arn,
notification_types=notification_types,
key=key,
keyid=keyid,
profile=profile
)
if asg['launch_config_name'] != launch_config_name:
# delete the old launch_config_name
deleted = __salt__['boto_asg.delete_launch_configuration'](
asg['launch_config_name'],
region=region,
key=key,
keyid=keyid,
profile=profile
)
if deleted:
if 'launch_config' not in ret['changes']:
ret['changes']['launch_config'] = {}
ret['changes']['launch_config']['deleted'] = asg['launch_config_name']
if updated:
ret['changes']['old'] = asg
asg = __salt__['boto_asg.get_config'](name, region, key, keyid,
profile)
ret['changes']['new'] = asg
ret['comment'] = 'Updated autoscale group.'
else:
ret['result'] = False
ret['comment'] = msg
else:
ret['comment'] = 'Autoscale group present.'
# add in alarms
_ret = _alarms_present(
name, min_size == max_size, alarms, alarms_from_pillar, region, key,
keyid, profile
)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
return ret | python | def present(
name,
launch_config_name,
availability_zones,
min_size,
max_size,
launch_config=None,
desired_capacity=None,
load_balancers=None,
default_cooldown=None,
health_check_type=None,
health_check_period=None,
placement_group=None,
vpc_zone_identifier=None,
subnet_names=None,
tags=None,
termination_policies=None,
termination_policies_from_pillar='boto_asg_termination_policies',
suspended_processes=None,
scaling_policies=None,
scaling_policies_from_pillar='boto_asg_scaling_policies',
scheduled_actions=None,
scheduled_actions_from_pillar='boto_asg_scheduled_actions',
alarms=None,
alarms_from_pillar='boto_asg_alarms',
region=None,
key=None,
keyid=None,
profile=None,
notification_arn=None,
notification_arn_from_pillar='boto_asg_notification_arn',
notification_types=None,
notification_types_from_pillar='boto_asg_notification_types'):
'''
Ensure the autoscale group exists.
name
Name of the autoscale group.
launch_config_name
Name of the launch config to use for the group. Or, if
``launch_config`` is specified, this will be the launch config
name's prefix. (see below)
launch_config
A dictionary of launch config attributes. If specified, a
launch config will be used or created, matching this set
of attributes, and the autoscale group will be set to use
that launch config. The launch config name will be the
``launch_config_name`` followed by a hyphen followed by a hash
of the ``launch_config`` dict contents.
Example:
.. code-block:: yaml
my_asg:
boto_asg.present:
- launch_config:
- ebs_optimized: false
- instance_profile_name: my_iam_profile
- kernel_id: ''
- ramdisk_id: ''
- key_name: my_ssh_key
- image_name: aws2015091-hvm
- instance_type: c3.xlarge
- instance_monitoring: false
- security_groups:
- my_sec_group_01
- my_sec_group_02
availability_zones
List of availability zones for the group.
min_size
Minimum size of the group.
max_size
Maximum size of the group.
desired_capacity
The desired capacity of the group.
load_balancers
List of load balancers for the group. Once set this can not be
updated (Amazon restriction).
default_cooldown
Number of seconds after a Scaling Activity completes before any further
scaling activities can start.
health_check_type
The service you want the health status from, Amazon EC2 or Elastic Load
Balancer (EC2 or ELB).
health_check_period
Length of time in seconds after a new EC2 instance comes into service
that Auto Scaling starts checking its health.
placement_group
Physical location of your cluster placement group created in Amazon
EC2. Once set this can not be updated (Amazon restriction).
vpc_zone_identifier
A list of the subnet identifiers of the Virtual Private Cloud.
subnet_names
For VPC, a list of subnet names (NOT subnet IDs) to deploy into.
Exclusive with vpc_zone_identifier.
tags
A list of tags. Example:
.. code-block:: yaml
- key: 'key'
value: 'value'
propagate_at_launch: true
termination_policies
A list of termination policies. Valid values are:
* ``OldestInstance``
* ``NewestInstance``
* ``OldestLaunchConfiguration``
* ``ClosestToNextInstanceHour``
* ``Default``
If no value is specified, the ``Default`` value is used.
termination_policies_from_pillar:
name of pillar dict that contains termination policy settings. Termination policies
defined for this specific state will override those from pillar.
suspended_processes
List of processes to be suspended. see
http://docs.aws.amazon.com/AutoScaling/latest/DeveloperGuide/US_SuspendResume.html
scaling_policies
List of scaling policies. Each policy is a dict of key-values described by
https://boto.readthedocs.io/en/latest/ref/autoscale.html#boto.ec2.autoscale.policy.ScalingPolicy
scaling_policies_from_pillar:
name of pillar dict that contains scaling policy settings. Scaling policies defined for
this specific state will override those from pillar.
scheduled_actions:
a dictionary of scheduled actions. Each key is the name of scheduled action and each value
is dictionary of options. For example:
.. code-block:: yaml
- scheduled_actions:
scale_up_at_10:
desired_capacity: 4
min_size: 3
max_size: 5
recurrence: "0 9 * * 1-5"
scale_down_at_7:
desired_capacity: 1
min_size: 1
max_size: 1
recurrence: "0 19 * * 1-5"
scheduled_actions_from_pillar:
name of pillar dict that contains scheduled_actions settings. Scheduled actions
for this specific state will override those from pillar.
alarms:
a dictionary of name->boto_cloudwatch_alarm sections to be associated with this ASG.
All attributes should be specified except for dimension which will be
automatically set to this ASG.
See the :mod:`salt.states.boto_cloudwatch_alarm` state for information
about these attributes.
If any alarm actions include ":self:" this will be replaced with the asg name.
For example, alarm_actions reading "['scaling_policy:self:ScaleUp']" will
map to the arn for this asg's scaling policy named "ScaleUp".
In addition, any alarms that have only scaling_policy as actions will be ignored if
min_size is equal to max_size for this ASG.
alarms_from_pillar:
name of pillar dict that contains alarm settings. Alarms defined for this specific
state will override those from pillar.
region
The region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
notification_arn
The AWS arn that notifications will be sent to
notification_arn_from_pillar
name of the pillar dict that contains ``notifcation_arn`` settings. A
``notification_arn`` defined for this specific state will override the
one from pillar.
notification_types
A list of event names that will trigger a notification. The list of valid
notification types is:
* ``autoscaling:EC2_INSTANCE_LAUNCH``
* ``autoscaling:EC2_INSTANCE_LAUNCH_ERROR``
* ``autoscaling:EC2_INSTANCE_TERMINATE``
* ``autoscaling:EC2_INSTANCE_TERMINATE_ERROR``
* ``autoscaling:TEST_NOTIFICATION``
notification_types_from_pillar
name of the pillar dict that contains ``notifcation_types`` settings.
``notification_types`` defined for this specific state will override those
from the pillar.
'''
if vpc_zone_identifier and subnet_names:
raise SaltInvocationError('vpc_zone_identifier and subnet_names are '
'mutually exclusive options.')
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
if subnet_names:
vpc_zone_identifier = []
for i in subnet_names:
r = __salt__['boto_vpc.get_resource_id']('subnet', name=i, region=region,
key=key, keyid=keyid, profile=profile)
if 'error' in r:
ret['comment'] = 'Error looking up subnet ids: {0}'.format(r['error'])
ret['result'] = False
return ret
if 'id' not in r:
ret['comment'] = 'Subnet {0} does not exist.'.format(i)
ret['result'] = False
return ret
vpc_zone_identifier.append(r['id'])
if vpc_zone_identifier:
vpc_id = __salt__['boto_vpc.get_subnet_association'](
vpc_zone_identifier,
region,
key,
keyid,
profile
)
vpc_id = vpc_id.get('vpc_id')
log.debug('Auto Scaling Group %s is associated with VPC ID %s',
name, vpc_id)
else:
vpc_id = None
log.debug('Auto Scaling Group %s has no VPC Association', name)
# if launch_config is defined, manage the launch config first.
# hash the launch_config dict to create a unique name suffix and then
# ensure it is present
if launch_config:
launch_config_bytes = salt.utils.stringutils.to_bytes(str(launch_config)) # future lint: disable=blacklisted-function
launch_config_name = launch_config_name + '-' + hashlib.md5(launch_config_bytes).hexdigest()
args = {
'name': launch_config_name,
'region': region,
'key': key,
'keyid': keyid,
'profile': profile
}
for index, item in enumerate(launch_config):
if 'image_name' in item:
image_name = item['image_name']
iargs = {'ami_name': image_name, 'region': region, 'key': key,
'keyid': keyid, 'profile': profile}
image_ids = __salt__['boto_ec2.find_images'](**iargs)
if image_ids: # find_images() returns False on failure
launch_config[index]['image_id'] = image_ids[0]
else:
log.warning("Couldn't find AMI named `%s`, passing literally.", image_name)
launch_config[index]['image_id'] = image_name
del launch_config[index]['image_name']
break
if vpc_id:
log.debug('Auto Scaling Group {0} is a associated with a vpc')
# locate the security groups attribute of a launch config
sg_index = None
for index, item in enumerate(launch_config):
if 'security_groups' in item:
sg_index = index
break
# if security groups exist within launch_config then convert
# to group ids
if sg_index is not None:
log.debug('security group associations found in launch config')
_group_ids = __salt__['boto_secgroup.convert_to_group_ids'](
launch_config[sg_index]['security_groups'], vpc_id=vpc_id,
region=region, key=key, keyid=keyid, profile=profile
)
launch_config[sg_index]['security_groups'] = _group_ids
for d in launch_config:
args.update(d)
if not __opts__['test']:
lc_ret = __states__['boto_lc.present'](**args)
if lc_ret['result'] is True and lc_ret['changes']:
if 'launch_config' not in ret['changes']:
ret['changes']['launch_config'] = {}
ret['changes']['launch_config'] = lc_ret['changes']
asg = __salt__['boto_asg.get_config'](name, region, key, keyid, profile)
termination_policies = _determine_termination_policies(
termination_policies,
termination_policies_from_pillar
)
scaling_policies = _determine_scaling_policies(
scaling_policies,
scaling_policies_from_pillar
)
scheduled_actions = _determine_scheduled_actions(
scheduled_actions,
scheduled_actions_from_pillar
)
if asg is None:
ret['result'] = False
ret['comment'] = 'Failed to check autoscale group existence.'
elif not asg:
if __opts__['test']:
msg = 'Autoscale group set to be created.'
ret['comment'] = msg
ret['result'] = None
return ret
notification_arn, notification_types = _determine_notification_info(
notification_arn,
notification_arn_from_pillar,
notification_types,
notification_types_from_pillar
)
created = __salt__['boto_asg.create'](name, launch_config_name,
availability_zones, min_size,
max_size, desired_capacity,
load_balancers, default_cooldown,
health_check_type,
health_check_period,
placement_group,
vpc_zone_identifier, tags,
termination_policies,
suspended_processes,
scaling_policies, scheduled_actions,
region, notification_arn,
notification_types,
key, keyid, profile)
if created:
ret['changes']['old'] = None
asg = __salt__['boto_asg.get_config'](name, region, key, keyid,
profile)
ret['changes']['new'] = asg
else:
ret['result'] = False
ret['comment'] = 'Failed to create autoscale group'
else:
need_update = False
# If any of these attributes can't be modified after creation
# time, we should remove them from the dict.
if scaling_policies:
for policy in scaling_policies:
if 'min_adjustment_step' not in policy:
policy['min_adjustment_step'] = None
if scheduled_actions:
for s_name, action in six.iteritems(scheduled_actions):
if 'end_time' not in action:
action['end_time'] = None
config = {
'launch_config_name': launch_config_name,
'availability_zones': availability_zones,
'min_size': min_size,
'max_size': max_size,
'desired_capacity': desired_capacity,
'default_cooldown': default_cooldown,
'health_check_type': health_check_type,
'health_check_period': health_check_period,
'vpc_zone_identifier': vpc_zone_identifier,
'tags': tags,
'termination_policies': termination_policies,
'suspended_processes': suspended_processes,
'scaling_policies': scaling_policies,
'scheduled_actions': scheduled_actions
}
#ensure that we reset termination_policies to default if none are specified
if not termination_policies:
config['termination_policies'] = ['Default']
if suspended_processes is None:
config['suspended_processes'] = []
# ensure that we delete scaling_policies if none are specified
if scaling_policies is None:
config['scaling_policies'] = []
# ensure that we delete scheduled_actions if none are specified
if scheduled_actions is None:
config['scheduled_actions'] = {}
# allow defaults on start_time
for s_name, action in six.iteritems(scheduled_actions):
if 'start_time' not in action:
asg_action = asg['scheduled_actions'].get(s_name, {})
if 'start_time' in asg_action:
del asg_action['start_time']
proposed = {}
# note: do not loop using "key, value" - this can modify the value of
# the aws access key
for asg_property, value in six.iteritems(config):
# Only modify values being specified; introspection is difficult
# otherwise since it's hard to track default values, which will
# always be returned from AWS.
if value is None:
continue
value = __utils__['boto3.ordered'](value)
if asg_property in asg:
_value = __utils__['boto3.ordered'](asg[asg_property])
if not value == _value:
log.debug('%s asg_property differs from %s', value, _value)
proposed.setdefault('old', {}).update({asg_property: _value})
proposed.setdefault('new', {}).update({asg_property: value})
need_update = True
if need_update:
if __opts__['test']:
msg = 'Autoscale group set to be updated.'
ret['comment'] = msg
ret['result'] = None
ret['changes'] = proposed
return ret
# add in alarms
notification_arn, notification_types = _determine_notification_info(
notification_arn,
notification_arn_from_pillar,
notification_types,
notification_types_from_pillar
)
updated, msg = __salt__['boto_asg.update'](
name,
launch_config_name,
availability_zones,
min_size,
max_size,
desired_capacity=desired_capacity,
load_balancers=load_balancers,
default_cooldown=default_cooldown,
health_check_type=health_check_type,
health_check_period=health_check_period,
placement_group=placement_group,
vpc_zone_identifier=vpc_zone_identifier,
tags=tags,
termination_policies=termination_policies,
suspended_processes=suspended_processes,
scaling_policies=scaling_policies,
scheduled_actions=scheduled_actions,
region=region,
notification_arn=notification_arn,
notification_types=notification_types,
key=key,
keyid=keyid,
profile=profile
)
if asg['launch_config_name'] != launch_config_name:
# delete the old launch_config_name
deleted = __salt__['boto_asg.delete_launch_configuration'](
asg['launch_config_name'],
region=region,
key=key,
keyid=keyid,
profile=profile
)
if deleted:
if 'launch_config' not in ret['changes']:
ret['changes']['launch_config'] = {}
ret['changes']['launch_config']['deleted'] = asg['launch_config_name']
if updated:
ret['changes']['old'] = asg
asg = __salt__['boto_asg.get_config'](name, region, key, keyid,
profile)
ret['changes']['new'] = asg
ret['comment'] = 'Updated autoscale group.'
else:
ret['result'] = False
ret['comment'] = msg
else:
ret['comment'] = 'Autoscale group present.'
# add in alarms
_ret = _alarms_present(
name, min_size == max_size, alarms, alarms_from_pillar, region, key,
keyid, profile
)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
return ret | [
"def",
"present",
"(",
"name",
",",
"launch_config_name",
",",
"availability_zones",
",",
"min_size",
",",
"max_size",
",",
"launch_config",
"=",
"None",
",",
"desired_capacity",
"=",
"None",
",",
"load_balancers",
"=",
"None",
",",
"default_cooldown",
"=",
"Non... | Ensure the autoscale group exists.
name
Name of the autoscale group.
launch_config_name
Name of the launch config to use for the group. Or, if
``launch_config`` is specified, this will be the launch config
name's prefix. (see below)
launch_config
A dictionary of launch config attributes. If specified, a
launch config will be used or created, matching this set
of attributes, and the autoscale group will be set to use
that launch config. The launch config name will be the
``launch_config_name`` followed by a hyphen followed by a hash
of the ``launch_config`` dict contents.
Example:
.. code-block:: yaml
my_asg:
boto_asg.present:
- launch_config:
- ebs_optimized: false
- instance_profile_name: my_iam_profile
- kernel_id: ''
- ramdisk_id: ''
- key_name: my_ssh_key
- image_name: aws2015091-hvm
- instance_type: c3.xlarge
- instance_monitoring: false
- security_groups:
- my_sec_group_01
- my_sec_group_02
availability_zones
List of availability zones for the group.
min_size
Minimum size of the group.
max_size
Maximum size of the group.
desired_capacity
The desired capacity of the group.
load_balancers
List of load balancers for the group. Once set this can not be
updated (Amazon restriction).
default_cooldown
Number of seconds after a Scaling Activity completes before any further
scaling activities can start.
health_check_type
The service you want the health status from, Amazon EC2 or Elastic Load
Balancer (EC2 or ELB).
health_check_period
Length of time in seconds after a new EC2 instance comes into service
that Auto Scaling starts checking its health.
placement_group
Physical location of your cluster placement group created in Amazon
EC2. Once set this can not be updated (Amazon restriction).
vpc_zone_identifier
A list of the subnet identifiers of the Virtual Private Cloud.
subnet_names
For VPC, a list of subnet names (NOT subnet IDs) to deploy into.
Exclusive with vpc_zone_identifier.
tags
A list of tags. Example:
.. code-block:: yaml
- key: 'key'
value: 'value'
propagate_at_launch: true
termination_policies
A list of termination policies. Valid values are:
* ``OldestInstance``
* ``NewestInstance``
* ``OldestLaunchConfiguration``
* ``ClosestToNextInstanceHour``
* ``Default``
If no value is specified, the ``Default`` value is used.
termination_policies_from_pillar:
name of pillar dict that contains termination policy settings. Termination policies
defined for this specific state will override those from pillar.
suspended_processes
List of processes to be suspended. see
http://docs.aws.amazon.com/AutoScaling/latest/DeveloperGuide/US_SuspendResume.html
scaling_policies
List of scaling policies. Each policy is a dict of key-values described by
https://boto.readthedocs.io/en/latest/ref/autoscale.html#boto.ec2.autoscale.policy.ScalingPolicy
scaling_policies_from_pillar:
name of pillar dict that contains scaling policy settings. Scaling policies defined for
this specific state will override those from pillar.
scheduled_actions:
a dictionary of scheduled actions. Each key is the name of scheduled action and each value
is dictionary of options. For example:
.. code-block:: yaml
- scheduled_actions:
scale_up_at_10:
desired_capacity: 4
min_size: 3
max_size: 5
recurrence: "0 9 * * 1-5"
scale_down_at_7:
desired_capacity: 1
min_size: 1
max_size: 1
recurrence: "0 19 * * 1-5"
scheduled_actions_from_pillar:
name of pillar dict that contains scheduled_actions settings. Scheduled actions
for this specific state will override those from pillar.
alarms:
a dictionary of name->boto_cloudwatch_alarm sections to be associated with this ASG.
All attributes should be specified except for dimension which will be
automatically set to this ASG.
See the :mod:`salt.states.boto_cloudwatch_alarm` state for information
about these attributes.
If any alarm actions include ":self:" this will be replaced with the asg name.
For example, alarm_actions reading "['scaling_policy:self:ScaleUp']" will
map to the arn for this asg's scaling policy named "ScaleUp".
In addition, any alarms that have only scaling_policy as actions will be ignored if
min_size is equal to max_size for this ASG.
alarms_from_pillar:
name of pillar dict that contains alarm settings. Alarms defined for this specific
state will override those from pillar.
region
The region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
notification_arn
The AWS arn that notifications will be sent to
notification_arn_from_pillar
name of the pillar dict that contains ``notifcation_arn`` settings. A
``notification_arn`` defined for this specific state will override the
one from pillar.
notification_types
A list of event names that will trigger a notification. The list of valid
notification types is:
* ``autoscaling:EC2_INSTANCE_LAUNCH``
* ``autoscaling:EC2_INSTANCE_LAUNCH_ERROR``
* ``autoscaling:EC2_INSTANCE_TERMINATE``
* ``autoscaling:EC2_INSTANCE_TERMINATE_ERROR``
* ``autoscaling:TEST_NOTIFICATION``
notification_types_from_pillar
name of the pillar dict that contains ``notifcation_types`` settings.
``notification_types`` defined for this specific state will override those
from the pillar. | [
"Ensure",
"the",
"autoscale",
"group",
"exists",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_asg.py#L217-L709 | train |
saltstack/salt | salt/states/boto_asg.py | _determine_termination_policies | def _determine_termination_policies(termination_policies, termination_policies_from_pillar):
'''
helper method for present. ensure that termination_policies are set
'''
pillar_termination_policies = copy.deepcopy(
__salt__['config.option'](termination_policies_from_pillar, [])
)
if not termination_policies and pillar_termination_policies:
termination_policies = pillar_termination_policies
return termination_policies | python | def _determine_termination_policies(termination_policies, termination_policies_from_pillar):
'''
helper method for present. ensure that termination_policies are set
'''
pillar_termination_policies = copy.deepcopy(
__salt__['config.option'](termination_policies_from_pillar, [])
)
if not termination_policies and pillar_termination_policies:
termination_policies = pillar_termination_policies
return termination_policies | [
"def",
"_determine_termination_policies",
"(",
"termination_policies",
",",
"termination_policies_from_pillar",
")",
":",
"pillar_termination_policies",
"=",
"copy",
".",
"deepcopy",
"(",
"__salt__",
"[",
"'config.option'",
"]",
"(",
"termination_policies_from_pillar",
",",
... | helper method for present. ensure that termination_policies are set | [
"helper",
"method",
"for",
"present",
".",
"ensure",
"that",
"termination_policies",
"are",
"set"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_asg.py#L712-L721 | train |
saltstack/salt | salt/states/boto_asg.py | _determine_scaling_policies | def _determine_scaling_policies(scaling_policies, scaling_policies_from_pillar):
'''
helper method for present. ensure that scaling_policies are set
'''
pillar_scaling_policies = copy.deepcopy(
__salt__['config.option'](scaling_policies_from_pillar, {})
)
if not scaling_policies and pillar_scaling_policies:
scaling_policies = pillar_scaling_policies
return scaling_policies | python | def _determine_scaling_policies(scaling_policies, scaling_policies_from_pillar):
'''
helper method for present. ensure that scaling_policies are set
'''
pillar_scaling_policies = copy.deepcopy(
__salt__['config.option'](scaling_policies_from_pillar, {})
)
if not scaling_policies and pillar_scaling_policies:
scaling_policies = pillar_scaling_policies
return scaling_policies | [
"def",
"_determine_scaling_policies",
"(",
"scaling_policies",
",",
"scaling_policies_from_pillar",
")",
":",
"pillar_scaling_policies",
"=",
"copy",
".",
"deepcopy",
"(",
"__salt__",
"[",
"'config.option'",
"]",
"(",
"scaling_policies_from_pillar",
",",
"{",
"}",
")",
... | helper method for present. ensure that scaling_policies are set | [
"helper",
"method",
"for",
"present",
".",
"ensure",
"that",
"scaling_policies",
"are",
"set"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_asg.py#L724-L733 | train |
saltstack/salt | salt/states/boto_asg.py | _determine_scheduled_actions | def _determine_scheduled_actions(scheduled_actions, scheduled_actions_from_pillar):
'''
helper method for present, ensure scheduled actions are setup
'''
tmp = copy.deepcopy(
__salt__['config.option'](scheduled_actions_from_pillar, {})
)
# merge with data from state
if scheduled_actions:
tmp = dictupdate.update(tmp, scheduled_actions)
return tmp | python | def _determine_scheduled_actions(scheduled_actions, scheduled_actions_from_pillar):
'''
helper method for present, ensure scheduled actions are setup
'''
tmp = copy.deepcopy(
__salt__['config.option'](scheduled_actions_from_pillar, {})
)
# merge with data from state
if scheduled_actions:
tmp = dictupdate.update(tmp, scheduled_actions)
return tmp | [
"def",
"_determine_scheduled_actions",
"(",
"scheduled_actions",
",",
"scheduled_actions_from_pillar",
")",
":",
"tmp",
"=",
"copy",
".",
"deepcopy",
"(",
"__salt__",
"[",
"'config.option'",
"]",
"(",
"scheduled_actions_from_pillar",
",",
"{",
"}",
")",
")",
"# merg... | helper method for present, ensure scheduled actions are setup | [
"helper",
"method",
"for",
"present",
"ensure",
"scheduled",
"actions",
"are",
"setup"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_asg.py#L736-L746 | train |
saltstack/salt | salt/states/boto_asg.py | _determine_notification_info | def _determine_notification_info(notification_arn,
notification_arn_from_pillar,
notification_types,
notification_types_from_pillar):
'''
helper method for present. ensure that notification_configs are set
'''
pillar_arn_list = copy.deepcopy(
__salt__['config.option'](notification_arn_from_pillar, {})
)
pillar_arn = None
if pillar_arn_list:
pillar_arn = pillar_arn_list[0]
pillar_notification_types = copy.deepcopy(
__salt__['config.option'](notification_types_from_pillar, {})
)
arn = notification_arn if notification_arn else pillar_arn
types = notification_types if notification_types else pillar_notification_types
return (arn, types) | python | def _determine_notification_info(notification_arn,
notification_arn_from_pillar,
notification_types,
notification_types_from_pillar):
'''
helper method for present. ensure that notification_configs are set
'''
pillar_arn_list = copy.deepcopy(
__salt__['config.option'](notification_arn_from_pillar, {})
)
pillar_arn = None
if pillar_arn_list:
pillar_arn = pillar_arn_list[0]
pillar_notification_types = copy.deepcopy(
__salt__['config.option'](notification_types_from_pillar, {})
)
arn = notification_arn if notification_arn else pillar_arn
types = notification_types if notification_types else pillar_notification_types
return (arn, types) | [
"def",
"_determine_notification_info",
"(",
"notification_arn",
",",
"notification_arn_from_pillar",
",",
"notification_types",
",",
"notification_types_from_pillar",
")",
":",
"pillar_arn_list",
"=",
"copy",
".",
"deepcopy",
"(",
"__salt__",
"[",
"'config.option'",
"]",
... | helper method for present. ensure that notification_configs are set | [
"helper",
"method",
"for",
"present",
".",
"ensure",
"that",
"notification_configs",
"are",
"set"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_asg.py#L749-L767 | train |
saltstack/salt | salt/states/boto_asg.py | _alarms_present | def _alarms_present(name, min_size_equals_max_size, alarms, alarms_from_pillar, region, key, keyid, profile):
'''
helper method for present. ensure that cloudwatch_alarms are set
'''
# load data from alarms_from_pillar
tmp = copy.deepcopy(__salt__['config.option'](alarms_from_pillar, {}))
# merge with data from alarms
if alarms:
tmp = dictupdate.update(tmp, alarms)
# set alarms, using boto_cloudwatch_alarm.present
merged_return_value = {'name': name, 'result': True, 'comment': '', 'changes': {}}
for _, info in six.iteritems(tmp):
# add asg to name and description
info['name'] = name + ' ' + info['name']
info['attributes']['description'] = name + ' ' + info['attributes']['description']
# add dimension attribute
if 'dimensions' not in info['attributes']:
info['attributes']['dimensions'] = {'AutoScalingGroupName': [name]}
scaling_policy_actions_only = True
# replace ":self:" with our name
for action_type in ['alarm_actions', 'insufficient_data_actions', 'ok_actions']:
if action_type in info['attributes']:
new_actions = []
for action in info['attributes'][action_type]:
if 'scaling_policy' not in action:
scaling_policy_actions_only = False
if ':self:' in action:
action = action.replace(':self:', ':{0}:'.format(name))
new_actions.append(action)
info['attributes'][action_type] = new_actions
# skip alarms that only have actions for scaling policy, if min_size == max_size for this ASG
if scaling_policy_actions_only and min_size_equals_max_size:
continue
# set alarm
kwargs = {
'name': info['name'],
'attributes': info['attributes'],
'region': region,
'key': key,
'keyid': keyid,
'profile': profile,
}
results = __states__['boto_cloudwatch_alarm.present'](**kwargs)
if not results['result']:
merged_return_value['result'] = False
if results.get('changes', {}) != {}:
merged_return_value['changes'][info['name']] = results['changes']
if 'comment' in results:
merged_return_value['comment'] += results['comment']
return merged_return_value | python | def _alarms_present(name, min_size_equals_max_size, alarms, alarms_from_pillar, region, key, keyid, profile):
'''
helper method for present. ensure that cloudwatch_alarms are set
'''
# load data from alarms_from_pillar
tmp = copy.deepcopy(__salt__['config.option'](alarms_from_pillar, {}))
# merge with data from alarms
if alarms:
tmp = dictupdate.update(tmp, alarms)
# set alarms, using boto_cloudwatch_alarm.present
merged_return_value = {'name': name, 'result': True, 'comment': '', 'changes': {}}
for _, info in six.iteritems(tmp):
# add asg to name and description
info['name'] = name + ' ' + info['name']
info['attributes']['description'] = name + ' ' + info['attributes']['description']
# add dimension attribute
if 'dimensions' not in info['attributes']:
info['attributes']['dimensions'] = {'AutoScalingGroupName': [name]}
scaling_policy_actions_only = True
# replace ":self:" with our name
for action_type in ['alarm_actions', 'insufficient_data_actions', 'ok_actions']:
if action_type in info['attributes']:
new_actions = []
for action in info['attributes'][action_type]:
if 'scaling_policy' not in action:
scaling_policy_actions_only = False
if ':self:' in action:
action = action.replace(':self:', ':{0}:'.format(name))
new_actions.append(action)
info['attributes'][action_type] = new_actions
# skip alarms that only have actions for scaling policy, if min_size == max_size for this ASG
if scaling_policy_actions_only and min_size_equals_max_size:
continue
# set alarm
kwargs = {
'name': info['name'],
'attributes': info['attributes'],
'region': region,
'key': key,
'keyid': keyid,
'profile': profile,
}
results = __states__['boto_cloudwatch_alarm.present'](**kwargs)
if not results['result']:
merged_return_value['result'] = False
if results.get('changes', {}) != {}:
merged_return_value['changes'][info['name']] = results['changes']
if 'comment' in results:
merged_return_value['comment'] += results['comment']
return merged_return_value | [
"def",
"_alarms_present",
"(",
"name",
",",
"min_size_equals_max_size",
",",
"alarms",
",",
"alarms_from_pillar",
",",
"region",
",",
"key",
",",
"keyid",
",",
"profile",
")",
":",
"# load data from alarms_from_pillar",
"tmp",
"=",
"copy",
".",
"deepcopy",
"(",
... | helper method for present. ensure that cloudwatch_alarms are set | [
"helper",
"method",
"for",
"present",
".",
"ensure",
"that",
"cloudwatch_alarms",
"are",
"set"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_asg.py#L770-L819 | train |
saltstack/salt | salt/states/boto_asg.py | absent | def absent(
name,
force=False,
region=None,
key=None,
keyid=None,
profile=None,
remove_lc=False):
'''
Ensure the named autoscale group is deleted.
name
Name of the autoscale group.
force
Force deletion of autoscale group.
remove_lc
Delete the launch config as well.
region
The region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
asg = __salt__['boto_asg.get_config'](name, region, key, keyid, profile)
if asg is None:
ret['result'] = False
ret['comment'] = 'Failed to check autoscale group existence.'
elif asg:
if __opts__['test']:
ret['comment'] = 'Autoscale group set to be deleted.'
ret['result'] = None
if remove_lc:
msg = 'Launch configuration {0} is set to be deleted.'.format(asg['launch_config_name'])
ret['comment'] = ' '.join([ret['comment'], msg])
return ret
deleted = __salt__['boto_asg.delete'](name, force, region, key, keyid,
profile)
if deleted:
if remove_lc:
lc_deleted = __salt__['boto_asg.delete_launch_configuration'](asg['launch_config_name'],
region,
key,
keyid,
profile)
if lc_deleted:
if 'launch_config' not in ret['changes']:
ret['changes']['launch_config'] = {}
ret['changes']['launch_config']['deleted'] = asg['launch_config_name']
else:
ret['result'] = False
ret['comment'] = ' '.join([ret['comment'], 'Failed to delete launch configuration.'])
ret['changes']['old'] = asg
ret['changes']['new'] = None
ret['comment'] = 'Deleted autoscale group.'
else:
ret['result'] = False
ret['comment'] = 'Failed to delete autoscale group.'
else:
ret['comment'] = 'Autoscale group does not exist.'
return ret | python | def absent(
name,
force=False,
region=None,
key=None,
keyid=None,
profile=None,
remove_lc=False):
'''
Ensure the named autoscale group is deleted.
name
Name of the autoscale group.
force
Force deletion of autoscale group.
remove_lc
Delete the launch config as well.
region
The region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
asg = __salt__['boto_asg.get_config'](name, region, key, keyid, profile)
if asg is None:
ret['result'] = False
ret['comment'] = 'Failed to check autoscale group existence.'
elif asg:
if __opts__['test']:
ret['comment'] = 'Autoscale group set to be deleted.'
ret['result'] = None
if remove_lc:
msg = 'Launch configuration {0} is set to be deleted.'.format(asg['launch_config_name'])
ret['comment'] = ' '.join([ret['comment'], msg])
return ret
deleted = __salt__['boto_asg.delete'](name, force, region, key, keyid,
profile)
if deleted:
if remove_lc:
lc_deleted = __salt__['boto_asg.delete_launch_configuration'](asg['launch_config_name'],
region,
key,
keyid,
profile)
if lc_deleted:
if 'launch_config' not in ret['changes']:
ret['changes']['launch_config'] = {}
ret['changes']['launch_config']['deleted'] = asg['launch_config_name']
else:
ret['result'] = False
ret['comment'] = ' '.join([ret['comment'], 'Failed to delete launch configuration.'])
ret['changes']['old'] = asg
ret['changes']['new'] = None
ret['comment'] = 'Deleted autoscale group.'
else:
ret['result'] = False
ret['comment'] = 'Failed to delete autoscale group.'
else:
ret['comment'] = 'Autoscale group does not exist.'
return ret | [
"def",
"absent",
"(",
"name",
",",
"force",
"=",
"False",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
",",
"remove_lc",
"=",
"False",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name... | Ensure the named autoscale group is deleted.
name
Name of the autoscale group.
force
Force deletion of autoscale group.
remove_lc
Delete the launch config as well.
region
The region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid. | [
"Ensure",
"the",
"named",
"autoscale",
"group",
"is",
"deleted",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_asg.py#L822-L892 | train |
saltstack/salt | salt/modules/kubernetesmod.py | _setup_conn_old | def _setup_conn_old(**kwargs):
'''
Setup kubernetes API connection singleton the old way
'''
host = __salt__['config.option']('kubernetes.api_url',
'http://localhost:8080')
username = __salt__['config.option']('kubernetes.user')
password = __salt__['config.option']('kubernetes.password')
ca_cert = __salt__['config.option']('kubernetes.certificate-authority-data')
client_cert = __salt__['config.option']('kubernetes.client-certificate-data')
client_key = __salt__['config.option']('kubernetes.client-key-data')
ca_cert_file = __salt__['config.option']('kubernetes.certificate-authority-file')
client_cert_file = __salt__['config.option']('kubernetes.client-certificate-file')
client_key_file = __salt__['config.option']('kubernetes.client-key-file')
# Override default API settings when settings are provided
if 'api_url' in kwargs:
host = kwargs.get('api_url')
if 'api_user' in kwargs:
username = kwargs.get('api_user')
if 'api_password' in kwargs:
password = kwargs.get('api_password')
if 'api_certificate_authority_file' in kwargs:
ca_cert_file = kwargs.get('api_certificate_authority_file')
if 'api_client_certificate_file' in kwargs:
client_cert_file = kwargs.get('api_client_certificate_file')
if 'api_client_key_file' in kwargs:
client_key_file = kwargs.get('api_client_key_file')
if (
kubernetes.client.configuration.host != host or
kubernetes.client.configuration.user != username or
kubernetes.client.configuration.password != password):
# Recreates API connection if settings are changed
kubernetes.client.configuration.__init__()
kubernetes.client.configuration.host = host
kubernetes.client.configuration.user = username
kubernetes.client.configuration.passwd = password
if ca_cert_file:
kubernetes.client.configuration.ssl_ca_cert = ca_cert_file
elif ca_cert:
with tempfile.NamedTemporaryFile(prefix='salt-kube-', delete=False) as ca:
ca.write(base64.b64decode(ca_cert))
kubernetes.client.configuration.ssl_ca_cert = ca.name
else:
kubernetes.client.configuration.ssl_ca_cert = None
if client_cert_file:
kubernetes.client.configuration.cert_file = client_cert_file
elif client_cert:
with tempfile.NamedTemporaryFile(prefix='salt-kube-', delete=False) as c:
c.write(base64.b64decode(client_cert))
kubernetes.client.configuration.cert_file = c.name
else:
kubernetes.client.configuration.cert_file = None
if client_key_file:
kubernetes.client.configuration.key_file = client_key_file
elif client_key:
with tempfile.NamedTemporaryFile(prefix='salt-kube-', delete=False) as k:
k.write(base64.b64decode(client_key))
kubernetes.client.configuration.key_file = k.name
else:
kubernetes.client.configuration.key_file = None
return {} | python | def _setup_conn_old(**kwargs):
'''
Setup kubernetes API connection singleton the old way
'''
host = __salt__['config.option']('kubernetes.api_url',
'http://localhost:8080')
username = __salt__['config.option']('kubernetes.user')
password = __salt__['config.option']('kubernetes.password')
ca_cert = __salt__['config.option']('kubernetes.certificate-authority-data')
client_cert = __salt__['config.option']('kubernetes.client-certificate-data')
client_key = __salt__['config.option']('kubernetes.client-key-data')
ca_cert_file = __salt__['config.option']('kubernetes.certificate-authority-file')
client_cert_file = __salt__['config.option']('kubernetes.client-certificate-file')
client_key_file = __salt__['config.option']('kubernetes.client-key-file')
# Override default API settings when settings are provided
if 'api_url' in kwargs:
host = kwargs.get('api_url')
if 'api_user' in kwargs:
username = kwargs.get('api_user')
if 'api_password' in kwargs:
password = kwargs.get('api_password')
if 'api_certificate_authority_file' in kwargs:
ca_cert_file = kwargs.get('api_certificate_authority_file')
if 'api_client_certificate_file' in kwargs:
client_cert_file = kwargs.get('api_client_certificate_file')
if 'api_client_key_file' in kwargs:
client_key_file = kwargs.get('api_client_key_file')
if (
kubernetes.client.configuration.host != host or
kubernetes.client.configuration.user != username or
kubernetes.client.configuration.password != password):
# Recreates API connection if settings are changed
kubernetes.client.configuration.__init__()
kubernetes.client.configuration.host = host
kubernetes.client.configuration.user = username
kubernetes.client.configuration.passwd = password
if ca_cert_file:
kubernetes.client.configuration.ssl_ca_cert = ca_cert_file
elif ca_cert:
with tempfile.NamedTemporaryFile(prefix='salt-kube-', delete=False) as ca:
ca.write(base64.b64decode(ca_cert))
kubernetes.client.configuration.ssl_ca_cert = ca.name
else:
kubernetes.client.configuration.ssl_ca_cert = None
if client_cert_file:
kubernetes.client.configuration.cert_file = client_cert_file
elif client_cert:
with tempfile.NamedTemporaryFile(prefix='salt-kube-', delete=False) as c:
c.write(base64.b64decode(client_cert))
kubernetes.client.configuration.cert_file = c.name
else:
kubernetes.client.configuration.cert_file = None
if client_key_file:
kubernetes.client.configuration.key_file = client_key_file
elif client_key:
with tempfile.NamedTemporaryFile(prefix='salt-kube-', delete=False) as k:
k.write(base64.b64decode(client_key))
kubernetes.client.configuration.key_file = k.name
else:
kubernetes.client.configuration.key_file = None
return {} | [
"def",
"_setup_conn_old",
"(",
"*",
"*",
"kwargs",
")",
":",
"host",
"=",
"__salt__",
"[",
"'config.option'",
"]",
"(",
"'kubernetes.api_url'",
",",
"'http://localhost:8080'",
")",
"username",
"=",
"__salt__",
"[",
"'config.option'",
"]",
"(",
"'kubernetes.user'",... | Setup kubernetes API connection singleton the old way | [
"Setup",
"kubernetes",
"API",
"connection",
"singleton",
"the",
"old",
"way"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/kubernetesmod.py#L117-L188 | train |
saltstack/salt | salt/modules/kubernetesmod.py | _setup_conn | def _setup_conn(**kwargs):
'''
Setup kubernetes API connection singleton
'''
kubeconfig = kwargs.get('kubeconfig') or __salt__['config.option']('kubernetes.kubeconfig')
kubeconfig_data = kwargs.get('kubeconfig_data') or __salt__['config.option']('kubernetes.kubeconfig-data')
context = kwargs.get('context') or __salt__['config.option']('kubernetes.context')
if (kubeconfig_data and not kubeconfig) or (kubeconfig_data and kwargs.get('kubeconfig_data')):
with tempfile.NamedTemporaryFile(prefix='salt-kubeconfig-', delete=False) as kcfg:
kcfg.write(base64.b64decode(kubeconfig_data))
kubeconfig = kcfg.name
if not (kubeconfig and context):
if kwargs.get('api_url') or __salt__['config.option']('kubernetes.api_url'):
salt.utils.versions.warn_until('Sodium',
'Kubernetes configuration via url, certificate, username and password will be removed in Sodiom. '
'Use \'kubeconfig\' and \'context\' instead.')
try:
return _setup_conn_old(**kwargs)
except Exception:
raise CommandExecutionError('Old style kubernetes configuration is only supported up to python-kubernetes 2.0.0')
else:
raise CommandExecutionError('Invalid kubernetes configuration. Parameter \'kubeconfig\' and \'context\' are required.')
kubernetes.config.load_kube_config(config_file=kubeconfig, context=context)
# The return makes unit testing easier
return {'kubeconfig': kubeconfig, 'context': context} | python | def _setup_conn(**kwargs):
'''
Setup kubernetes API connection singleton
'''
kubeconfig = kwargs.get('kubeconfig') or __salt__['config.option']('kubernetes.kubeconfig')
kubeconfig_data = kwargs.get('kubeconfig_data') or __salt__['config.option']('kubernetes.kubeconfig-data')
context = kwargs.get('context') or __salt__['config.option']('kubernetes.context')
if (kubeconfig_data and not kubeconfig) or (kubeconfig_data and kwargs.get('kubeconfig_data')):
with tempfile.NamedTemporaryFile(prefix='salt-kubeconfig-', delete=False) as kcfg:
kcfg.write(base64.b64decode(kubeconfig_data))
kubeconfig = kcfg.name
if not (kubeconfig and context):
if kwargs.get('api_url') or __salt__['config.option']('kubernetes.api_url'):
salt.utils.versions.warn_until('Sodium',
'Kubernetes configuration via url, certificate, username and password will be removed in Sodiom. '
'Use \'kubeconfig\' and \'context\' instead.')
try:
return _setup_conn_old(**kwargs)
except Exception:
raise CommandExecutionError('Old style kubernetes configuration is only supported up to python-kubernetes 2.0.0')
else:
raise CommandExecutionError('Invalid kubernetes configuration. Parameter \'kubeconfig\' and \'context\' are required.')
kubernetes.config.load_kube_config(config_file=kubeconfig, context=context)
# The return makes unit testing easier
return {'kubeconfig': kubeconfig, 'context': context} | [
"def",
"_setup_conn",
"(",
"*",
"*",
"kwargs",
")",
":",
"kubeconfig",
"=",
"kwargs",
".",
"get",
"(",
"'kubeconfig'",
")",
"or",
"__salt__",
"[",
"'config.option'",
"]",
"(",
"'kubernetes.kubeconfig'",
")",
"kubeconfig_data",
"=",
"kwargs",
".",
"get",
"(",... | Setup kubernetes API connection singleton | [
"Setup",
"kubernetes",
"API",
"connection",
"singleton"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/kubernetesmod.py#L192-L219 | train |
saltstack/salt | salt/modules/kubernetesmod.py | ping | def ping(**kwargs):
'''
Checks connections with the kubernetes API server.
Returns True if the connection can be established, False otherwise.
CLI Example:
salt '*' kubernetes.ping
'''
status = True
try:
nodes(**kwargs)
except CommandExecutionError:
status = False
return status | python | def ping(**kwargs):
'''
Checks connections with the kubernetes API server.
Returns True if the connection can be established, False otherwise.
CLI Example:
salt '*' kubernetes.ping
'''
status = True
try:
nodes(**kwargs)
except CommandExecutionError:
status = False
return status | [
"def",
"ping",
"(",
"*",
"*",
"kwargs",
")",
":",
"status",
"=",
"True",
"try",
":",
"nodes",
"(",
"*",
"*",
"kwargs",
")",
"except",
"CommandExecutionError",
":",
"status",
"=",
"False",
"return",
"status"
] | Checks connections with the kubernetes API server.
Returns True if the connection can be established, False otherwise.
CLI Example:
salt '*' kubernetes.ping | [
"Checks",
"connections",
"with",
"the",
"kubernetes",
"API",
"server",
".",
"Returns",
"True",
"if",
"the",
"connection",
"can",
"be",
"established",
"False",
"otherwise",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/kubernetesmod.py#L251-L265 | train |
saltstack/salt | salt/modules/kubernetesmod.py | nodes | def nodes(**kwargs):
'''
Return the names of the nodes composing the kubernetes cluster
CLI Examples::
salt '*' kubernetes.nodes
salt '*' kubernetes.nodes kubeconfig=/etc/salt/k8s/kubeconfig context=minikube
'''
cfg = _setup_conn(**kwargs)
try:
api_instance = kubernetes.client.CoreV1Api()
api_response = api_instance.list_node()
return [k8s_node['metadata']['name'] for k8s_node in api_response.to_dict().get('items')]
except (ApiException, HTTPError) as exc:
if isinstance(exc, ApiException) and exc.status == 404:
return None
else:
log.exception('Exception when calling CoreV1Api->list_node')
raise CommandExecutionError(exc)
finally:
_cleanup(**cfg) | python | def nodes(**kwargs):
'''
Return the names of the nodes composing the kubernetes cluster
CLI Examples::
salt '*' kubernetes.nodes
salt '*' kubernetes.nodes kubeconfig=/etc/salt/k8s/kubeconfig context=minikube
'''
cfg = _setup_conn(**kwargs)
try:
api_instance = kubernetes.client.CoreV1Api()
api_response = api_instance.list_node()
return [k8s_node['metadata']['name'] for k8s_node in api_response.to_dict().get('items')]
except (ApiException, HTTPError) as exc:
if isinstance(exc, ApiException) and exc.status == 404:
return None
else:
log.exception('Exception when calling CoreV1Api->list_node')
raise CommandExecutionError(exc)
finally:
_cleanup(**cfg) | [
"def",
"nodes",
"(",
"*",
"*",
"kwargs",
")",
":",
"cfg",
"=",
"_setup_conn",
"(",
"*",
"*",
"kwargs",
")",
"try",
":",
"api_instance",
"=",
"kubernetes",
".",
"client",
".",
"CoreV1Api",
"(",
")",
"api_response",
"=",
"api_instance",
".",
"list_node",
... | Return the names of the nodes composing the kubernetes cluster
CLI Examples::
salt '*' kubernetes.nodes
salt '*' kubernetes.nodes kubeconfig=/etc/salt/k8s/kubeconfig context=minikube | [
"Return",
"the",
"names",
"of",
"the",
"nodes",
"composing",
"the",
"kubernetes",
"cluster"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/kubernetesmod.py#L268-L290 | train |
saltstack/salt | salt/modules/kubernetesmod.py | node | def node(name, **kwargs):
'''
Return the details of the node identified by the specified name
CLI Examples::
salt '*' kubernetes.node name='minikube'
'''
cfg = _setup_conn(**kwargs)
try:
api_instance = kubernetes.client.CoreV1Api()
api_response = api_instance.list_node()
except (ApiException, HTTPError) as exc:
if isinstance(exc, ApiException) and exc.status == 404:
return None
else:
log.exception('Exception when calling CoreV1Api->list_node')
raise CommandExecutionError(exc)
finally:
_cleanup(**cfg)
for k8s_node in api_response.items:
if k8s_node.metadata.name == name:
return k8s_node.to_dict()
return None | python | def node(name, **kwargs):
'''
Return the details of the node identified by the specified name
CLI Examples::
salt '*' kubernetes.node name='minikube'
'''
cfg = _setup_conn(**kwargs)
try:
api_instance = kubernetes.client.CoreV1Api()
api_response = api_instance.list_node()
except (ApiException, HTTPError) as exc:
if isinstance(exc, ApiException) and exc.status == 404:
return None
else:
log.exception('Exception when calling CoreV1Api->list_node')
raise CommandExecutionError(exc)
finally:
_cleanup(**cfg)
for k8s_node in api_response.items:
if k8s_node.metadata.name == name:
return k8s_node.to_dict()
return None | [
"def",
"node",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"cfg",
"=",
"_setup_conn",
"(",
"*",
"*",
"kwargs",
")",
"try",
":",
"api_instance",
"=",
"kubernetes",
".",
"client",
".",
"CoreV1Api",
"(",
")",
"api_response",
"=",
"api_instance",
".",
... | Return the details of the node identified by the specified name
CLI Examples::
salt '*' kubernetes.node name='minikube' | [
"Return",
"the",
"details",
"of",
"the",
"node",
"identified",
"by",
"the",
"specified",
"name"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/kubernetesmod.py#L293-L318 | train |
saltstack/salt | salt/modules/kubernetesmod.py | node_add_label | def node_add_label(node_name, label_name, label_value, **kwargs):
'''
Set the value of the label identified by `label_name` to `label_value` on
the node identified by the name `node_name`.
Creates the lable if not present.
CLI Examples::
salt '*' kubernetes.node_add_label node_name="minikube" \
label_name="foo" label_value="bar"
'''
cfg = _setup_conn(**kwargs)
try:
api_instance = kubernetes.client.CoreV1Api()
body = {
'metadata': {
'labels': {
label_name: label_value}
}
}
api_response = api_instance.patch_node(node_name, body)
return api_response
except (ApiException, HTTPError) as exc:
if isinstance(exc, ApiException) and exc.status == 404:
return None
else:
log.exception('Exception when calling CoreV1Api->patch_node')
raise CommandExecutionError(exc)
finally:
_cleanup(**cfg)
return None | python | def node_add_label(node_name, label_name, label_value, **kwargs):
'''
Set the value of the label identified by `label_name` to `label_value` on
the node identified by the name `node_name`.
Creates the lable if not present.
CLI Examples::
salt '*' kubernetes.node_add_label node_name="minikube" \
label_name="foo" label_value="bar"
'''
cfg = _setup_conn(**kwargs)
try:
api_instance = kubernetes.client.CoreV1Api()
body = {
'metadata': {
'labels': {
label_name: label_value}
}
}
api_response = api_instance.patch_node(node_name, body)
return api_response
except (ApiException, HTTPError) as exc:
if isinstance(exc, ApiException) and exc.status == 404:
return None
else:
log.exception('Exception when calling CoreV1Api->patch_node')
raise CommandExecutionError(exc)
finally:
_cleanup(**cfg)
return None | [
"def",
"node_add_label",
"(",
"node_name",
",",
"label_name",
",",
"label_value",
",",
"*",
"*",
"kwargs",
")",
":",
"cfg",
"=",
"_setup_conn",
"(",
"*",
"*",
"kwargs",
")",
"try",
":",
"api_instance",
"=",
"kubernetes",
".",
"client",
".",
"CoreV1Api",
... | Set the value of the label identified by `label_name` to `label_value` on
the node identified by the name `node_name`.
Creates the lable if not present.
CLI Examples::
salt '*' kubernetes.node_add_label node_name="minikube" \
label_name="foo" label_value="bar" | [
"Set",
"the",
"value",
"of",
"the",
"label",
"identified",
"by",
"label_name",
"to",
"label_value",
"on",
"the",
"node",
"identified",
"by",
"the",
"name",
"node_name",
".",
"Creates",
"the",
"lable",
"if",
"not",
"present",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/kubernetesmod.py#L337-L368 | train |
saltstack/salt | salt/modules/kubernetesmod.py | namespaces | def namespaces(**kwargs):
'''
Return the names of the available namespaces
CLI Examples::
salt '*' kubernetes.namespaces
salt '*' kubernetes.namespaces kubeconfig=/etc/salt/k8s/kubeconfig context=minikube
'''
cfg = _setup_conn(**kwargs)
try:
api_instance = kubernetes.client.CoreV1Api()
api_response = api_instance.list_namespace()
return [nms['metadata']['name'] for nms in api_response.to_dict().get('items')]
except (ApiException, HTTPError) as exc:
if isinstance(exc, ApiException) and exc.status == 404:
return None
else:
log.exception('Exception when calling CoreV1Api->list_namespace')
raise CommandExecutionError(exc)
finally:
_cleanup(**cfg) | python | def namespaces(**kwargs):
'''
Return the names of the available namespaces
CLI Examples::
salt '*' kubernetes.namespaces
salt '*' kubernetes.namespaces kubeconfig=/etc/salt/k8s/kubeconfig context=minikube
'''
cfg = _setup_conn(**kwargs)
try:
api_instance = kubernetes.client.CoreV1Api()
api_response = api_instance.list_namespace()
return [nms['metadata']['name'] for nms in api_response.to_dict().get('items')]
except (ApiException, HTTPError) as exc:
if isinstance(exc, ApiException) and exc.status == 404:
return None
else:
log.exception('Exception when calling CoreV1Api->list_namespace')
raise CommandExecutionError(exc)
finally:
_cleanup(**cfg) | [
"def",
"namespaces",
"(",
"*",
"*",
"kwargs",
")",
":",
"cfg",
"=",
"_setup_conn",
"(",
"*",
"*",
"kwargs",
")",
"try",
":",
"api_instance",
"=",
"kubernetes",
".",
"client",
".",
"CoreV1Api",
"(",
")",
"api_response",
"=",
"api_instance",
".",
"list_nam... | Return the names of the available namespaces
CLI Examples::
salt '*' kubernetes.namespaces
salt '*' kubernetes.namespaces kubeconfig=/etc/salt/k8s/kubeconfig context=minikube | [
"Return",
"the",
"names",
"of",
"the",
"available",
"namespaces"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/kubernetesmod.py#L404-L426 | train |
saltstack/salt | salt/modules/kubernetesmod.py | deployments | def deployments(namespace='default', **kwargs):
'''
Return a list of kubernetes deployments defined in the namespace
CLI Examples::
salt '*' kubernetes.deployments
salt '*' kubernetes.deployments namespace=default
'''
cfg = _setup_conn(**kwargs)
try:
api_instance = kubernetes.client.ExtensionsV1beta1Api()
api_response = api_instance.list_namespaced_deployment(namespace)
return [dep['metadata']['name'] for dep in api_response.to_dict().get('items')]
except (ApiException, HTTPError) as exc:
if isinstance(exc, ApiException) and exc.status == 404:
return None
else:
log.exception(
'Exception when calling '
'ExtensionsV1beta1Api->list_namespaced_deployment'
)
raise CommandExecutionError(exc)
finally:
_cleanup(**cfg) | python | def deployments(namespace='default', **kwargs):
'''
Return a list of kubernetes deployments defined in the namespace
CLI Examples::
salt '*' kubernetes.deployments
salt '*' kubernetes.deployments namespace=default
'''
cfg = _setup_conn(**kwargs)
try:
api_instance = kubernetes.client.ExtensionsV1beta1Api()
api_response = api_instance.list_namespaced_deployment(namespace)
return [dep['metadata']['name'] for dep in api_response.to_dict().get('items')]
except (ApiException, HTTPError) as exc:
if isinstance(exc, ApiException) and exc.status == 404:
return None
else:
log.exception(
'Exception when calling '
'ExtensionsV1beta1Api->list_namespaced_deployment'
)
raise CommandExecutionError(exc)
finally:
_cleanup(**cfg) | [
"def",
"deployments",
"(",
"namespace",
"=",
"'default'",
",",
"*",
"*",
"kwargs",
")",
":",
"cfg",
"=",
"_setup_conn",
"(",
"*",
"*",
"kwargs",
")",
"try",
":",
"api_instance",
"=",
"kubernetes",
".",
"client",
".",
"ExtensionsV1beta1Api",
"(",
")",
"ap... | Return a list of kubernetes deployments defined in the namespace
CLI Examples::
salt '*' kubernetes.deployments
salt '*' kubernetes.deployments namespace=default | [
"Return",
"a",
"list",
"of",
"kubernetes",
"deployments",
"defined",
"in",
"the",
"namespace"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/kubernetesmod.py#L429-L454 | train |
saltstack/salt | salt/modules/kubernetesmod.py | services | def services(namespace='default', **kwargs):
'''
Return a list of kubernetes services defined in the namespace
CLI Examples::
salt '*' kubernetes.services
salt '*' kubernetes.services namespace=default
'''
cfg = _setup_conn(**kwargs)
try:
api_instance = kubernetes.client.CoreV1Api()
api_response = api_instance.list_namespaced_service(namespace)
return [srv['metadata']['name'] for srv in api_response.to_dict().get('items')]
except (ApiException, HTTPError) as exc:
if isinstance(exc, ApiException) and exc.status == 404:
return None
else:
log.exception(
'Exception when calling '
'CoreV1Api->list_namespaced_service'
)
raise CommandExecutionError(exc)
finally:
_cleanup(**cfg) | python | def services(namespace='default', **kwargs):
'''
Return a list of kubernetes services defined in the namespace
CLI Examples::
salt '*' kubernetes.services
salt '*' kubernetes.services namespace=default
'''
cfg = _setup_conn(**kwargs)
try:
api_instance = kubernetes.client.CoreV1Api()
api_response = api_instance.list_namespaced_service(namespace)
return [srv['metadata']['name'] for srv in api_response.to_dict().get('items')]
except (ApiException, HTTPError) as exc:
if isinstance(exc, ApiException) and exc.status == 404:
return None
else:
log.exception(
'Exception when calling '
'CoreV1Api->list_namespaced_service'
)
raise CommandExecutionError(exc)
finally:
_cleanup(**cfg) | [
"def",
"services",
"(",
"namespace",
"=",
"'default'",
",",
"*",
"*",
"kwargs",
")",
":",
"cfg",
"=",
"_setup_conn",
"(",
"*",
"*",
"kwargs",
")",
"try",
":",
"api_instance",
"=",
"kubernetes",
".",
"client",
".",
"CoreV1Api",
"(",
")",
"api_response",
... | Return a list of kubernetes services defined in the namespace
CLI Examples::
salt '*' kubernetes.services
salt '*' kubernetes.services namespace=default | [
"Return",
"a",
"list",
"of",
"kubernetes",
"services",
"defined",
"in",
"the",
"namespace"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/kubernetesmod.py#L457-L482 | train |
saltstack/salt | salt/modules/kubernetesmod.py | pods | def pods(namespace='default', **kwargs):
'''
Return a list of kubernetes pods defined in the namespace
CLI Examples::
salt '*' kubernetes.pods
salt '*' kubernetes.pods namespace=default
'''
cfg = _setup_conn(**kwargs)
try:
api_instance = kubernetes.client.CoreV1Api()
api_response = api_instance.list_namespaced_pod(namespace)
return [pod['metadata']['name'] for pod in api_response.to_dict().get('items')]
except (ApiException, HTTPError) as exc:
if isinstance(exc, ApiException) and exc.status == 404:
return None
else:
log.exception(
'Exception when calling '
'CoreV1Api->list_namespaced_pod'
)
raise CommandExecutionError(exc)
finally:
_cleanup(**cfg) | python | def pods(namespace='default', **kwargs):
'''
Return a list of kubernetes pods defined in the namespace
CLI Examples::
salt '*' kubernetes.pods
salt '*' kubernetes.pods namespace=default
'''
cfg = _setup_conn(**kwargs)
try:
api_instance = kubernetes.client.CoreV1Api()
api_response = api_instance.list_namespaced_pod(namespace)
return [pod['metadata']['name'] for pod in api_response.to_dict().get('items')]
except (ApiException, HTTPError) as exc:
if isinstance(exc, ApiException) and exc.status == 404:
return None
else:
log.exception(
'Exception when calling '
'CoreV1Api->list_namespaced_pod'
)
raise CommandExecutionError(exc)
finally:
_cleanup(**cfg) | [
"def",
"pods",
"(",
"namespace",
"=",
"'default'",
",",
"*",
"*",
"kwargs",
")",
":",
"cfg",
"=",
"_setup_conn",
"(",
"*",
"*",
"kwargs",
")",
"try",
":",
"api_instance",
"=",
"kubernetes",
".",
"client",
".",
"CoreV1Api",
"(",
")",
"api_response",
"="... | Return a list of kubernetes pods defined in the namespace
CLI Examples::
salt '*' kubernetes.pods
salt '*' kubernetes.pods namespace=default | [
"Return",
"a",
"list",
"of",
"kubernetes",
"pods",
"defined",
"in",
"the",
"namespace"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/kubernetesmod.py#L485-L510 | train |
saltstack/salt | salt/modules/kubernetesmod.py | configmaps | def configmaps(namespace='default', **kwargs):
'''
Return a list of kubernetes configmaps defined in the namespace
CLI Examples::
salt '*' kubernetes.configmaps
salt '*' kubernetes.configmaps namespace=default
'''
cfg = _setup_conn(**kwargs)
try:
api_instance = kubernetes.client.CoreV1Api()
api_response = api_instance.list_namespaced_config_map(namespace)
return [secret['metadata']['name'] for secret in api_response.to_dict().get('items')]
except (ApiException, HTTPError) as exc:
if isinstance(exc, ApiException) and exc.status == 404:
return None
else:
log.exception(
'Exception when calling '
'CoreV1Api->list_namespaced_config_map'
)
raise CommandExecutionError(exc)
finally:
_cleanup(**cfg) | python | def configmaps(namespace='default', **kwargs):
'''
Return a list of kubernetes configmaps defined in the namespace
CLI Examples::
salt '*' kubernetes.configmaps
salt '*' kubernetes.configmaps namespace=default
'''
cfg = _setup_conn(**kwargs)
try:
api_instance = kubernetes.client.CoreV1Api()
api_response = api_instance.list_namespaced_config_map(namespace)
return [secret['metadata']['name'] for secret in api_response.to_dict().get('items')]
except (ApiException, HTTPError) as exc:
if isinstance(exc, ApiException) and exc.status == 404:
return None
else:
log.exception(
'Exception when calling '
'CoreV1Api->list_namespaced_config_map'
)
raise CommandExecutionError(exc)
finally:
_cleanup(**cfg) | [
"def",
"configmaps",
"(",
"namespace",
"=",
"'default'",
",",
"*",
"*",
"kwargs",
")",
":",
"cfg",
"=",
"_setup_conn",
"(",
"*",
"*",
"kwargs",
")",
"try",
":",
"api_instance",
"=",
"kubernetes",
".",
"client",
".",
"CoreV1Api",
"(",
")",
"api_response",... | Return a list of kubernetes configmaps defined in the namespace
CLI Examples::
salt '*' kubernetes.configmaps
salt '*' kubernetes.configmaps namespace=default | [
"Return",
"a",
"list",
"of",
"kubernetes",
"configmaps",
"defined",
"in",
"the",
"namespace"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/kubernetesmod.py#L541-L566 | train |
saltstack/salt | salt/modules/kubernetesmod.py | show_deployment | def show_deployment(name, namespace='default', **kwargs):
'''
Return the kubernetes deployment defined by name and namespace
CLI Examples::
salt '*' kubernetes.show_deployment my-nginx default
salt '*' kubernetes.show_deployment name=my-nginx namespace=default
'''
cfg = _setup_conn(**kwargs)
try:
api_instance = kubernetes.client.ExtensionsV1beta1Api()
api_response = api_instance.read_namespaced_deployment(name, namespace)
return api_response.to_dict()
except (ApiException, HTTPError) as exc:
if isinstance(exc, ApiException) and exc.status == 404:
return None
else:
log.exception(
'Exception when calling '
'ExtensionsV1beta1Api->read_namespaced_deployment'
)
raise CommandExecutionError(exc)
finally:
_cleanup(**cfg) | python | def show_deployment(name, namespace='default', **kwargs):
'''
Return the kubernetes deployment defined by name and namespace
CLI Examples::
salt '*' kubernetes.show_deployment my-nginx default
salt '*' kubernetes.show_deployment name=my-nginx namespace=default
'''
cfg = _setup_conn(**kwargs)
try:
api_instance = kubernetes.client.ExtensionsV1beta1Api()
api_response = api_instance.read_namespaced_deployment(name, namespace)
return api_response.to_dict()
except (ApiException, HTTPError) as exc:
if isinstance(exc, ApiException) and exc.status == 404:
return None
else:
log.exception(
'Exception when calling '
'ExtensionsV1beta1Api->read_namespaced_deployment'
)
raise CommandExecutionError(exc)
finally:
_cleanup(**cfg) | [
"def",
"show_deployment",
"(",
"name",
",",
"namespace",
"=",
"'default'",
",",
"*",
"*",
"kwargs",
")",
":",
"cfg",
"=",
"_setup_conn",
"(",
"*",
"*",
"kwargs",
")",
"try",
":",
"api_instance",
"=",
"kubernetes",
".",
"client",
".",
"ExtensionsV1beta1Api"... | Return the kubernetes deployment defined by name and namespace
CLI Examples::
salt '*' kubernetes.show_deployment my-nginx default
salt '*' kubernetes.show_deployment name=my-nginx namespace=default | [
"Return",
"the",
"kubernetes",
"deployment",
"defined",
"by",
"name",
"and",
"namespace"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/kubernetesmod.py#L569-L594 | train |
saltstack/salt | salt/modules/kubernetesmod.py | show_namespace | def show_namespace(name, **kwargs):
'''
Return information for a given namespace defined by the specified name
CLI Examples::
salt '*' kubernetes.show_namespace kube-system
'''
cfg = _setup_conn(**kwargs)
try:
api_instance = kubernetes.client.CoreV1Api()
api_response = api_instance.read_namespace(name)
return api_response.to_dict()
except (ApiException, HTTPError) as exc:
if isinstance(exc, ApiException) and exc.status == 404:
return None
else:
log.exception(
'Exception when calling '
'CoreV1Api->read_namespace'
)
raise CommandExecutionError(exc)
finally:
_cleanup(**cfg) | python | def show_namespace(name, **kwargs):
'''
Return information for a given namespace defined by the specified name
CLI Examples::
salt '*' kubernetes.show_namespace kube-system
'''
cfg = _setup_conn(**kwargs)
try:
api_instance = kubernetes.client.CoreV1Api()
api_response = api_instance.read_namespace(name)
return api_response.to_dict()
except (ApiException, HTTPError) as exc:
if isinstance(exc, ApiException) and exc.status == 404:
return None
else:
log.exception(
'Exception when calling '
'CoreV1Api->read_namespace'
)
raise CommandExecutionError(exc)
finally:
_cleanup(**cfg) | [
"def",
"show_namespace",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"cfg",
"=",
"_setup_conn",
"(",
"*",
"*",
"kwargs",
")",
"try",
":",
"api_instance",
"=",
"kubernetes",
".",
"client",
".",
"CoreV1Api",
"(",
")",
"api_response",
"=",
"api_instance... | Return information for a given namespace defined by the specified name
CLI Examples::
salt '*' kubernetes.show_namespace kube-system | [
"Return",
"information",
"for",
"a",
"given",
"namespace",
"defined",
"by",
"the",
"specified",
"name"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/kubernetesmod.py#L653-L677 | train |
saltstack/salt | salt/modules/kubernetesmod.py | show_secret | def show_secret(name, namespace='default', decode=False, **kwargs):
'''
Return the kubernetes secret defined by name and namespace.
The secrets can be decoded if specified by the user. Warning: this has
security implications.
CLI Examples::
salt '*' kubernetes.show_secret confidential default
salt '*' kubernetes.show_secret name=confidential namespace=default
salt '*' kubernetes.show_secret name=confidential decode=True
'''
cfg = _setup_conn(**kwargs)
try:
api_instance = kubernetes.client.CoreV1Api()
api_response = api_instance.read_namespaced_secret(name, namespace)
if api_response.data and (decode or decode == 'True'):
for key in api_response.data:
value = api_response.data[key]
api_response.data[key] = base64.b64decode(value)
return api_response.to_dict()
except (ApiException, HTTPError) as exc:
if isinstance(exc, ApiException) and exc.status == 404:
return None
else:
log.exception(
'Exception when calling '
'CoreV1Api->read_namespaced_secret'
)
raise CommandExecutionError(exc)
finally:
_cleanup(**cfg) | python | def show_secret(name, namespace='default', decode=False, **kwargs):
'''
Return the kubernetes secret defined by name and namespace.
The secrets can be decoded if specified by the user. Warning: this has
security implications.
CLI Examples::
salt '*' kubernetes.show_secret confidential default
salt '*' kubernetes.show_secret name=confidential namespace=default
salt '*' kubernetes.show_secret name=confidential decode=True
'''
cfg = _setup_conn(**kwargs)
try:
api_instance = kubernetes.client.CoreV1Api()
api_response = api_instance.read_namespaced_secret(name, namespace)
if api_response.data and (decode or decode == 'True'):
for key in api_response.data:
value = api_response.data[key]
api_response.data[key] = base64.b64decode(value)
return api_response.to_dict()
except (ApiException, HTTPError) as exc:
if isinstance(exc, ApiException) and exc.status == 404:
return None
else:
log.exception(
'Exception when calling '
'CoreV1Api->read_namespaced_secret'
)
raise CommandExecutionError(exc)
finally:
_cleanup(**cfg) | [
"def",
"show_secret",
"(",
"name",
",",
"namespace",
"=",
"'default'",
",",
"decode",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"cfg",
"=",
"_setup_conn",
"(",
"*",
"*",
"kwargs",
")",
"try",
":",
"api_instance",
"=",
"kubernetes",
".",
"client"... | Return the kubernetes secret defined by name and namespace.
The secrets can be decoded if specified by the user. Warning: this has
security implications.
CLI Examples::
salt '*' kubernetes.show_secret confidential default
salt '*' kubernetes.show_secret name=confidential namespace=default
salt '*' kubernetes.show_secret name=confidential decode=True | [
"Return",
"the",
"kubernetes",
"secret",
"defined",
"by",
"name",
"and",
"namespace",
".",
"The",
"secrets",
"can",
"be",
"decoded",
"if",
"specified",
"by",
"the",
"user",
".",
"Warning",
":",
"this",
"has",
"security",
"implications",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/kubernetesmod.py#L680-L713 | train |
saltstack/salt | salt/modules/kubernetesmod.py | delete_deployment | def delete_deployment(name, namespace='default', **kwargs):
'''
Deletes the kubernetes deployment defined by name and namespace
CLI Examples::
salt '*' kubernetes.delete_deployment my-nginx
salt '*' kubernetes.delete_deployment name=my-nginx namespace=default
'''
cfg = _setup_conn(**kwargs)
body = kubernetes.client.V1DeleteOptions(orphan_dependents=True)
try:
api_instance = kubernetes.client.ExtensionsV1beta1Api()
api_response = api_instance.delete_namespaced_deployment(
name=name,
namespace=namespace,
body=body)
mutable_api_response = api_response.to_dict()
if not salt.utils.platform.is_windows():
try:
with _time_limit(POLLING_TIME_LIMIT):
while show_deployment(name, namespace) is not None:
sleep(1)
else: # pylint: disable=useless-else-on-loop
mutable_api_response['code'] = 200
except TimeoutError:
pass
else:
# Windows has not signal.alarm implementation, so we are just falling
# back to loop-counting.
for i in range(60):
if show_deployment(name, namespace) is None:
mutable_api_response['code'] = 200
break
else:
sleep(1)
if mutable_api_response['code'] != 200:
log.warning('Reached polling time limit. Deployment is not yet '
'deleted, but we are backing off. Sorry, but you\'ll '
'have to check manually.')
return mutable_api_response
except (ApiException, HTTPError) as exc:
if isinstance(exc, ApiException) and exc.status == 404:
return None
else:
log.exception(
'Exception when calling '
'ExtensionsV1beta1Api->delete_namespaced_deployment'
)
raise CommandExecutionError(exc)
finally:
_cleanup(**cfg) | python | def delete_deployment(name, namespace='default', **kwargs):
'''
Deletes the kubernetes deployment defined by name and namespace
CLI Examples::
salt '*' kubernetes.delete_deployment my-nginx
salt '*' kubernetes.delete_deployment name=my-nginx namespace=default
'''
cfg = _setup_conn(**kwargs)
body = kubernetes.client.V1DeleteOptions(orphan_dependents=True)
try:
api_instance = kubernetes.client.ExtensionsV1beta1Api()
api_response = api_instance.delete_namespaced_deployment(
name=name,
namespace=namespace,
body=body)
mutable_api_response = api_response.to_dict()
if not salt.utils.platform.is_windows():
try:
with _time_limit(POLLING_TIME_LIMIT):
while show_deployment(name, namespace) is not None:
sleep(1)
else: # pylint: disable=useless-else-on-loop
mutable_api_response['code'] = 200
except TimeoutError:
pass
else:
# Windows has not signal.alarm implementation, so we are just falling
# back to loop-counting.
for i in range(60):
if show_deployment(name, namespace) is None:
mutable_api_response['code'] = 200
break
else:
sleep(1)
if mutable_api_response['code'] != 200:
log.warning('Reached polling time limit. Deployment is not yet '
'deleted, but we are backing off. Sorry, but you\'ll '
'have to check manually.')
return mutable_api_response
except (ApiException, HTTPError) as exc:
if isinstance(exc, ApiException) and exc.status == 404:
return None
else:
log.exception(
'Exception when calling '
'ExtensionsV1beta1Api->delete_namespaced_deployment'
)
raise CommandExecutionError(exc)
finally:
_cleanup(**cfg) | [
"def",
"delete_deployment",
"(",
"name",
",",
"namespace",
"=",
"'default'",
",",
"*",
"*",
"kwargs",
")",
":",
"cfg",
"=",
"_setup_conn",
"(",
"*",
"*",
"kwargs",
")",
"body",
"=",
"kubernetes",
".",
"client",
".",
"V1DeleteOptions",
"(",
"orphan_dependen... | Deletes the kubernetes deployment defined by name and namespace
CLI Examples::
salt '*' kubernetes.delete_deployment my-nginx
salt '*' kubernetes.delete_deployment name=my-nginx namespace=default | [
"Deletes",
"the",
"kubernetes",
"deployment",
"defined",
"by",
"name",
"and",
"namespace"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/kubernetesmod.py#L746-L798 | train |
saltstack/salt | salt/modules/kubernetesmod.py | delete_service | def delete_service(name, namespace='default', **kwargs):
'''
Deletes the kubernetes service defined by name and namespace
CLI Examples::
salt '*' kubernetes.delete_service my-nginx default
salt '*' kubernetes.delete_service name=my-nginx namespace=default
'''
cfg = _setup_conn(**kwargs)
try:
api_instance = kubernetes.client.CoreV1Api()
api_response = api_instance.delete_namespaced_service(
name=name,
namespace=namespace)
return api_response.to_dict()
except (ApiException, HTTPError) as exc:
if isinstance(exc, ApiException) and exc.status == 404:
return None
else:
log.exception(
'Exception when calling CoreV1Api->delete_namespaced_service'
)
raise CommandExecutionError(exc)
finally:
_cleanup(**cfg) | python | def delete_service(name, namespace='default', **kwargs):
'''
Deletes the kubernetes service defined by name and namespace
CLI Examples::
salt '*' kubernetes.delete_service my-nginx default
salt '*' kubernetes.delete_service name=my-nginx namespace=default
'''
cfg = _setup_conn(**kwargs)
try:
api_instance = kubernetes.client.CoreV1Api()
api_response = api_instance.delete_namespaced_service(
name=name,
namespace=namespace)
return api_response.to_dict()
except (ApiException, HTTPError) as exc:
if isinstance(exc, ApiException) and exc.status == 404:
return None
else:
log.exception(
'Exception when calling CoreV1Api->delete_namespaced_service'
)
raise CommandExecutionError(exc)
finally:
_cleanup(**cfg) | [
"def",
"delete_service",
"(",
"name",
",",
"namespace",
"=",
"'default'",
",",
"*",
"*",
"kwargs",
")",
":",
"cfg",
"=",
"_setup_conn",
"(",
"*",
"*",
"kwargs",
")",
"try",
":",
"api_instance",
"=",
"kubernetes",
".",
"client",
".",
"CoreV1Api",
"(",
"... | Deletes the kubernetes service defined by name and namespace
CLI Examples::
salt '*' kubernetes.delete_service my-nginx default
salt '*' kubernetes.delete_service name=my-nginx namespace=default | [
"Deletes",
"the",
"kubernetes",
"service",
"defined",
"by",
"name",
"and",
"namespace"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/kubernetesmod.py#L801-L828 | train |
saltstack/salt | salt/modules/kubernetesmod.py | delete_pod | def delete_pod(name, namespace='default', **kwargs):
'''
Deletes the kubernetes pod defined by name and namespace
CLI Examples::
salt '*' kubernetes.delete_pod guestbook-708336848-5nl8c default
salt '*' kubernetes.delete_pod name=guestbook-708336848-5nl8c namespace=default
'''
cfg = _setup_conn(**kwargs)
body = kubernetes.client.V1DeleteOptions(orphan_dependents=True)
try:
api_instance = kubernetes.client.CoreV1Api()
api_response = api_instance.delete_namespaced_pod(
name=name,
namespace=namespace,
body=body)
return api_response.to_dict()
except (ApiException, HTTPError) as exc:
if isinstance(exc, ApiException) and exc.status == 404:
return None
else:
log.exception(
'Exception when calling '
'CoreV1Api->delete_namespaced_pod'
)
raise CommandExecutionError(exc)
finally:
_cleanup(**cfg) | python | def delete_pod(name, namespace='default', **kwargs):
'''
Deletes the kubernetes pod defined by name and namespace
CLI Examples::
salt '*' kubernetes.delete_pod guestbook-708336848-5nl8c default
salt '*' kubernetes.delete_pod name=guestbook-708336848-5nl8c namespace=default
'''
cfg = _setup_conn(**kwargs)
body = kubernetes.client.V1DeleteOptions(orphan_dependents=True)
try:
api_instance = kubernetes.client.CoreV1Api()
api_response = api_instance.delete_namespaced_pod(
name=name,
namespace=namespace,
body=body)
return api_response.to_dict()
except (ApiException, HTTPError) as exc:
if isinstance(exc, ApiException) and exc.status == 404:
return None
else:
log.exception(
'Exception when calling '
'CoreV1Api->delete_namespaced_pod'
)
raise CommandExecutionError(exc)
finally:
_cleanup(**cfg) | [
"def",
"delete_pod",
"(",
"name",
",",
"namespace",
"=",
"'default'",
",",
"*",
"*",
"kwargs",
")",
":",
"cfg",
"=",
"_setup_conn",
"(",
"*",
"*",
"kwargs",
")",
"body",
"=",
"kubernetes",
".",
"client",
".",
"V1DeleteOptions",
"(",
"orphan_dependents",
... | Deletes the kubernetes pod defined by name and namespace
CLI Examples::
salt '*' kubernetes.delete_pod guestbook-708336848-5nl8c default
salt '*' kubernetes.delete_pod name=guestbook-708336848-5nl8c namespace=default | [
"Deletes",
"the",
"kubernetes",
"pod",
"defined",
"by",
"name",
"and",
"namespace"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/kubernetesmod.py#L831-L861 | train |
saltstack/salt | salt/modules/kubernetesmod.py | create_pod | def create_pod(
name,
namespace,
metadata,
spec,
source,
template,
saltenv,
**kwargs):
'''
Creates the kubernetes deployment as defined by the user.
'''
body = __create_object_body(
kind='Pod',
obj_class=kubernetes.client.V1Pod,
spec_creator=__dict_to_pod_spec,
name=name,
namespace=namespace,
metadata=metadata,
spec=spec,
source=source,
template=template,
saltenv=saltenv)
cfg = _setup_conn(**kwargs)
try:
api_instance = kubernetes.client.CoreV1Api()
api_response = api_instance.create_namespaced_pod(
namespace, body)
return api_response.to_dict()
except (ApiException, HTTPError) as exc:
if isinstance(exc, ApiException) and exc.status == 404:
return None
else:
log.exception(
'Exception when calling '
'CoreV1Api->create_namespaced_pod'
)
raise CommandExecutionError(exc)
finally:
_cleanup(**cfg) | python | def create_pod(
name,
namespace,
metadata,
spec,
source,
template,
saltenv,
**kwargs):
'''
Creates the kubernetes deployment as defined by the user.
'''
body = __create_object_body(
kind='Pod',
obj_class=kubernetes.client.V1Pod,
spec_creator=__dict_to_pod_spec,
name=name,
namespace=namespace,
metadata=metadata,
spec=spec,
source=source,
template=template,
saltenv=saltenv)
cfg = _setup_conn(**kwargs)
try:
api_instance = kubernetes.client.CoreV1Api()
api_response = api_instance.create_namespaced_pod(
namespace, body)
return api_response.to_dict()
except (ApiException, HTTPError) as exc:
if isinstance(exc, ApiException) and exc.status == 404:
return None
else:
log.exception(
'Exception when calling '
'CoreV1Api->create_namespaced_pod'
)
raise CommandExecutionError(exc)
finally:
_cleanup(**cfg) | [
"def",
"create_pod",
"(",
"name",
",",
"namespace",
",",
"metadata",
",",
"spec",
",",
"source",
",",
"template",
",",
"saltenv",
",",
"*",
"*",
"kwargs",
")",
":",
"body",
"=",
"__create_object_body",
"(",
"kind",
"=",
"'Pod'",
",",
"obj_class",
"=",
... | Creates the kubernetes deployment as defined by the user. | [
"Creates",
"the",
"kubernetes",
"deployment",
"as",
"defined",
"by",
"the",
"user",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/kubernetesmod.py#L1003-L1045 | train |
saltstack/salt | salt/modules/kubernetesmod.py | create_secret | def create_secret(
name,
namespace='default',
data=None,
source=None,
template=None,
saltenv='base',
**kwargs):
'''
Creates the kubernetes secret as defined by the user.
CLI Examples::
salt 'minion1' kubernetes.create_secret \
passwords default '{"db": "letmein"}'
salt 'minion2' kubernetes.create_secret \
name=passwords namespace=default data='{"db": "letmein"}'
'''
if source:
data = __read_and_render_yaml_file(source, template, saltenv)
elif data is None:
data = {}
data = __enforce_only_strings_dict(data)
# encode the secrets using base64 as required by kubernetes
for key in data:
data[key] = base64.b64encode(data[key])
body = kubernetes.client.V1Secret(
metadata=__dict_to_object_meta(name, namespace, {}),
data=data)
cfg = _setup_conn(**kwargs)
try:
api_instance = kubernetes.client.CoreV1Api()
api_response = api_instance.create_namespaced_secret(
namespace, body)
return api_response.to_dict()
except (ApiException, HTTPError) as exc:
if isinstance(exc, ApiException) and exc.status == 404:
return None
else:
log.exception(
'Exception when calling '
'CoreV1Api->create_namespaced_secret'
)
raise CommandExecutionError(exc)
finally:
_cleanup(**cfg) | python | def create_secret(
name,
namespace='default',
data=None,
source=None,
template=None,
saltenv='base',
**kwargs):
'''
Creates the kubernetes secret as defined by the user.
CLI Examples::
salt 'minion1' kubernetes.create_secret \
passwords default '{"db": "letmein"}'
salt 'minion2' kubernetes.create_secret \
name=passwords namespace=default data='{"db": "letmein"}'
'''
if source:
data = __read_and_render_yaml_file(source, template, saltenv)
elif data is None:
data = {}
data = __enforce_only_strings_dict(data)
# encode the secrets using base64 as required by kubernetes
for key in data:
data[key] = base64.b64encode(data[key])
body = kubernetes.client.V1Secret(
metadata=__dict_to_object_meta(name, namespace, {}),
data=data)
cfg = _setup_conn(**kwargs)
try:
api_instance = kubernetes.client.CoreV1Api()
api_response = api_instance.create_namespaced_secret(
namespace, body)
return api_response.to_dict()
except (ApiException, HTTPError) as exc:
if isinstance(exc, ApiException) and exc.status == 404:
return None
else:
log.exception(
'Exception when calling '
'CoreV1Api->create_namespaced_secret'
)
raise CommandExecutionError(exc)
finally:
_cleanup(**cfg) | [
"def",
"create_secret",
"(",
"name",
",",
"namespace",
"=",
"'default'",
",",
"data",
"=",
"None",
",",
"source",
"=",
"None",
",",
"template",
"=",
"None",
",",
"saltenv",
"=",
"'base'",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"source",
":",
"data"... | Creates the kubernetes secret as defined by the user.
CLI Examples::
salt 'minion1' kubernetes.create_secret \
passwords default '{"db": "letmein"}'
salt 'minion2' kubernetes.create_secret \
name=passwords namespace=default data='{"db": "letmein"}' | [
"Creates",
"the",
"kubernetes",
"secret",
"as",
"defined",
"by",
"the",
"user",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/kubernetesmod.py#L1093-L1145 | train |
saltstack/salt | salt/modules/kubernetesmod.py | create_configmap | def create_configmap(
name,
namespace,
data,
source=None,
template=None,
saltenv='base',
**kwargs):
'''
Creates the kubernetes configmap as defined by the user.
CLI Examples::
salt 'minion1' kubernetes.create_configmap \
settings default '{"example.conf": "# example file"}'
salt 'minion2' kubernetes.create_configmap \
name=settings namespace=default data='{"example.conf": "# example file"}'
'''
if source:
data = __read_and_render_yaml_file(source, template, saltenv)
elif data is None:
data = {}
data = __enforce_only_strings_dict(data)
body = kubernetes.client.V1ConfigMap(
metadata=__dict_to_object_meta(name, namespace, {}),
data=data)
cfg = _setup_conn(**kwargs)
try:
api_instance = kubernetes.client.CoreV1Api()
api_response = api_instance.create_namespaced_config_map(
namespace, body)
return api_response.to_dict()
except (ApiException, HTTPError) as exc:
if isinstance(exc, ApiException) and exc.status == 404:
return None
else:
log.exception(
'Exception when calling '
'CoreV1Api->create_namespaced_config_map'
)
raise CommandExecutionError(exc)
finally:
_cleanup(**cfg) | python | def create_configmap(
name,
namespace,
data,
source=None,
template=None,
saltenv='base',
**kwargs):
'''
Creates the kubernetes configmap as defined by the user.
CLI Examples::
salt 'minion1' kubernetes.create_configmap \
settings default '{"example.conf": "# example file"}'
salt 'minion2' kubernetes.create_configmap \
name=settings namespace=default data='{"example.conf": "# example file"}'
'''
if source:
data = __read_and_render_yaml_file(source, template, saltenv)
elif data is None:
data = {}
data = __enforce_only_strings_dict(data)
body = kubernetes.client.V1ConfigMap(
metadata=__dict_to_object_meta(name, namespace, {}),
data=data)
cfg = _setup_conn(**kwargs)
try:
api_instance = kubernetes.client.CoreV1Api()
api_response = api_instance.create_namespaced_config_map(
namespace, body)
return api_response.to_dict()
except (ApiException, HTTPError) as exc:
if isinstance(exc, ApiException) and exc.status == 404:
return None
else:
log.exception(
'Exception when calling '
'CoreV1Api->create_namespaced_config_map'
)
raise CommandExecutionError(exc)
finally:
_cleanup(**cfg) | [
"def",
"create_configmap",
"(",
"name",
",",
"namespace",
",",
"data",
",",
"source",
"=",
"None",
",",
"template",
"=",
"None",
",",
"saltenv",
"=",
"'base'",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"source",
":",
"data",
"=",
"__read_and_render_yaml_f... | Creates the kubernetes configmap as defined by the user.
CLI Examples::
salt 'minion1' kubernetes.create_configmap \
settings default '{"example.conf": "# example file"}'
salt 'minion2' kubernetes.create_configmap \
name=settings namespace=default data='{"example.conf": "# example file"}' | [
"Creates",
"the",
"kubernetes",
"configmap",
"as",
"defined",
"by",
"the",
"user",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/kubernetesmod.py#L1148-L1196 | train |
saltstack/salt | salt/modules/kubernetesmod.py | create_namespace | def create_namespace(
name,
**kwargs):
'''
Creates a namespace with the specified name.
CLI Example:
salt '*' kubernetes.create_namespace salt
salt '*' kubernetes.create_namespace name=salt
'''
meta_obj = kubernetes.client.V1ObjectMeta(name=name)
body = kubernetes.client.V1Namespace(metadata=meta_obj)
body.metadata.name = name
cfg = _setup_conn(**kwargs)
try:
api_instance = kubernetes.client.CoreV1Api()
api_response = api_instance.create_namespace(body)
return api_response.to_dict()
except (ApiException, HTTPError) as exc:
if isinstance(exc, ApiException) and exc.status == 404:
return None
else:
log.exception(
'Exception when calling '
'CoreV1Api->create_namespace'
)
raise CommandExecutionError(exc)
finally:
_cleanup(**cfg) | python | def create_namespace(
name,
**kwargs):
'''
Creates a namespace with the specified name.
CLI Example:
salt '*' kubernetes.create_namespace salt
salt '*' kubernetes.create_namespace name=salt
'''
meta_obj = kubernetes.client.V1ObjectMeta(name=name)
body = kubernetes.client.V1Namespace(metadata=meta_obj)
body.metadata.name = name
cfg = _setup_conn(**kwargs)
try:
api_instance = kubernetes.client.CoreV1Api()
api_response = api_instance.create_namespace(body)
return api_response.to_dict()
except (ApiException, HTTPError) as exc:
if isinstance(exc, ApiException) and exc.status == 404:
return None
else:
log.exception(
'Exception when calling '
'CoreV1Api->create_namespace'
)
raise CommandExecutionError(exc)
finally:
_cleanup(**cfg) | [
"def",
"create_namespace",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"meta_obj",
"=",
"kubernetes",
".",
"client",
".",
"V1ObjectMeta",
"(",
"name",
"=",
"name",
")",
"body",
"=",
"kubernetes",
".",
"client",
".",
"V1Namespace",
"(",
"metadata",
"=... | Creates a namespace with the specified name.
CLI Example:
salt '*' kubernetes.create_namespace salt
salt '*' kubernetes.create_namespace name=salt | [
"Creates",
"a",
"namespace",
"with",
"the",
"specified",
"name",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/kubernetesmod.py#L1199-L1231 | train |
saltstack/salt | salt/modules/kubernetesmod.py | replace_deployment | def replace_deployment(name,
metadata,
spec,
source,
template,
saltenv,
namespace='default',
**kwargs):
'''
Replaces an existing deployment with a new one defined by name and
namespace, having the specificed metadata and spec.
'''
body = __create_object_body(
kind='Deployment',
obj_class=AppsV1beta1Deployment,
spec_creator=__dict_to_deployment_spec,
name=name,
namespace=namespace,
metadata=metadata,
spec=spec,
source=source,
template=template,
saltenv=saltenv)
cfg = _setup_conn(**kwargs)
try:
api_instance = kubernetes.client.ExtensionsV1beta1Api()
api_response = api_instance.replace_namespaced_deployment(
name, namespace, body)
return api_response.to_dict()
except (ApiException, HTTPError) as exc:
if isinstance(exc, ApiException) and exc.status == 404:
return None
else:
log.exception(
'Exception when calling '
'ExtensionsV1beta1Api->replace_namespaced_deployment'
)
raise CommandExecutionError(exc)
finally:
_cleanup(**cfg) | python | def replace_deployment(name,
metadata,
spec,
source,
template,
saltenv,
namespace='default',
**kwargs):
'''
Replaces an existing deployment with a new one defined by name and
namespace, having the specificed metadata and spec.
'''
body = __create_object_body(
kind='Deployment',
obj_class=AppsV1beta1Deployment,
spec_creator=__dict_to_deployment_spec,
name=name,
namespace=namespace,
metadata=metadata,
spec=spec,
source=source,
template=template,
saltenv=saltenv)
cfg = _setup_conn(**kwargs)
try:
api_instance = kubernetes.client.ExtensionsV1beta1Api()
api_response = api_instance.replace_namespaced_deployment(
name, namespace, body)
return api_response.to_dict()
except (ApiException, HTTPError) as exc:
if isinstance(exc, ApiException) and exc.status == 404:
return None
else:
log.exception(
'Exception when calling '
'ExtensionsV1beta1Api->replace_namespaced_deployment'
)
raise CommandExecutionError(exc)
finally:
_cleanup(**cfg) | [
"def",
"replace_deployment",
"(",
"name",
",",
"metadata",
",",
"spec",
",",
"source",
",",
"template",
",",
"saltenv",
",",
"namespace",
"=",
"'default'",
",",
"*",
"*",
"kwargs",
")",
":",
"body",
"=",
"__create_object_body",
"(",
"kind",
"=",
"'Deployme... | Replaces an existing deployment with a new one defined by name and
namespace, having the specificed metadata and spec. | [
"Replaces",
"an",
"existing",
"deployment",
"with",
"a",
"new",
"one",
"defined",
"by",
"name",
"and",
"namespace",
"having",
"the",
"specificed",
"metadata",
"and",
"spec",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/kubernetesmod.py#L1234-L1276 | train |
saltstack/salt | salt/modules/kubernetesmod.py | replace_service | def replace_service(name,
metadata,
spec,
source,
template,
old_service,
saltenv,
namespace='default',
**kwargs):
'''
Replaces an existing service with a new one defined by name and namespace,
having the specificed metadata and spec.
'''
body = __create_object_body(
kind='Service',
obj_class=kubernetes.client.V1Service,
spec_creator=__dict_to_service_spec,
name=name,
namespace=namespace,
metadata=metadata,
spec=spec,
source=source,
template=template,
saltenv=saltenv)
# Some attributes have to be preserved
# otherwise exceptions will be thrown
body.spec.cluster_ip = old_service['spec']['cluster_ip']
body.metadata.resource_version = old_service['metadata']['resource_version']
cfg = _setup_conn(**kwargs)
try:
api_instance = kubernetes.client.CoreV1Api()
api_response = api_instance.replace_namespaced_service(
name, namespace, body)
return api_response.to_dict()
except (ApiException, HTTPError) as exc:
if isinstance(exc, ApiException) and exc.status == 404:
return None
else:
log.exception(
'Exception when calling '
'CoreV1Api->replace_namespaced_service'
)
raise CommandExecutionError(exc)
finally:
_cleanup(**cfg) | python | def replace_service(name,
metadata,
spec,
source,
template,
old_service,
saltenv,
namespace='default',
**kwargs):
'''
Replaces an existing service with a new one defined by name and namespace,
having the specificed metadata and spec.
'''
body = __create_object_body(
kind='Service',
obj_class=kubernetes.client.V1Service,
spec_creator=__dict_to_service_spec,
name=name,
namespace=namespace,
metadata=metadata,
spec=spec,
source=source,
template=template,
saltenv=saltenv)
# Some attributes have to be preserved
# otherwise exceptions will be thrown
body.spec.cluster_ip = old_service['spec']['cluster_ip']
body.metadata.resource_version = old_service['metadata']['resource_version']
cfg = _setup_conn(**kwargs)
try:
api_instance = kubernetes.client.CoreV1Api()
api_response = api_instance.replace_namespaced_service(
name, namespace, body)
return api_response.to_dict()
except (ApiException, HTTPError) as exc:
if isinstance(exc, ApiException) and exc.status == 404:
return None
else:
log.exception(
'Exception when calling '
'CoreV1Api->replace_namespaced_service'
)
raise CommandExecutionError(exc)
finally:
_cleanup(**cfg) | [
"def",
"replace_service",
"(",
"name",
",",
"metadata",
",",
"spec",
",",
"source",
",",
"template",
",",
"old_service",
",",
"saltenv",
",",
"namespace",
"=",
"'default'",
",",
"*",
"*",
"kwargs",
")",
":",
"body",
"=",
"__create_object_body",
"(",
"kind"... | Replaces an existing service with a new one defined by name and namespace,
having the specificed metadata and spec. | [
"Replaces",
"an",
"existing",
"service",
"with",
"a",
"new",
"one",
"defined",
"by",
"name",
"and",
"namespace",
"having",
"the",
"specificed",
"metadata",
"and",
"spec",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/kubernetesmod.py#L1279-L1327 | train |
saltstack/salt | salt/modules/kubernetesmod.py | __create_object_body | def __create_object_body(kind,
obj_class,
spec_creator,
name,
namespace,
metadata,
spec,
source,
template,
saltenv):
'''
Create a Kubernetes Object body instance.
'''
if source:
src_obj = __read_and_render_yaml_file(source, template, saltenv)
if (
not isinstance(src_obj, dict) or
'kind' not in src_obj or
src_obj['kind'] != kind):
raise CommandExecutionError(
'The source file should define only '
'a {0} object'.format(kind))
if 'metadata' in src_obj:
metadata = src_obj['metadata']
if 'spec' in src_obj:
spec = src_obj['spec']
return obj_class(
metadata=__dict_to_object_meta(name, namespace, metadata),
spec=spec_creator(spec)) | python | def __create_object_body(kind,
obj_class,
spec_creator,
name,
namespace,
metadata,
spec,
source,
template,
saltenv):
'''
Create a Kubernetes Object body instance.
'''
if source:
src_obj = __read_and_render_yaml_file(source, template, saltenv)
if (
not isinstance(src_obj, dict) or
'kind' not in src_obj or
src_obj['kind'] != kind):
raise CommandExecutionError(
'The source file should define only '
'a {0} object'.format(kind))
if 'metadata' in src_obj:
metadata = src_obj['metadata']
if 'spec' in src_obj:
spec = src_obj['spec']
return obj_class(
metadata=__dict_to_object_meta(name, namespace, metadata),
spec=spec_creator(spec)) | [
"def",
"__create_object_body",
"(",
"kind",
",",
"obj_class",
",",
"spec_creator",
",",
"name",
",",
"namespace",
",",
"metadata",
",",
"spec",
",",
"source",
",",
"template",
",",
"saltenv",
")",
":",
"if",
"source",
":",
"src_obj",
"=",
"__read_and_render_... | Create a Kubernetes Object body instance. | [
"Create",
"a",
"Kubernetes",
"Object",
"body",
"instance",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/kubernetesmod.py#L1434-L1464 | train |
saltstack/salt | salt/modules/kubernetesmod.py | __read_and_render_yaml_file | def __read_and_render_yaml_file(source,
template,
saltenv):
'''
Read a yaml file and, if needed, renders that using the specifieds
templating. Returns the python objects defined inside of the file.
'''
sfn = __salt__['cp.cache_file'](source, saltenv)
if not sfn:
raise CommandExecutionError(
'Source file \'{0}\' not found'.format(source))
with salt.utils.files.fopen(sfn, 'r') as src:
contents = src.read()
if template:
if template in salt.utils.templates.TEMPLATE_REGISTRY:
# TODO: should we allow user to set also `context` like # pylint: disable=fixme
# `file.managed` does?
# Apply templating
data = salt.utils.templates.TEMPLATE_REGISTRY[template](
contents,
from_str=True,
to_str=True,
saltenv=saltenv,
grains=__grains__,
pillar=__pillar__,
salt=__salt__,
opts=__opts__)
if not data['result']:
# Failed to render the template
raise CommandExecutionError(
'Failed to render file path with error: '
'{0}'.format(data['data'])
)
contents = data['data'].encode('utf-8')
else:
raise CommandExecutionError(
'Unknown template specified: {0}'.format(
template))
return salt.utils.yaml.safe_load(contents) | python | def __read_and_render_yaml_file(source,
template,
saltenv):
'''
Read a yaml file and, if needed, renders that using the specifieds
templating. Returns the python objects defined inside of the file.
'''
sfn = __salt__['cp.cache_file'](source, saltenv)
if not sfn:
raise CommandExecutionError(
'Source file \'{0}\' not found'.format(source))
with salt.utils.files.fopen(sfn, 'r') as src:
contents = src.read()
if template:
if template in salt.utils.templates.TEMPLATE_REGISTRY:
# TODO: should we allow user to set also `context` like # pylint: disable=fixme
# `file.managed` does?
# Apply templating
data = salt.utils.templates.TEMPLATE_REGISTRY[template](
contents,
from_str=True,
to_str=True,
saltenv=saltenv,
grains=__grains__,
pillar=__pillar__,
salt=__salt__,
opts=__opts__)
if not data['result']:
# Failed to render the template
raise CommandExecutionError(
'Failed to render file path with error: '
'{0}'.format(data['data'])
)
contents = data['data'].encode('utf-8')
else:
raise CommandExecutionError(
'Unknown template specified: {0}'.format(
template))
return salt.utils.yaml.safe_load(contents) | [
"def",
"__read_and_render_yaml_file",
"(",
"source",
",",
"template",
",",
"saltenv",
")",
":",
"sfn",
"=",
"__salt__",
"[",
"'cp.cache_file'",
"]",
"(",
"source",
",",
"saltenv",
")",
"if",
"not",
"sfn",
":",
"raise",
"CommandExecutionError",
"(",
"'Source fi... | Read a yaml file and, if needed, renders that using the specifieds
templating. Returns the python objects defined inside of the file. | [
"Read",
"a",
"yaml",
"file",
"and",
"if",
"needed",
"renders",
"that",
"using",
"the",
"specifieds",
"templating",
".",
"Returns",
"the",
"python",
"objects",
"defined",
"inside",
"of",
"the",
"file",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/kubernetesmod.py#L1467-L1510 | train |
saltstack/salt | salt/modules/kubernetesmod.py | __dict_to_object_meta | def __dict_to_object_meta(name, namespace, metadata):
'''
Converts a dictionary into kubernetes ObjectMetaV1 instance.
'''
meta_obj = kubernetes.client.V1ObjectMeta()
meta_obj.namespace = namespace
# Replicate `kubectl [create|replace|apply] --record`
if 'annotations' not in metadata:
metadata['annotations'] = {}
if 'kubernetes.io/change-cause' not in metadata['annotations']:
metadata['annotations']['kubernetes.io/change-cause'] = ' '.join(sys.argv)
for key, value in iteritems(metadata):
if hasattr(meta_obj, key):
setattr(meta_obj, key, value)
if meta_obj.name != name:
log.warning(
'The object already has a name attribute, overwriting it with '
'the one defined inside of salt')
meta_obj.name = name
return meta_obj | python | def __dict_to_object_meta(name, namespace, metadata):
'''
Converts a dictionary into kubernetes ObjectMetaV1 instance.
'''
meta_obj = kubernetes.client.V1ObjectMeta()
meta_obj.namespace = namespace
# Replicate `kubectl [create|replace|apply] --record`
if 'annotations' not in metadata:
metadata['annotations'] = {}
if 'kubernetes.io/change-cause' not in metadata['annotations']:
metadata['annotations']['kubernetes.io/change-cause'] = ' '.join(sys.argv)
for key, value in iteritems(metadata):
if hasattr(meta_obj, key):
setattr(meta_obj, key, value)
if meta_obj.name != name:
log.warning(
'The object already has a name attribute, overwriting it with '
'the one defined inside of salt')
meta_obj.name = name
return meta_obj | [
"def",
"__dict_to_object_meta",
"(",
"name",
",",
"namespace",
",",
"metadata",
")",
":",
"meta_obj",
"=",
"kubernetes",
".",
"client",
".",
"V1ObjectMeta",
"(",
")",
"meta_obj",
".",
"namespace",
"=",
"namespace",
"# Replicate `kubectl [create|replace|apply] --record... | Converts a dictionary into kubernetes ObjectMetaV1 instance. | [
"Converts",
"a",
"dictionary",
"into",
"kubernetes",
"ObjectMetaV1",
"instance",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/kubernetesmod.py#L1513-L1536 | train |
saltstack/salt | salt/modules/kubernetesmod.py | __dict_to_deployment_spec | def __dict_to_deployment_spec(spec):
'''
Converts a dictionary into kubernetes AppsV1beta1DeploymentSpec instance.
'''
spec_obj = AppsV1beta1DeploymentSpec(template=spec.get('template', ''))
for key, value in iteritems(spec):
if hasattr(spec_obj, key):
setattr(spec_obj, key, value)
return spec_obj | python | def __dict_to_deployment_spec(spec):
'''
Converts a dictionary into kubernetes AppsV1beta1DeploymentSpec instance.
'''
spec_obj = AppsV1beta1DeploymentSpec(template=spec.get('template', ''))
for key, value in iteritems(spec):
if hasattr(spec_obj, key):
setattr(spec_obj, key, value)
return spec_obj | [
"def",
"__dict_to_deployment_spec",
"(",
"spec",
")",
":",
"spec_obj",
"=",
"AppsV1beta1DeploymentSpec",
"(",
"template",
"=",
"spec",
".",
"get",
"(",
"'template'",
",",
"''",
")",
")",
"for",
"key",
",",
"value",
"in",
"iteritems",
"(",
"spec",
")",
":",... | Converts a dictionary into kubernetes AppsV1beta1DeploymentSpec instance. | [
"Converts",
"a",
"dictionary",
"into",
"kubernetes",
"AppsV1beta1DeploymentSpec",
"instance",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/kubernetesmod.py#L1539-L1548 | train |
saltstack/salt | salt/modules/kubernetesmod.py | __dict_to_pod_spec | def __dict_to_pod_spec(spec):
'''
Converts a dictionary into kubernetes V1PodSpec instance.
'''
spec_obj = kubernetes.client.V1PodSpec()
for key, value in iteritems(spec):
if hasattr(spec_obj, key):
setattr(spec_obj, key, value)
return spec_obj | python | def __dict_to_pod_spec(spec):
'''
Converts a dictionary into kubernetes V1PodSpec instance.
'''
spec_obj = kubernetes.client.V1PodSpec()
for key, value in iteritems(spec):
if hasattr(spec_obj, key):
setattr(spec_obj, key, value)
return spec_obj | [
"def",
"__dict_to_pod_spec",
"(",
"spec",
")",
":",
"spec_obj",
"=",
"kubernetes",
".",
"client",
".",
"V1PodSpec",
"(",
")",
"for",
"key",
",",
"value",
"in",
"iteritems",
"(",
"spec",
")",
":",
"if",
"hasattr",
"(",
"spec_obj",
",",
"key",
")",
":",
... | Converts a dictionary into kubernetes V1PodSpec instance. | [
"Converts",
"a",
"dictionary",
"into",
"kubernetes",
"V1PodSpec",
"instance",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/kubernetesmod.py#L1551-L1560 | train |
saltstack/salt | salt/modules/kubernetesmod.py | __dict_to_service_spec | def __dict_to_service_spec(spec):
'''
Converts a dictionary into kubernetes V1ServiceSpec instance.
'''
spec_obj = kubernetes.client.V1ServiceSpec()
for key, value in iteritems(spec): # pylint: disable=too-many-nested-blocks
if key == 'ports':
spec_obj.ports = []
for port in value:
kube_port = kubernetes.client.V1ServicePort()
if isinstance(port, dict):
for port_key, port_value in iteritems(port):
if hasattr(kube_port, port_key):
setattr(kube_port, port_key, port_value)
else:
kube_port.port = port
spec_obj.ports.append(kube_port)
elif hasattr(spec_obj, key):
setattr(spec_obj, key, value)
return spec_obj | python | def __dict_to_service_spec(spec):
'''
Converts a dictionary into kubernetes V1ServiceSpec instance.
'''
spec_obj = kubernetes.client.V1ServiceSpec()
for key, value in iteritems(spec): # pylint: disable=too-many-nested-blocks
if key == 'ports':
spec_obj.ports = []
for port in value:
kube_port = kubernetes.client.V1ServicePort()
if isinstance(port, dict):
for port_key, port_value in iteritems(port):
if hasattr(kube_port, port_key):
setattr(kube_port, port_key, port_value)
else:
kube_port.port = port
spec_obj.ports.append(kube_port)
elif hasattr(spec_obj, key):
setattr(spec_obj, key, value)
return spec_obj | [
"def",
"__dict_to_service_spec",
"(",
"spec",
")",
":",
"spec_obj",
"=",
"kubernetes",
".",
"client",
".",
"V1ServiceSpec",
"(",
")",
"for",
"key",
",",
"value",
"in",
"iteritems",
"(",
"spec",
")",
":",
"# pylint: disable=too-many-nested-blocks",
"if",
"key",
... | Converts a dictionary into kubernetes V1ServiceSpec instance. | [
"Converts",
"a",
"dictionary",
"into",
"kubernetes",
"V1ServiceSpec",
"instance",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/kubernetesmod.py#L1563-L1583 | train |
saltstack/salt | salt/modules/kubernetesmod.py | __enforce_only_strings_dict | def __enforce_only_strings_dict(dictionary):
'''
Returns a dictionary that has string keys and values.
'''
ret = {}
for key, value in iteritems(dictionary):
ret[six.text_type(key)] = six.text_type(value)
return ret | python | def __enforce_only_strings_dict(dictionary):
'''
Returns a dictionary that has string keys and values.
'''
ret = {}
for key, value in iteritems(dictionary):
ret[six.text_type(key)] = six.text_type(value)
return ret | [
"def",
"__enforce_only_strings_dict",
"(",
"dictionary",
")",
":",
"ret",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"iteritems",
"(",
"dictionary",
")",
":",
"ret",
"[",
"six",
".",
"text_type",
"(",
"key",
")",
"]",
"=",
"six",
".",
"text_type"... | Returns a dictionary that has string keys and values. | [
"Returns",
"a",
"dictionary",
"that",
"has",
"string",
"keys",
"and",
"values",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/kubernetesmod.py#L1586-L1595 | train |
saltstack/salt | salt/utils/virt.py | VirtKey.accept | def accept(self, pub):
'''
Accept the provided key
'''
try:
with salt.utils.files.fopen(self.path, 'r') as fp_:
expiry = int(fp_.read())
except (OSError, IOError):
log.error(
'Request to sign key for minion \'%s\' on hyper \'%s\' '
'denied: no authorization', self.id, self.hyper
)
return False
except ValueError:
log.error('Invalid expiry data in %s', self.path)
return False
# Limit acceptance window to 10 minutes
# TODO: Move this value to the master config file
if (time.time() - expiry) > 600:
log.warning(
'Request to sign key for minion "%s" on hyper "%s" denied: '
'authorization expired', self.id, self.hyper
)
return False
pubfn = os.path.join(self.opts['pki_dir'],
'minions',
self.id)
with salt.utils.files.fopen(pubfn, 'w+') as fp_:
fp_.write(pub)
self.void()
return True | python | def accept(self, pub):
'''
Accept the provided key
'''
try:
with salt.utils.files.fopen(self.path, 'r') as fp_:
expiry = int(fp_.read())
except (OSError, IOError):
log.error(
'Request to sign key for minion \'%s\' on hyper \'%s\' '
'denied: no authorization', self.id, self.hyper
)
return False
except ValueError:
log.error('Invalid expiry data in %s', self.path)
return False
# Limit acceptance window to 10 minutes
# TODO: Move this value to the master config file
if (time.time() - expiry) > 600:
log.warning(
'Request to sign key for minion "%s" on hyper "%s" denied: '
'authorization expired', self.id, self.hyper
)
return False
pubfn = os.path.join(self.opts['pki_dir'],
'minions',
self.id)
with salt.utils.files.fopen(pubfn, 'w+') as fp_:
fp_.write(pub)
self.void()
return True | [
"def",
"accept",
"(",
"self",
",",
"pub",
")",
":",
"try",
":",
"with",
"salt",
".",
"utils",
".",
"files",
".",
"fopen",
"(",
"self",
".",
"path",
",",
"'r'",
")",
"as",
"fp_",
":",
"expiry",
"=",
"int",
"(",
"fp_",
".",
"read",
"(",
")",
")... | Accept the provided key | [
"Accept",
"the",
"provided",
"key"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/virt.py#L32-L64 | train |
saltstack/salt | salt/utils/virt.py | VirtKey.authorize | def authorize(self):
'''
Prepare the master to expect a signing request
'''
with salt.utils.files.fopen(self.path, 'w+') as fp_:
fp_.write(str(int(time.time()))) # future lint: disable=blacklisted-function
return True | python | def authorize(self):
'''
Prepare the master to expect a signing request
'''
with salt.utils.files.fopen(self.path, 'w+') as fp_:
fp_.write(str(int(time.time()))) # future lint: disable=blacklisted-function
return True | [
"def",
"authorize",
"(",
"self",
")",
":",
"with",
"salt",
".",
"utils",
".",
"files",
".",
"fopen",
"(",
"self",
".",
"path",
",",
"'w+'",
")",
"as",
"fp_",
":",
"fp_",
".",
"write",
"(",
"str",
"(",
"int",
"(",
"time",
".",
"time",
"(",
")",
... | Prepare the master to expect a signing request | [
"Prepare",
"the",
"master",
"to",
"expect",
"a",
"signing",
"request"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/virt.py#L66-L72 | train |
saltstack/salt | salt/ext/backports_abc.py | patch | def patch(patch_inspect=True):
"""
Main entry point for patching the ``collections.abc`` and ``inspect``
standard library modules.
"""
PATCHED['collections.abc.Generator'] = _collections_abc.Generator = Generator
PATCHED['collections.abc.Coroutine'] = _collections_abc.Coroutine = Coroutine
PATCHED['collections.abc.Awaitable'] = _collections_abc.Awaitable = Awaitable
if patch_inspect:
import inspect
PATCHED['inspect.isawaitable'] = inspect.isawaitable = isawaitable | python | def patch(patch_inspect=True):
"""
Main entry point for patching the ``collections.abc`` and ``inspect``
standard library modules.
"""
PATCHED['collections.abc.Generator'] = _collections_abc.Generator = Generator
PATCHED['collections.abc.Coroutine'] = _collections_abc.Coroutine = Coroutine
PATCHED['collections.abc.Awaitable'] = _collections_abc.Awaitable = Awaitable
if patch_inspect:
import inspect
PATCHED['inspect.isawaitable'] = inspect.isawaitable = isawaitable | [
"def",
"patch",
"(",
"patch_inspect",
"=",
"True",
")",
":",
"PATCHED",
"[",
"'collections.abc.Generator'",
"]",
"=",
"_collections_abc",
".",
"Generator",
"=",
"Generator",
"PATCHED",
"[",
"'collections.abc.Coroutine'",
"]",
"=",
"_collections_abc",
".",
"Coroutine... | Main entry point for patching the ``collections.abc`` and ``inspect``
standard library modules. | [
"Main",
"entry",
"point",
"for",
"patching",
"the",
"collections",
".",
"abc",
"and",
"inspect",
"standard",
"library",
"modules",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/ext/backports_abc.py#L205-L216 | train |
saltstack/salt | salt/utils/kickstart.py | parse_auth | def parse_auth(rule):
'''
Parses the auth/authconfig line
'''
parser = argparse.ArgumentParser()
rules = shlex.split(rule)
rules.pop(0)
noargs = ('back', 'test', 'nostart', 'kickstart', 'probe', 'enablecache',
'disablecache', 'disablenis', 'enableshadow', 'disableshadow',
'enablemd5', 'disablemd5', 'enableldap', 'enableldapauth',
'enableldaptls', 'disableldap', 'disableldapauth',
'enablekrb5kdcdns', 'disablekrb5kdcdns', 'enablekrb5realmdns',
'disablekrb5realmdns', 'disablekrb5', 'disablehe-siod',
'enablesmbauth', 'disablesmbauth', 'enablewinbind',
'enablewinbindauth', 'disablewinbind', 'disablewinbindauth',
'enablewinbindusedefaultdomain', 'disablewinbindusedefaultdomain',
'enablewins', 'disablewins')
for arg in noargs:
parser.add_argument('--{0}'.format(arg), dest=arg, action='store_true')
parser.add_argument('--enablenis', dest='enablenis', action='store')
parser.add_argument('--hesiodrhs', dest='hesiodrhs', action='store')
parser.add_argument('--krb5adminserver', dest='krb5adminserver',
action='append')
parser.add_argument('--krb5kdc', dest='krb5kdc', action='append')
parser.add_argument('--ldapbasedn', dest='ldapbasedn', action='store')
parser.add_argument('--ldapserver', dest='ldapserver', action='append')
parser.add_argument('--nisserver', dest='nisserver', action='append')
parser.add_argument('--passalgo', dest='passalgo', action='store')
parser.add_argument('--smbidmapgid', dest='smbidmapgid', action='store')
parser.add_argument('--smbidmapuid', dest='smbidmapuid', action='store')
parser.add_argument('--smbrealm', dest='smbrealm', action='store')
parser.add_argument('--smbsecurity', dest='smbsecurity', action='store',
choices=['user', 'server', 'domain', 'dns'])
parser.add_argument('--smbservers', dest='smbservers', action='store')
parser.add_argument('--smbworkgroup', dest='smbworkgroup', action='store')
parser.add_argument('--winbindjoin', dest='winbindjoin', action='store')
parser.add_argument('--winbindseparator', dest='winbindseparator',
action='store')
parser.add_argument('--winbindtemplatehomedir',
dest='winbindtemplatehomedir', action='store')
parser.add_argument('--winbindtemplateprimarygroup',
dest='winbindtemplateprimarygroup', action='store')
parser.add_argument('--winbindtemplateshell', dest='winbindtemplateshell',
action='store')
parser.add_argument('--enablekrb5', dest='enablekrb5', action='store_true')
if '--enablekrb5' in rules:
parser.add_argument('--krb5realm', dest='krb5realm', action='store',
required=True)
parser.add_argument('--enablehesiod', dest='enablehesiod',
action='store_true')
if '--enablehesiod' in rules:
parser.add_argument('--hesiodlhs', dest='hesiodlhs', action='store',
required=True)
args = clean_args(vars(parser.parse_args(rules)))
parser = None
return args | python | def parse_auth(rule):
'''
Parses the auth/authconfig line
'''
parser = argparse.ArgumentParser()
rules = shlex.split(rule)
rules.pop(0)
noargs = ('back', 'test', 'nostart', 'kickstart', 'probe', 'enablecache',
'disablecache', 'disablenis', 'enableshadow', 'disableshadow',
'enablemd5', 'disablemd5', 'enableldap', 'enableldapauth',
'enableldaptls', 'disableldap', 'disableldapauth',
'enablekrb5kdcdns', 'disablekrb5kdcdns', 'enablekrb5realmdns',
'disablekrb5realmdns', 'disablekrb5', 'disablehe-siod',
'enablesmbauth', 'disablesmbauth', 'enablewinbind',
'enablewinbindauth', 'disablewinbind', 'disablewinbindauth',
'enablewinbindusedefaultdomain', 'disablewinbindusedefaultdomain',
'enablewins', 'disablewins')
for arg in noargs:
parser.add_argument('--{0}'.format(arg), dest=arg, action='store_true')
parser.add_argument('--enablenis', dest='enablenis', action='store')
parser.add_argument('--hesiodrhs', dest='hesiodrhs', action='store')
parser.add_argument('--krb5adminserver', dest='krb5adminserver',
action='append')
parser.add_argument('--krb5kdc', dest='krb5kdc', action='append')
parser.add_argument('--ldapbasedn', dest='ldapbasedn', action='store')
parser.add_argument('--ldapserver', dest='ldapserver', action='append')
parser.add_argument('--nisserver', dest='nisserver', action='append')
parser.add_argument('--passalgo', dest='passalgo', action='store')
parser.add_argument('--smbidmapgid', dest='smbidmapgid', action='store')
parser.add_argument('--smbidmapuid', dest='smbidmapuid', action='store')
parser.add_argument('--smbrealm', dest='smbrealm', action='store')
parser.add_argument('--smbsecurity', dest='smbsecurity', action='store',
choices=['user', 'server', 'domain', 'dns'])
parser.add_argument('--smbservers', dest='smbservers', action='store')
parser.add_argument('--smbworkgroup', dest='smbworkgroup', action='store')
parser.add_argument('--winbindjoin', dest='winbindjoin', action='store')
parser.add_argument('--winbindseparator', dest='winbindseparator',
action='store')
parser.add_argument('--winbindtemplatehomedir',
dest='winbindtemplatehomedir', action='store')
parser.add_argument('--winbindtemplateprimarygroup',
dest='winbindtemplateprimarygroup', action='store')
parser.add_argument('--winbindtemplateshell', dest='winbindtemplateshell',
action='store')
parser.add_argument('--enablekrb5', dest='enablekrb5', action='store_true')
if '--enablekrb5' in rules:
parser.add_argument('--krb5realm', dest='krb5realm', action='store',
required=True)
parser.add_argument('--enablehesiod', dest='enablehesiod',
action='store_true')
if '--enablehesiod' in rules:
parser.add_argument('--hesiodlhs', dest='hesiodlhs', action='store',
required=True)
args = clean_args(vars(parser.parse_args(rules)))
parser = None
return args | [
"def",
"parse_auth",
"(",
"rule",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"rules",
"=",
"shlex",
".",
"split",
"(",
"rule",
")",
"rules",
".",
"pop",
"(",
"0",
")",
"noargs",
"=",
"(",
"'back'",
",",
"'test'",
",",
"'n... | Parses the auth/authconfig line | [
"Parses",
"the",
"auth",
"/",
"authconfig",
"line"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/kickstart.py#L25-L83 | train |
saltstack/salt | salt/utils/kickstart.py | parse_iscsiname | def parse_iscsiname(rule):
'''
Parse the iscsiname line
'''
parser = argparse.ArgumentParser()
rules = shlex.split(rule)
rules.pop(0)
#parser.add_argument('iqn')
args = clean_args(vars(parser.parse_args(rules)))
parser = None
return args | python | def parse_iscsiname(rule):
'''
Parse the iscsiname line
'''
parser = argparse.ArgumentParser()
rules = shlex.split(rule)
rules.pop(0)
#parser.add_argument('iqn')
args = clean_args(vars(parser.parse_args(rules)))
parser = None
return args | [
"def",
"parse_iscsiname",
"(",
"rule",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"rules",
"=",
"shlex",
".",
"split",
"(",
"rule",
")",
"rules",
".",
"pop",
"(",
"0",
")",
"#parser.add_argument('iqn')",
"args",
"=",
"clean_args"... | Parse the iscsiname line | [
"Parse",
"the",
"iscsiname",
"line"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/kickstart.py#L345-L356 | train |
saltstack/salt | salt/utils/kickstart.py | parse_partition | def parse_partition(rule):
'''
Parse the partition line
'''
parser = argparse.ArgumentParser()
rules = shlex.split(rule)
rules.pop(0)
parser.add_argument('mntpoint')
parser.add_argument('--size', dest='size', action='store')
parser.add_argument('--grow', dest='grow', action='store_true')
parser.add_argument('--maxsize', dest='maxsize', action='store')
parser.add_argument('--noformat', dest='noformat', action='store_true')
parser.add_argument('--onpart', '--usepart', dest='onpart', action='store')
parser.add_argument('--ondisk', '--ondrive', dest='ondisk', action='store')
parser.add_argument('--asprimary', dest='asprimary', action='store_true')
parser.add_argument('--fsprofile', dest='fsprofile', action='store')
parser.add_argument('--fstype', dest='fstype', action='store')
parser.add_argument('--fsoptions', dest='fsoptions', action='store')
parser.add_argument('--label', dest='label', action='store')
parser.add_argument('--recommended', dest='recommended',
action='store_true')
parser.add_argument('--onbiosdisk', dest='onbiosdisk', action='store')
parser.add_argument('--encrypted', dest='encrypted', action='store_true')
parser.add_argument('--passphrase', dest='passphrase', action='store')
parser.add_argument('--escrowcert', dest='escrowcert', action='store')
parser.add_argument('--backupphrase', dest='backupphrase', action='store')
args = clean_args(vars(parser.parse_args(rules)))
parser = None
return args | python | def parse_partition(rule):
'''
Parse the partition line
'''
parser = argparse.ArgumentParser()
rules = shlex.split(rule)
rules.pop(0)
parser.add_argument('mntpoint')
parser.add_argument('--size', dest='size', action='store')
parser.add_argument('--grow', dest='grow', action='store_true')
parser.add_argument('--maxsize', dest='maxsize', action='store')
parser.add_argument('--noformat', dest='noformat', action='store_true')
parser.add_argument('--onpart', '--usepart', dest='onpart', action='store')
parser.add_argument('--ondisk', '--ondrive', dest='ondisk', action='store')
parser.add_argument('--asprimary', dest='asprimary', action='store_true')
parser.add_argument('--fsprofile', dest='fsprofile', action='store')
parser.add_argument('--fstype', dest='fstype', action='store')
parser.add_argument('--fsoptions', dest='fsoptions', action='store')
parser.add_argument('--label', dest='label', action='store')
parser.add_argument('--recommended', dest='recommended',
action='store_true')
parser.add_argument('--onbiosdisk', dest='onbiosdisk', action='store')
parser.add_argument('--encrypted', dest='encrypted', action='store_true')
parser.add_argument('--passphrase', dest='passphrase', action='store')
parser.add_argument('--escrowcert', dest='escrowcert', action='store')
parser.add_argument('--backupphrase', dest='backupphrase', action='store')
args = clean_args(vars(parser.parse_args(rules)))
parser = None
return args | [
"def",
"parse_partition",
"(",
"rule",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"rules",
"=",
"shlex",
".",
"split",
"(",
"rule",
")",
"rules",
".",
"pop",
"(",
"0",
")",
"parser",
".",
"add_argument",
"(",
"'mntpoint'",
")... | Parse the partition line | [
"Parse",
"the",
"partition",
"line"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/kickstart.py#L528-L557 | train |
saltstack/salt | salt/utils/kickstart.py | parse_raid | def parse_raid(rule):
'''
Parse the raid line
'''
parser = argparse.ArgumentParser()
rules = shlex.split(rule)
rules.pop(0)
partitions = []
newrules = []
for count in range(0, len(rules)):
if count == 0:
newrules.append(rules[count])
continue
elif rules[count].startswith('--'):
newrules.append(rules[count])
continue
else:
partitions.append(rules[count])
rules = newrules
parser.add_argument('mntpoint')
parser.add_argument('--level', dest='level', action='store')
parser.add_argument('--device', dest='device', action='store')
parser.add_argument('--spares', dest='spares', action='store')
parser.add_argument('--fstype', dest='fstype', action='store')
parser.add_argument('--fsoptions', dest='fsoptions', action='store')
parser.add_argument('--label', dest='label', action='store')
parser.add_argument('--noformat', dest='noformat', action='store_true')
parser.add_argument('--useexisting', dest='useexisting',
action='store_true')
parser.add_argument('--encrypted', dest='encrypted', action='store_true')
parser.add_argument('--passphrase', dest='passphrase', action='store')
parser.add_argument('--escrowcert', dest='escrowcert', action='store')
parser.add_argument('--backuppassphrase', dest='backuppassphrase',
action='store')
args = clean_args(vars(parser.parse_args(rules)))
if partitions:
args['partitions'] = partitions
parser = None
return args | python | def parse_raid(rule):
'''
Parse the raid line
'''
parser = argparse.ArgumentParser()
rules = shlex.split(rule)
rules.pop(0)
partitions = []
newrules = []
for count in range(0, len(rules)):
if count == 0:
newrules.append(rules[count])
continue
elif rules[count].startswith('--'):
newrules.append(rules[count])
continue
else:
partitions.append(rules[count])
rules = newrules
parser.add_argument('mntpoint')
parser.add_argument('--level', dest='level', action='store')
parser.add_argument('--device', dest='device', action='store')
parser.add_argument('--spares', dest='spares', action='store')
parser.add_argument('--fstype', dest='fstype', action='store')
parser.add_argument('--fsoptions', dest='fsoptions', action='store')
parser.add_argument('--label', dest='label', action='store')
parser.add_argument('--noformat', dest='noformat', action='store_true')
parser.add_argument('--useexisting', dest='useexisting',
action='store_true')
parser.add_argument('--encrypted', dest='encrypted', action='store_true')
parser.add_argument('--passphrase', dest='passphrase', action='store')
parser.add_argument('--escrowcert', dest='escrowcert', action='store')
parser.add_argument('--backuppassphrase', dest='backuppassphrase',
action='store')
args = clean_args(vars(parser.parse_args(rules)))
if partitions:
args['partitions'] = partitions
parser = None
return args | [
"def",
"parse_raid",
"(",
"rule",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"rules",
"=",
"shlex",
".",
"split",
"(",
"rule",
")",
"rules",
".",
"pop",
"(",
"0",
")",
"partitions",
"=",
"[",
"]",
"newrules",
"=",
"[",
"]... | Parse the raid line | [
"Parse",
"the",
"raid",
"line"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/kickstart.py#L560-L601 | train |
saltstack/salt | salt/utils/kickstart.py | parse_services | def parse_services(rule):
'''
Parse the services line
'''
parser = argparse.ArgumentParser()
rules = shlex.split(rule)
rules.pop(0)
parser.add_argument('--disabled', dest='disabled', action='store')
parser.add_argument('--enabled', dest='enabled', action='store')
args = clean_args(vars(parser.parse_args(rules)))
parser = None
return args | python | def parse_services(rule):
'''
Parse the services line
'''
parser = argparse.ArgumentParser()
rules = shlex.split(rule)
rules.pop(0)
parser.add_argument('--disabled', dest='disabled', action='store')
parser.add_argument('--enabled', dest='enabled', action='store')
args = clean_args(vars(parser.parse_args(rules)))
parser = None
return args | [
"def",
"parse_services",
"(",
"rule",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"rules",
"=",
"shlex",
".",
"split",
"(",
"rule",
")",
"rules",
".",
"pop",
"(",
"0",
")",
"parser",
".",
"add_argument",
"(",
"'--disabled'",
"... | Parse the services line | [
"Parse",
"the",
"services",
"line"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/kickstart.py#L689-L701 | train |
saltstack/salt | salt/utils/kickstart.py | parse_updates | def parse_updates(rule):
'''
Parse the updates line
'''
rules = shlex.split(rule)
rules.pop(0)
return {'url': rules[0]} if rules else True | python | def parse_updates(rule):
'''
Parse the updates line
'''
rules = shlex.split(rule)
rules.pop(0)
return {'url': rules[0]} if rules else True | [
"def",
"parse_updates",
"(",
"rule",
")",
":",
"rules",
"=",
"shlex",
".",
"split",
"(",
"rule",
")",
"rules",
".",
"pop",
"(",
"0",
")",
"return",
"{",
"'url'",
":",
"rules",
"[",
"0",
"]",
"}",
"if",
"rules",
"else",
"True"
] | Parse the updates line | [
"Parse",
"the",
"updates",
"line"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/kickstart.py#L739-L745 | train |
saltstack/salt | salt/utils/kickstart.py | parse_volgroup | def parse_volgroup(rule):
'''
Parse the volgroup line
'''
parser = argparse.ArgumentParser()
rules = shlex.split(rule)
rules.pop(0)
partitions = []
newrules = []
for count in range(0, len(rules)):
if count == 0:
newrules.append(rules[count])
continue
elif rules[count].startswith('--'):
newrules.append(rules[count])
continue
else:
partitions.append(rules[count])
rules = newrules
parser.add_argument('name')
parser.add_argument('--noformat', dest='noformat', action='store_true')
parser.add_argument('--useexisting', dest='useexisting',
action='store_true')
parser.add_argument('--pesize', dest='pesize', action='store')
parser.add_argument('--reserved-space', dest='reserved-space',
action='store')
parser.add_argument('--reserved-percent', dest='reserved-percent',
action='store')
args = clean_args(vars(parser.parse_args(rules)))
if partitions:
args['partitions'] = partitions
parser = None
return args | python | def parse_volgroup(rule):
'''
Parse the volgroup line
'''
parser = argparse.ArgumentParser()
rules = shlex.split(rule)
rules.pop(0)
partitions = []
newrules = []
for count in range(0, len(rules)):
if count == 0:
newrules.append(rules[count])
continue
elif rules[count].startswith('--'):
newrules.append(rules[count])
continue
else:
partitions.append(rules[count])
rules = newrules
parser.add_argument('name')
parser.add_argument('--noformat', dest='noformat', action='store_true')
parser.add_argument('--useexisting', dest='useexisting',
action='store_true')
parser.add_argument('--pesize', dest='pesize', action='store')
parser.add_argument('--reserved-space', dest='reserved-space',
action='store')
parser.add_argument('--reserved-percent', dest='reserved-percent',
action='store')
args = clean_args(vars(parser.parse_args(rules)))
if partitions:
args['partitions'] = partitions
parser = None
return args | [
"def",
"parse_volgroup",
"(",
"rule",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"rules",
"=",
"shlex",
".",
"split",
"(",
"rule",
")",
"rules",
".",
"pop",
"(",
"0",
")",
"partitions",
"=",
"[",
"]",
"newrules",
"=",
"[",
... | Parse the volgroup line | [
"Parse",
"the",
"volgroup",
"line"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/kickstart.py#L820-L855 | train |
saltstack/salt | salt/utils/kickstart.py | mksls | def mksls(src, dst=None):
'''
Convert a kickstart file to an SLS file
'''
mode = 'command'
sls = {}
ks_opts = {}
with salt.utils.files.fopen(src, 'r') as fh_:
for line in fh_:
if line.startswith('#'):
continue
if mode == 'command':
if line.startswith('auth ') or line.startswith('authconfig '):
ks_opts['auth'] = parse_auth(line)
elif line.startswith('autopart'):
ks_opts['autopath'] = parse_autopart(line)
elif line.startswith('autostep'):
ks_opts['autostep'] = parse_autostep(line)
elif line.startswith('bootloader'):
ks_opts['bootloader'] = parse_bootloader(line)
elif line.startswith('btrfs'):
ks_opts['btrfs'] = parse_btrfs(line)
elif line.startswith('cdrom'):
ks_opts['cdrom'] = True
elif line.startswith('clearpart'):
ks_opts['clearpart'] = parse_clearpart(line)
elif line.startswith('cmdline'):
ks_opts['cmdline'] = True
elif line.startswith('device'):
ks_opts['device'] = parse_device(line)
elif line.startswith('dmraid'):
ks_opts['dmraid'] = parse_dmraid(line)
elif line.startswith('driverdisk'):
ks_opts['driverdisk'] = parse_driverdisk(line)
elif line.startswith('firewall'):
ks_opts['firewall'] = parse_firewall(line)
elif line.startswith('firstboot'):
ks_opts['firstboot'] = parse_firstboot(line)
elif line.startswith('group'):
ks_opts['group'] = parse_group(line)
elif line.startswith('graphical'):
ks_opts['graphical'] = True
elif line.startswith('halt'):
ks_opts['halt'] = True
elif line.startswith('harddrive'):
ks_opts['harddrive'] = True
elif line.startswith('ignoredisk'):
ks_opts['ignoredisk'] = parse_ignoredisk(line)
elif line.startswith('install'):
ks_opts['install'] = True
elif line.startswith('iscsi'):
ks_opts['iscsi'] = parse_iscsi(line)
elif line.startswith('iscsiname'):
ks_opts['iscsiname'] = parse_iscsiname(line)
elif line.startswith('keyboard'):
ks_opts['keyboard'] = parse_keyboard(line)
elif line.startswith('lang'):
ks_opts['lang'] = parse_lang(line)
elif line.startswith('logvol'):
if 'logvol' not in ks_opts.keys():
ks_opts['logvol'] = []
ks_opts['logvol'].append(parse_logvol(line))
elif line.startswith('logging'):
ks_opts['logging'] = parse_logging(line)
elif line.startswith('mediacheck'):
ks_opts['mediacheck'] = True
elif line.startswith('monitor'):
ks_opts['monitor'] = parse_monitor(line)
elif line.startswith('multipath'):
ks_opts['multipath'] = parse_multipath(line)
elif line.startswith('network'):
if 'network' not in ks_opts.keys():
ks_opts['network'] = []
ks_opts['network'].append(parse_network(line))
elif line.startswith('nfs'):
ks_opts['nfs'] = True
elif line.startswith('part ') or line.startswith('partition'):
if 'part' not in ks_opts.keys():
ks_opts['part'] = []
ks_opts['part'].append(parse_partition(line))
elif line.startswith('poweroff'):
ks_opts['poweroff'] = True
elif line.startswith('raid'):
if 'raid' not in ks_opts.keys():
ks_opts['raid'] = []
ks_opts['raid'].append(parse_raid(line))
elif line.startswith('reboot'):
ks_opts['reboot'] = parse_reboot(line)
elif line.startswith('repo'):
ks_opts['repo'] = parse_repo(line)
elif line.startswith('rescue'):
ks_opts['rescue'] = parse_rescue(line)
elif line.startswith('rootpw'):
ks_opts['rootpw'] = parse_rootpw(line)
elif line.startswith('selinux'):
ks_opts['selinux'] = parse_selinux(line)
elif line.startswith('services'):
ks_opts['services'] = parse_services(line)
elif line.startswith('shutdown'):
ks_opts['shutdown'] = True
elif line.startswith('sshpw'):
ks_opts['sshpw'] = parse_sshpw(line)
elif line.startswith('skipx'):
ks_opts['skipx'] = True
elif line.startswith('text'):
ks_opts['text'] = True
elif line.startswith('timezone'):
ks_opts['timezone'] = parse_timezone(line)
elif line.startswith('updates'):
ks_opts['updates'] = parse_updates(line)
elif line.startswith('upgrade'):
ks_opts['upgrade'] = parse_upgrade(line)
elif line.startswith('url'):
ks_opts['url'] = True
elif line.startswith('user'):
ks_opts['user'] = parse_user(line)
elif line.startswith('vnc'):
ks_opts['vnc'] = parse_vnc(line)
elif line.startswith('volgroup'):
ks_opts['volgroup'] = parse_volgroup(line)
elif line.startswith('xconfig'):
ks_opts['xconfig'] = parse_xconfig(line)
elif line.startswith('zerombr'):
ks_opts['zerombr'] = True
elif line.startswith('zfcp'):
ks_opts['zfcp'] = parse_zfcp(line)
if line.startswith('%include'):
rules = shlex.split(line)
if not ks_opts['include']:
ks_opts['include'] = []
ks_opts['include'].append(rules[1])
if line.startswith('%ksappend'):
rules = shlex.split(line)
if not ks_opts['ksappend']:
ks_opts['ksappend'] = []
ks_opts['ksappend'].append(rules[1])
if line.startswith('%packages'):
mode = 'packages'
if 'packages' not in ks_opts.keys():
ks_opts['packages'] = {'packages': {}}
parser = argparse.ArgumentParser()
opts = shlex.split(line)
opts.pop(0)
parser.add_argument('--default', dest='default', action='store_true')
parser.add_argument('--excludedocs', dest='excludedocs',
action='store_true')
parser.add_argument('--ignoremissing', dest='ignoremissing',
action='store_true')
parser.add_argument('--instLangs', dest='instLangs', action='store')
parser.add_argument('--multilib', dest='multilib', action='store_true')
parser.add_argument('--nodefaults', dest='nodefaults',
action='store_true')
parser.add_argument('--optional', dest='optional', action='store_true')
parser.add_argument('--nobase', dest='nobase', action='store_true')
args = clean_args(vars(parser.parse_args(opts)))
ks_opts['packages']['options'] = args
continue
if line.startswith('%pre'):
mode = 'pre'
parser = argparse.ArgumentParser()
opts = shlex.split(line)
opts.pop(0)
parser.add_argument('--interpreter', dest='interpreter',
action='store')
parser.add_argument('--erroronfail', dest='erroronfail',
action='store_true')
parser.add_argument('--log', dest='log', action='store')
args = clean_args(vars(parser.parse_args(opts)))
ks_opts['pre'] = {'options': args, 'script': ''}
continue
if line.startswith('%post'):
mode = 'post'
parser = argparse.ArgumentParser()
opts = shlex.split(line)
opts.pop(0)
parser.add_argument('--nochroot', dest='nochroot', action='store_true')
parser.add_argument('--interpreter', dest='interpreter',
action='store')
parser.add_argument('--erroronfail', dest='erroronfail',
action='store_true')
parser.add_argument('--log', dest='log', action='store')
args = clean_args(vars(parser.parse_args(opts)))
ks_opts['post'] = {'options': args, 'script': ''}
continue
if line.startswith('%end'):
mode = None
if mode == 'packages':
if line.startswith('-'):
package = line.replace('-', '', 1).strip()
ks_opts['packages']['packages'][package] = False
else:
ks_opts['packages']['packages'][line.strip()] = True
if mode == 'pre':
ks_opts['pre']['script'] += line
if mode == 'post':
ks_opts['post']['script'] += line
# Set language
sls[ks_opts['lang']['lang']] = {'locale': ['system']}
# Set keyboard
sls[ks_opts['keyboard']['xlayouts']] = {'keyboard': ['system']}
# Set timezone
sls[ks_opts['timezone']['timezone']] = {'timezone': ['system']}
if 'utc' in ks_opts['timezone'].keys():
sls[ks_opts['timezone']['timezone']]['timezone'].append('utc')
# Set network
if 'network' in ks_opts.keys():
for interface in ks_opts['network']:
device = interface.get('device', None)
if device is not None:
del interface['device']
sls[device] = {'proto': interface['bootproto']}
del interface['bootproto']
if 'onboot' in interface.keys():
if 'no' in interface['onboot']:
sls[device]['enabled'] = False
else:
sls[device]['enabled'] = True
del interface['onboot']
if 'noipv4' in interface.keys():
sls[device]['ipv4'] = {'enabled': False}
del interface['noipv4']
if 'noipv6' in interface.keys():
sls[device]['ipv6'] = {'enabled': False}
del interface['noipv6']
for option in interface:
if type(interface[option]) is bool:
sls[device][option] = {'enabled': [interface[option]]}
else:
sls[device][option] = interface[option]
if 'hostname' in interface:
sls['system'] = {
'network.system': {
'enabled': True,
'hostname': interface['hostname'],
'apply_hostname': True,
}
}
# Set selinux
if 'selinux' in ks_opts.keys():
for mode in ks_opts['selinux']:
sls[mode] = {'selinux': ['mode']}
# Get package data together
if 'nobase' not in ks_opts['packages']['options']:
sls['base'] = {'pkg_group': ['installed']}
packages = ks_opts['packages']['packages']
for package in packages:
if not packages[package]:
continue
if package and packages[package] is True:
if package.startswith('@'):
pkg_group = package.replace('@', '', 1)
sls[pkg_group] = {'pkg_group': ['installed']}
else:
sls[package] = {'pkg': ['installed']}
elif packages[package] is False:
sls[package] = {'pkg': ['absent']}
if dst:
with salt.utils.files.fopen(dst, 'w') as fp_:
salt.utils.yaml.safe_dump(sls, fp_, default_flow_style=False)
else:
return salt.utils.yaml.safe_dump(sls, default_flow_style=False) | python | def mksls(src, dst=None):
'''
Convert a kickstart file to an SLS file
'''
mode = 'command'
sls = {}
ks_opts = {}
with salt.utils.files.fopen(src, 'r') as fh_:
for line in fh_:
if line.startswith('#'):
continue
if mode == 'command':
if line.startswith('auth ') or line.startswith('authconfig '):
ks_opts['auth'] = parse_auth(line)
elif line.startswith('autopart'):
ks_opts['autopath'] = parse_autopart(line)
elif line.startswith('autostep'):
ks_opts['autostep'] = parse_autostep(line)
elif line.startswith('bootloader'):
ks_opts['bootloader'] = parse_bootloader(line)
elif line.startswith('btrfs'):
ks_opts['btrfs'] = parse_btrfs(line)
elif line.startswith('cdrom'):
ks_opts['cdrom'] = True
elif line.startswith('clearpart'):
ks_opts['clearpart'] = parse_clearpart(line)
elif line.startswith('cmdline'):
ks_opts['cmdline'] = True
elif line.startswith('device'):
ks_opts['device'] = parse_device(line)
elif line.startswith('dmraid'):
ks_opts['dmraid'] = parse_dmraid(line)
elif line.startswith('driverdisk'):
ks_opts['driverdisk'] = parse_driverdisk(line)
elif line.startswith('firewall'):
ks_opts['firewall'] = parse_firewall(line)
elif line.startswith('firstboot'):
ks_opts['firstboot'] = parse_firstboot(line)
elif line.startswith('group'):
ks_opts['group'] = parse_group(line)
elif line.startswith('graphical'):
ks_opts['graphical'] = True
elif line.startswith('halt'):
ks_opts['halt'] = True
elif line.startswith('harddrive'):
ks_opts['harddrive'] = True
elif line.startswith('ignoredisk'):
ks_opts['ignoredisk'] = parse_ignoredisk(line)
elif line.startswith('install'):
ks_opts['install'] = True
elif line.startswith('iscsi'):
ks_opts['iscsi'] = parse_iscsi(line)
elif line.startswith('iscsiname'):
ks_opts['iscsiname'] = parse_iscsiname(line)
elif line.startswith('keyboard'):
ks_opts['keyboard'] = parse_keyboard(line)
elif line.startswith('lang'):
ks_opts['lang'] = parse_lang(line)
elif line.startswith('logvol'):
if 'logvol' not in ks_opts.keys():
ks_opts['logvol'] = []
ks_opts['logvol'].append(parse_logvol(line))
elif line.startswith('logging'):
ks_opts['logging'] = parse_logging(line)
elif line.startswith('mediacheck'):
ks_opts['mediacheck'] = True
elif line.startswith('monitor'):
ks_opts['monitor'] = parse_monitor(line)
elif line.startswith('multipath'):
ks_opts['multipath'] = parse_multipath(line)
elif line.startswith('network'):
if 'network' not in ks_opts.keys():
ks_opts['network'] = []
ks_opts['network'].append(parse_network(line))
elif line.startswith('nfs'):
ks_opts['nfs'] = True
elif line.startswith('part ') or line.startswith('partition'):
if 'part' not in ks_opts.keys():
ks_opts['part'] = []
ks_opts['part'].append(parse_partition(line))
elif line.startswith('poweroff'):
ks_opts['poweroff'] = True
elif line.startswith('raid'):
if 'raid' not in ks_opts.keys():
ks_opts['raid'] = []
ks_opts['raid'].append(parse_raid(line))
elif line.startswith('reboot'):
ks_opts['reboot'] = parse_reboot(line)
elif line.startswith('repo'):
ks_opts['repo'] = parse_repo(line)
elif line.startswith('rescue'):
ks_opts['rescue'] = parse_rescue(line)
elif line.startswith('rootpw'):
ks_opts['rootpw'] = parse_rootpw(line)
elif line.startswith('selinux'):
ks_opts['selinux'] = parse_selinux(line)
elif line.startswith('services'):
ks_opts['services'] = parse_services(line)
elif line.startswith('shutdown'):
ks_opts['shutdown'] = True
elif line.startswith('sshpw'):
ks_opts['sshpw'] = parse_sshpw(line)
elif line.startswith('skipx'):
ks_opts['skipx'] = True
elif line.startswith('text'):
ks_opts['text'] = True
elif line.startswith('timezone'):
ks_opts['timezone'] = parse_timezone(line)
elif line.startswith('updates'):
ks_opts['updates'] = parse_updates(line)
elif line.startswith('upgrade'):
ks_opts['upgrade'] = parse_upgrade(line)
elif line.startswith('url'):
ks_opts['url'] = True
elif line.startswith('user'):
ks_opts['user'] = parse_user(line)
elif line.startswith('vnc'):
ks_opts['vnc'] = parse_vnc(line)
elif line.startswith('volgroup'):
ks_opts['volgroup'] = parse_volgroup(line)
elif line.startswith('xconfig'):
ks_opts['xconfig'] = parse_xconfig(line)
elif line.startswith('zerombr'):
ks_opts['zerombr'] = True
elif line.startswith('zfcp'):
ks_opts['zfcp'] = parse_zfcp(line)
if line.startswith('%include'):
rules = shlex.split(line)
if not ks_opts['include']:
ks_opts['include'] = []
ks_opts['include'].append(rules[1])
if line.startswith('%ksappend'):
rules = shlex.split(line)
if not ks_opts['ksappend']:
ks_opts['ksappend'] = []
ks_opts['ksappend'].append(rules[1])
if line.startswith('%packages'):
mode = 'packages'
if 'packages' not in ks_opts.keys():
ks_opts['packages'] = {'packages': {}}
parser = argparse.ArgumentParser()
opts = shlex.split(line)
opts.pop(0)
parser.add_argument('--default', dest='default', action='store_true')
parser.add_argument('--excludedocs', dest='excludedocs',
action='store_true')
parser.add_argument('--ignoremissing', dest='ignoremissing',
action='store_true')
parser.add_argument('--instLangs', dest='instLangs', action='store')
parser.add_argument('--multilib', dest='multilib', action='store_true')
parser.add_argument('--nodefaults', dest='nodefaults',
action='store_true')
parser.add_argument('--optional', dest='optional', action='store_true')
parser.add_argument('--nobase', dest='nobase', action='store_true')
args = clean_args(vars(parser.parse_args(opts)))
ks_opts['packages']['options'] = args
continue
if line.startswith('%pre'):
mode = 'pre'
parser = argparse.ArgumentParser()
opts = shlex.split(line)
opts.pop(0)
parser.add_argument('--interpreter', dest='interpreter',
action='store')
parser.add_argument('--erroronfail', dest='erroronfail',
action='store_true')
parser.add_argument('--log', dest='log', action='store')
args = clean_args(vars(parser.parse_args(opts)))
ks_opts['pre'] = {'options': args, 'script': ''}
continue
if line.startswith('%post'):
mode = 'post'
parser = argparse.ArgumentParser()
opts = shlex.split(line)
opts.pop(0)
parser.add_argument('--nochroot', dest='nochroot', action='store_true')
parser.add_argument('--interpreter', dest='interpreter',
action='store')
parser.add_argument('--erroronfail', dest='erroronfail',
action='store_true')
parser.add_argument('--log', dest='log', action='store')
args = clean_args(vars(parser.parse_args(opts)))
ks_opts['post'] = {'options': args, 'script': ''}
continue
if line.startswith('%end'):
mode = None
if mode == 'packages':
if line.startswith('-'):
package = line.replace('-', '', 1).strip()
ks_opts['packages']['packages'][package] = False
else:
ks_opts['packages']['packages'][line.strip()] = True
if mode == 'pre':
ks_opts['pre']['script'] += line
if mode == 'post':
ks_opts['post']['script'] += line
# Set language
sls[ks_opts['lang']['lang']] = {'locale': ['system']}
# Set keyboard
sls[ks_opts['keyboard']['xlayouts']] = {'keyboard': ['system']}
# Set timezone
sls[ks_opts['timezone']['timezone']] = {'timezone': ['system']}
if 'utc' in ks_opts['timezone'].keys():
sls[ks_opts['timezone']['timezone']]['timezone'].append('utc')
# Set network
if 'network' in ks_opts.keys():
for interface in ks_opts['network']:
device = interface.get('device', None)
if device is not None:
del interface['device']
sls[device] = {'proto': interface['bootproto']}
del interface['bootproto']
if 'onboot' in interface.keys():
if 'no' in interface['onboot']:
sls[device]['enabled'] = False
else:
sls[device]['enabled'] = True
del interface['onboot']
if 'noipv4' in interface.keys():
sls[device]['ipv4'] = {'enabled': False}
del interface['noipv4']
if 'noipv6' in interface.keys():
sls[device]['ipv6'] = {'enabled': False}
del interface['noipv6']
for option in interface:
if type(interface[option]) is bool:
sls[device][option] = {'enabled': [interface[option]]}
else:
sls[device][option] = interface[option]
if 'hostname' in interface:
sls['system'] = {
'network.system': {
'enabled': True,
'hostname': interface['hostname'],
'apply_hostname': True,
}
}
# Set selinux
if 'selinux' in ks_opts.keys():
for mode in ks_opts['selinux']:
sls[mode] = {'selinux': ['mode']}
# Get package data together
if 'nobase' not in ks_opts['packages']['options']:
sls['base'] = {'pkg_group': ['installed']}
packages = ks_opts['packages']['packages']
for package in packages:
if not packages[package]:
continue
if package and packages[package] is True:
if package.startswith('@'):
pkg_group = package.replace('@', '', 1)
sls[pkg_group] = {'pkg_group': ['installed']}
else:
sls[package] = {'pkg': ['installed']}
elif packages[package] is False:
sls[package] = {'pkg': ['absent']}
if dst:
with salt.utils.files.fopen(dst, 'w') as fp_:
salt.utils.yaml.safe_dump(sls, fp_, default_flow_style=False)
else:
return salt.utils.yaml.safe_dump(sls, default_flow_style=False) | [
"def",
"mksls",
"(",
"src",
",",
"dst",
"=",
"None",
")",
":",
"mode",
"=",
"'command'",
"sls",
"=",
"{",
"}",
"ks_opts",
"=",
"{",
"}",
"with",
"salt",
".",
"utils",
".",
"files",
".",
"fopen",
"(",
"src",
",",
"'r'",
")",
"as",
"fh_",
":",
... | Convert a kickstart file to an SLS file | [
"Convert",
"a",
"kickstart",
"file",
"to",
"an",
"SLS",
"file"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/kickstart.py#L891-L1178 | train |
saltstack/salt | salt/modules/mac_power.py | _validate_sleep | def _validate_sleep(minutes):
'''
Helper function that validates the minutes parameter. Can be any number
between 1 and 180. Can also be the string values "Never" and "Off".
Because "On" and "Off" get converted to boolean values on the command line
it will error if "On" is passed
Returns: The value to be passed to the command
'''
# Must be a value between 1 and 180 or Never/Off
if isinstance(minutes, six.string_types):
if minutes.lower() in ['never', 'off']:
return 'Never'
else:
msg = 'Invalid String Value for Minutes.\n' \
'String values must be "Never" or "Off".\n' \
'Passed: {0}'.format(minutes)
raise SaltInvocationError(msg)
elif isinstance(minutes, bool):
if minutes:
msg = 'Invalid Boolean Value for Minutes.\n' \
'Boolean value "On" or "True" is not allowed.\n' \
'Salt CLI converts "On" to boolean True.\n' \
'Passed: {0}'.format(minutes)
raise SaltInvocationError(msg)
else:
return 'Never'
elif isinstance(minutes, int):
if minutes in range(1, 181):
return minutes
else:
msg = 'Invalid Integer Value for Minutes.\n' \
'Integer values must be between 1 and 180.\n' \
'Passed: {0}'.format(minutes)
raise SaltInvocationError(msg)
else:
msg = 'Unknown Variable Type Passed for Minutes.\n' \
'Passed: {0}'.format(minutes)
raise SaltInvocationError(msg) | python | def _validate_sleep(minutes):
'''
Helper function that validates the minutes parameter. Can be any number
between 1 and 180. Can also be the string values "Never" and "Off".
Because "On" and "Off" get converted to boolean values on the command line
it will error if "On" is passed
Returns: The value to be passed to the command
'''
# Must be a value between 1 and 180 or Never/Off
if isinstance(minutes, six.string_types):
if minutes.lower() in ['never', 'off']:
return 'Never'
else:
msg = 'Invalid String Value for Minutes.\n' \
'String values must be "Never" or "Off".\n' \
'Passed: {0}'.format(minutes)
raise SaltInvocationError(msg)
elif isinstance(minutes, bool):
if minutes:
msg = 'Invalid Boolean Value for Minutes.\n' \
'Boolean value "On" or "True" is not allowed.\n' \
'Salt CLI converts "On" to boolean True.\n' \
'Passed: {0}'.format(minutes)
raise SaltInvocationError(msg)
else:
return 'Never'
elif isinstance(minutes, int):
if minutes in range(1, 181):
return minutes
else:
msg = 'Invalid Integer Value for Minutes.\n' \
'Integer values must be between 1 and 180.\n' \
'Passed: {0}'.format(minutes)
raise SaltInvocationError(msg)
else:
msg = 'Unknown Variable Type Passed for Minutes.\n' \
'Passed: {0}'.format(minutes)
raise SaltInvocationError(msg) | [
"def",
"_validate_sleep",
"(",
"minutes",
")",
":",
"# Must be a value between 1 and 180 or Never/Off",
"if",
"isinstance",
"(",
"minutes",
",",
"six",
".",
"string_types",
")",
":",
"if",
"minutes",
".",
"lower",
"(",
")",
"in",
"[",
"'never'",
",",
"'off'",
... | Helper function that validates the minutes parameter. Can be any number
between 1 and 180. Can also be the string values "Never" and "Off".
Because "On" and "Off" get converted to boolean values on the command line
it will error if "On" is passed
Returns: The value to be passed to the command | [
"Helper",
"function",
"that",
"validates",
"the",
"minutes",
"parameter",
".",
"Can",
"be",
"any",
"number",
"between",
"1",
"and",
"180",
".",
"Can",
"also",
"be",
"the",
"string",
"values",
"Never",
"and",
"Off",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_power.py#L33-L72 | train |
saltstack/salt | salt/modules/mac_power.py | set_sleep | def set_sleep(minutes):
'''
Sets the amount of idle time until the machine sleeps. Sets the same value
for Computer, Display, and Hard Disk. Pass "Never" or "Off" for computers
that should never sleep.
:param minutes: Can be an integer between 1 and 180 or "Never" or "Off"
:ptype: int, str
:return: True if successful, False if not
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' power.set_sleep 120
salt '*' power.set_sleep never
'''
value = _validate_sleep(minutes)
cmd = 'systemsetup -setsleep {0}'.format(value)
salt.utils.mac_utils.execute_return_success(cmd)
state = []
for check in (get_computer_sleep, get_display_sleep, get_harddisk_sleep):
state.append(salt.utils.mac_utils.confirm_updated(
value,
check,
))
return all(state) | python | def set_sleep(minutes):
'''
Sets the amount of idle time until the machine sleeps. Sets the same value
for Computer, Display, and Hard Disk. Pass "Never" or "Off" for computers
that should never sleep.
:param minutes: Can be an integer between 1 and 180 or "Never" or "Off"
:ptype: int, str
:return: True if successful, False if not
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' power.set_sleep 120
salt '*' power.set_sleep never
'''
value = _validate_sleep(minutes)
cmd = 'systemsetup -setsleep {0}'.format(value)
salt.utils.mac_utils.execute_return_success(cmd)
state = []
for check in (get_computer_sleep, get_display_sleep, get_harddisk_sleep):
state.append(salt.utils.mac_utils.confirm_updated(
value,
check,
))
return all(state) | [
"def",
"set_sleep",
"(",
"minutes",
")",
":",
"value",
"=",
"_validate_sleep",
"(",
"minutes",
")",
"cmd",
"=",
"'systemsetup -setsleep {0}'",
".",
"format",
"(",
"value",
")",
"salt",
".",
"utils",
".",
"mac_utils",
".",
"execute_return_success",
"(",
"cmd",
... | Sets the amount of idle time until the machine sleeps. Sets the same value
for Computer, Display, and Hard Disk. Pass "Never" or "Off" for computers
that should never sleep.
:param minutes: Can be an integer between 1 and 180 or "Never" or "Off"
:ptype: int, str
:return: True if successful, False if not
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' power.set_sleep 120
salt '*' power.set_sleep never | [
"Sets",
"the",
"amount",
"of",
"idle",
"time",
"until",
"the",
"machine",
"sleeps",
".",
"Sets",
"the",
"same",
"value",
"for",
"Computer",
"Display",
"and",
"Hard",
"Disk",
".",
"Pass",
"Never",
"or",
"Off",
"for",
"computers",
"that",
"should",
"never",
... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_power.py#L96-L125 | train |
saltstack/salt | salt/modules/mac_power.py | get_computer_sleep | def get_computer_sleep():
'''
Display the amount of idle time until the computer sleeps.
:return: A string representing the sleep settings for the computer
:rtype: str
CLI Example:
..code-block:: bash
salt '*' power.get_computer_sleep
'''
ret = salt.utils.mac_utils.execute_return_result(
'systemsetup -getcomputersleep')
return salt.utils.mac_utils.parse_return(ret) | python | def get_computer_sleep():
'''
Display the amount of idle time until the computer sleeps.
:return: A string representing the sleep settings for the computer
:rtype: str
CLI Example:
..code-block:: bash
salt '*' power.get_computer_sleep
'''
ret = salt.utils.mac_utils.execute_return_result(
'systemsetup -getcomputersleep')
return salt.utils.mac_utils.parse_return(ret) | [
"def",
"get_computer_sleep",
"(",
")",
":",
"ret",
"=",
"salt",
".",
"utils",
".",
"mac_utils",
".",
"execute_return_result",
"(",
"'systemsetup -getcomputersleep'",
")",
"return",
"salt",
".",
"utils",
".",
"mac_utils",
".",
"parse_return",
"(",
"ret",
")"
] | Display the amount of idle time until the computer sleeps.
:return: A string representing the sleep settings for the computer
:rtype: str
CLI Example:
..code-block:: bash
salt '*' power.get_computer_sleep | [
"Display",
"the",
"amount",
"of",
"idle",
"time",
"until",
"the",
"computer",
"sleeps",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_power.py#L128-L143 | train |
saltstack/salt | salt/modules/mac_power.py | set_computer_sleep | def set_computer_sleep(minutes):
'''
Set the amount of idle time until the computer sleeps. Pass "Never" of "Off"
to never sleep.
:param minutes: Can be an integer between 1 and 180 or "Never" or "Off"
:ptype: int, str
:return: True if successful, False if not
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' power.set_computer_sleep 120
salt '*' power.set_computer_sleep off
'''
value = _validate_sleep(minutes)
cmd = 'systemsetup -setcomputersleep {0}'.format(value)
salt.utils.mac_utils.execute_return_success(cmd)
return salt.utils.mac_utils.confirm_updated(
str(value),
get_computer_sleep,
) | python | def set_computer_sleep(minutes):
'''
Set the amount of idle time until the computer sleeps. Pass "Never" of "Off"
to never sleep.
:param minutes: Can be an integer between 1 and 180 or "Never" or "Off"
:ptype: int, str
:return: True if successful, False if not
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' power.set_computer_sleep 120
salt '*' power.set_computer_sleep off
'''
value = _validate_sleep(minutes)
cmd = 'systemsetup -setcomputersleep {0}'.format(value)
salt.utils.mac_utils.execute_return_success(cmd)
return salt.utils.mac_utils.confirm_updated(
str(value),
get_computer_sleep,
) | [
"def",
"set_computer_sleep",
"(",
"minutes",
")",
":",
"value",
"=",
"_validate_sleep",
"(",
"minutes",
")",
"cmd",
"=",
"'systemsetup -setcomputersleep {0}'",
".",
"format",
"(",
"value",
")",
"salt",
".",
"utils",
".",
"mac_utils",
".",
"execute_return_success",... | Set the amount of idle time until the computer sleeps. Pass "Never" of "Off"
to never sleep.
:param minutes: Can be an integer between 1 and 180 or "Never" or "Off"
:ptype: int, str
:return: True if successful, False if not
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' power.set_computer_sleep 120
salt '*' power.set_computer_sleep off | [
"Set",
"the",
"amount",
"of",
"idle",
"time",
"until",
"the",
"computer",
"sleeps",
".",
"Pass",
"Never",
"of",
"Off",
"to",
"never",
"sleep",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_power.py#L146-L171 | train |
saltstack/salt | salt/modules/mac_power.py | get_display_sleep | def get_display_sleep():
'''
Display the amount of idle time until the display sleeps.
:return: A string representing the sleep settings for the displey
:rtype: str
CLI Example:
..code-block:: bash
salt '*' power.get_display_sleep
'''
ret = salt.utils.mac_utils.execute_return_result(
'systemsetup -getdisplaysleep')
return salt.utils.mac_utils.parse_return(ret) | python | def get_display_sleep():
'''
Display the amount of idle time until the display sleeps.
:return: A string representing the sleep settings for the displey
:rtype: str
CLI Example:
..code-block:: bash
salt '*' power.get_display_sleep
'''
ret = salt.utils.mac_utils.execute_return_result(
'systemsetup -getdisplaysleep')
return salt.utils.mac_utils.parse_return(ret) | [
"def",
"get_display_sleep",
"(",
")",
":",
"ret",
"=",
"salt",
".",
"utils",
".",
"mac_utils",
".",
"execute_return_result",
"(",
"'systemsetup -getdisplaysleep'",
")",
"return",
"salt",
".",
"utils",
".",
"mac_utils",
".",
"parse_return",
"(",
"ret",
")"
] | Display the amount of idle time until the display sleeps.
:return: A string representing the sleep settings for the displey
:rtype: str
CLI Example:
..code-block:: bash
salt '*' power.get_display_sleep | [
"Display",
"the",
"amount",
"of",
"idle",
"time",
"until",
"the",
"display",
"sleeps",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_power.py#L174-L189 | train |
saltstack/salt | salt/modules/mac_power.py | set_display_sleep | def set_display_sleep(minutes):
'''
Set the amount of idle time until the display sleeps. Pass "Never" of "Off"
to never sleep.
:param minutes: Can be an integer between 1 and 180 or "Never" or "Off"
:ptype: int, str
:return: True if successful, False if not
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' power.set_display_sleep 120
salt '*' power.set_display_sleep off
'''
value = _validate_sleep(minutes)
cmd = 'systemsetup -setdisplaysleep {0}'.format(value)
salt.utils.mac_utils.execute_return_success(cmd)
return salt.utils.mac_utils.confirm_updated(
str(value),
get_display_sleep,
) | python | def set_display_sleep(minutes):
'''
Set the amount of idle time until the display sleeps. Pass "Never" of "Off"
to never sleep.
:param minutes: Can be an integer between 1 and 180 or "Never" or "Off"
:ptype: int, str
:return: True if successful, False if not
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' power.set_display_sleep 120
salt '*' power.set_display_sleep off
'''
value = _validate_sleep(minutes)
cmd = 'systemsetup -setdisplaysleep {0}'.format(value)
salt.utils.mac_utils.execute_return_success(cmd)
return salt.utils.mac_utils.confirm_updated(
str(value),
get_display_sleep,
) | [
"def",
"set_display_sleep",
"(",
"minutes",
")",
":",
"value",
"=",
"_validate_sleep",
"(",
"minutes",
")",
"cmd",
"=",
"'systemsetup -setdisplaysleep {0}'",
".",
"format",
"(",
"value",
")",
"salt",
".",
"utils",
".",
"mac_utils",
".",
"execute_return_success",
... | Set the amount of idle time until the display sleeps. Pass "Never" of "Off"
to never sleep.
:param minutes: Can be an integer between 1 and 180 or "Never" or "Off"
:ptype: int, str
:return: True if successful, False if not
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' power.set_display_sleep 120
salt '*' power.set_display_sleep off | [
"Set",
"the",
"amount",
"of",
"idle",
"time",
"until",
"the",
"display",
"sleeps",
".",
"Pass",
"Never",
"of",
"Off",
"to",
"never",
"sleep",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_power.py#L192-L217 | train |
saltstack/salt | salt/modules/mac_power.py | get_harddisk_sleep | def get_harddisk_sleep():
'''
Display the amount of idle time until the hard disk sleeps.
:return: A string representing the sleep settings for the hard disk
:rtype: str
CLI Example:
..code-block:: bash
salt '*' power.get_harddisk_sleep
'''
ret = salt.utils.mac_utils.execute_return_result(
'systemsetup -getharddisksleep')
return salt.utils.mac_utils.parse_return(ret) | python | def get_harddisk_sleep():
'''
Display the amount of idle time until the hard disk sleeps.
:return: A string representing the sleep settings for the hard disk
:rtype: str
CLI Example:
..code-block:: bash
salt '*' power.get_harddisk_sleep
'''
ret = salt.utils.mac_utils.execute_return_result(
'systemsetup -getharddisksleep')
return salt.utils.mac_utils.parse_return(ret) | [
"def",
"get_harddisk_sleep",
"(",
")",
":",
"ret",
"=",
"salt",
".",
"utils",
".",
"mac_utils",
".",
"execute_return_result",
"(",
"'systemsetup -getharddisksleep'",
")",
"return",
"salt",
".",
"utils",
".",
"mac_utils",
".",
"parse_return",
"(",
"ret",
")"
] | Display the amount of idle time until the hard disk sleeps.
:return: A string representing the sleep settings for the hard disk
:rtype: str
CLI Example:
..code-block:: bash
salt '*' power.get_harddisk_sleep | [
"Display",
"the",
"amount",
"of",
"idle",
"time",
"until",
"the",
"hard",
"disk",
"sleeps",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_power.py#L220-L235 | train |
saltstack/salt | salt/modules/mac_power.py | set_harddisk_sleep | def set_harddisk_sleep(minutes):
'''
Set the amount of idle time until the harddisk sleeps. Pass "Never" of "Off"
to never sleep.
:param minutes: Can be an integer between 1 and 180 or "Never" or "Off"
:ptype: int, str
:return: True if successful, False if not
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' power.set_harddisk_sleep 120
salt '*' power.set_harddisk_sleep off
'''
value = _validate_sleep(minutes)
cmd = 'systemsetup -setharddisksleep {0}'.format(value)
salt.utils.mac_utils.execute_return_success(cmd)
return salt.utils.mac_utils.confirm_updated(
str(value),
get_harddisk_sleep,
) | python | def set_harddisk_sleep(minutes):
'''
Set the amount of idle time until the harddisk sleeps. Pass "Never" of "Off"
to never sleep.
:param minutes: Can be an integer between 1 and 180 or "Never" or "Off"
:ptype: int, str
:return: True if successful, False if not
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' power.set_harddisk_sleep 120
salt '*' power.set_harddisk_sleep off
'''
value = _validate_sleep(minutes)
cmd = 'systemsetup -setharddisksleep {0}'.format(value)
salt.utils.mac_utils.execute_return_success(cmd)
return salt.utils.mac_utils.confirm_updated(
str(value),
get_harddisk_sleep,
) | [
"def",
"set_harddisk_sleep",
"(",
"minutes",
")",
":",
"value",
"=",
"_validate_sleep",
"(",
"minutes",
")",
"cmd",
"=",
"'systemsetup -setharddisksleep {0}'",
".",
"format",
"(",
"value",
")",
"salt",
".",
"utils",
".",
"mac_utils",
".",
"execute_return_success",... | Set the amount of idle time until the harddisk sleeps. Pass "Never" of "Off"
to never sleep.
:param minutes: Can be an integer between 1 and 180 or "Never" or "Off"
:ptype: int, str
:return: True if successful, False if not
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' power.set_harddisk_sleep 120
salt '*' power.set_harddisk_sleep off | [
"Set",
"the",
"amount",
"of",
"idle",
"time",
"until",
"the",
"harddisk",
"sleeps",
".",
"Pass",
"Never",
"of",
"Off",
"to",
"never",
"sleep",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_power.py#L238-L263 | train |
saltstack/salt | salt/modules/mac_power.py | get_wake_on_modem | def get_wake_on_modem():
'''
Displays whether 'wake on modem' is on or off if supported
:return: A string value representing the "wake on modem" settings
:rtype: str
CLI Example:
.. code-block:: bash
salt '*' power.get_wake_on_modem
'''
ret = salt.utils.mac_utils.execute_return_result(
'systemsetup -getwakeonmodem')
return salt.utils.mac_utils.validate_enabled(
salt.utils.mac_utils.parse_return(ret)) == 'on' | python | def get_wake_on_modem():
'''
Displays whether 'wake on modem' is on or off if supported
:return: A string value representing the "wake on modem" settings
:rtype: str
CLI Example:
.. code-block:: bash
salt '*' power.get_wake_on_modem
'''
ret = salt.utils.mac_utils.execute_return_result(
'systemsetup -getwakeonmodem')
return salt.utils.mac_utils.validate_enabled(
salt.utils.mac_utils.parse_return(ret)) == 'on' | [
"def",
"get_wake_on_modem",
"(",
")",
":",
"ret",
"=",
"salt",
".",
"utils",
".",
"mac_utils",
".",
"execute_return_result",
"(",
"'systemsetup -getwakeonmodem'",
")",
"return",
"salt",
".",
"utils",
".",
"mac_utils",
".",
"validate_enabled",
"(",
"salt",
".",
... | Displays whether 'wake on modem' is on or off if supported
:return: A string value representing the "wake on modem" settings
:rtype: str
CLI Example:
.. code-block:: bash
salt '*' power.get_wake_on_modem | [
"Displays",
"whether",
"wake",
"on",
"modem",
"is",
"on",
"or",
"off",
"if",
"supported"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_power.py#L266-L282 | train |
saltstack/salt | salt/modules/mac_power.py | set_wake_on_modem | def set_wake_on_modem(enabled):
'''
Set whether or not the computer will wake from sleep when modem activity is
detected.
:param bool enabled: True to enable, False to disable. "On" and "Off" are
also acceptable values. Additionally you can pass 1 and 0 to represent
True and False respectively
:return: True if successful, False if not
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' power.set_wake_on_modem True
'''
state = salt.utils.mac_utils.validate_enabled(enabled)
cmd = 'systemsetup -setwakeonmodem {0}'.format(state)
salt.utils.mac_utils.execute_return_success(cmd)
return salt.utils.mac_utils.confirm_updated(
state,
get_wake_on_modem,
) | python | def set_wake_on_modem(enabled):
'''
Set whether or not the computer will wake from sleep when modem activity is
detected.
:param bool enabled: True to enable, False to disable. "On" and "Off" are
also acceptable values. Additionally you can pass 1 and 0 to represent
True and False respectively
:return: True if successful, False if not
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' power.set_wake_on_modem True
'''
state = salt.utils.mac_utils.validate_enabled(enabled)
cmd = 'systemsetup -setwakeonmodem {0}'.format(state)
salt.utils.mac_utils.execute_return_success(cmd)
return salt.utils.mac_utils.confirm_updated(
state,
get_wake_on_modem,
) | [
"def",
"set_wake_on_modem",
"(",
"enabled",
")",
":",
"state",
"=",
"salt",
".",
"utils",
".",
"mac_utils",
".",
"validate_enabled",
"(",
"enabled",
")",
"cmd",
"=",
"'systemsetup -setwakeonmodem {0}'",
".",
"format",
"(",
"state",
")",
"salt",
".",
"utils",
... | Set whether or not the computer will wake from sleep when modem activity is
detected.
:param bool enabled: True to enable, False to disable. "On" and "Off" are
also acceptable values. Additionally you can pass 1 and 0 to represent
True and False respectively
:return: True if successful, False if not
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' power.set_wake_on_modem True | [
"Set",
"whether",
"or",
"not",
"the",
"computer",
"will",
"wake",
"from",
"sleep",
"when",
"modem",
"activity",
"is",
"detected",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_power.py#L285-L310 | train |
saltstack/salt | salt/modules/mac_power.py | get_wake_on_network | def get_wake_on_network():
'''
Displays whether 'wake on network' is on or off if supported
:return: A string value representing the "wake on network" settings
:rtype: string
CLI Example:
.. code-block:: bash
salt '*' power.get_wake_on_network
'''
ret = salt.utils.mac_utils.execute_return_result(
'systemsetup -getwakeonnetworkaccess')
return salt.utils.mac_utils.validate_enabled(
salt.utils.mac_utils.parse_return(ret)) == 'on' | python | def get_wake_on_network():
'''
Displays whether 'wake on network' is on or off if supported
:return: A string value representing the "wake on network" settings
:rtype: string
CLI Example:
.. code-block:: bash
salt '*' power.get_wake_on_network
'''
ret = salt.utils.mac_utils.execute_return_result(
'systemsetup -getwakeonnetworkaccess')
return salt.utils.mac_utils.validate_enabled(
salt.utils.mac_utils.parse_return(ret)) == 'on' | [
"def",
"get_wake_on_network",
"(",
")",
":",
"ret",
"=",
"salt",
".",
"utils",
".",
"mac_utils",
".",
"execute_return_result",
"(",
"'systemsetup -getwakeonnetworkaccess'",
")",
"return",
"salt",
".",
"utils",
".",
"mac_utils",
".",
"validate_enabled",
"(",
"salt"... | Displays whether 'wake on network' is on or off if supported
:return: A string value representing the "wake on network" settings
:rtype: string
CLI Example:
.. code-block:: bash
salt '*' power.get_wake_on_network | [
"Displays",
"whether",
"wake",
"on",
"network",
"is",
"on",
"or",
"off",
"if",
"supported"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_power.py#L313-L329 | train |
saltstack/salt | salt/modules/mac_power.py | set_wake_on_network | def set_wake_on_network(enabled):
'''
Set whether or not the computer will wake from sleep when network activity
is detected.
:param bool enabled: True to enable, False to disable. "On" and "Off" are
also acceptable values. Additionally you can pass 1 and 0 to represent
True and False respectively
:return: True if successful, False if not
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' power.set_wake_on_network True
'''
state = salt.utils.mac_utils.validate_enabled(enabled)
cmd = 'systemsetup -setwakeonnetworkaccess {0}'.format(state)
salt.utils.mac_utils.execute_return_success(cmd)
return salt.utils.mac_utils.confirm_updated(
state,
get_wake_on_network,
) | python | def set_wake_on_network(enabled):
'''
Set whether or not the computer will wake from sleep when network activity
is detected.
:param bool enabled: True to enable, False to disable. "On" and "Off" are
also acceptable values. Additionally you can pass 1 and 0 to represent
True and False respectively
:return: True if successful, False if not
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' power.set_wake_on_network True
'''
state = salt.utils.mac_utils.validate_enabled(enabled)
cmd = 'systemsetup -setwakeonnetworkaccess {0}'.format(state)
salt.utils.mac_utils.execute_return_success(cmd)
return salt.utils.mac_utils.confirm_updated(
state,
get_wake_on_network,
) | [
"def",
"set_wake_on_network",
"(",
"enabled",
")",
":",
"state",
"=",
"salt",
".",
"utils",
".",
"mac_utils",
".",
"validate_enabled",
"(",
"enabled",
")",
"cmd",
"=",
"'systemsetup -setwakeonnetworkaccess {0}'",
".",
"format",
"(",
"state",
")",
"salt",
".",
... | Set whether or not the computer will wake from sleep when network activity
is detected.
:param bool enabled: True to enable, False to disable. "On" and "Off" are
also acceptable values. Additionally you can pass 1 and 0 to represent
True and False respectively
:return: True if successful, False if not
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' power.set_wake_on_network True | [
"Set",
"whether",
"or",
"not",
"the",
"computer",
"will",
"wake",
"from",
"sleep",
"when",
"network",
"activity",
"is",
"detected",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_power.py#L332-L357 | train |
saltstack/salt | salt/modules/mac_power.py | get_restart_power_failure | def get_restart_power_failure():
'''
Displays whether 'restart on power failure' is on or off if supported
:return: A string value representing the "restart on power failure" settings
:rtype: string
CLI Example:
.. code-block:: bash
salt '*' power.get_restart_power_failure
'''
ret = salt.utils.mac_utils.execute_return_result(
'systemsetup -getrestartpowerfailure')
return salt.utils.mac_utils.validate_enabled(
salt.utils.mac_utils.parse_return(ret)) == 'on' | python | def get_restart_power_failure():
'''
Displays whether 'restart on power failure' is on or off if supported
:return: A string value representing the "restart on power failure" settings
:rtype: string
CLI Example:
.. code-block:: bash
salt '*' power.get_restart_power_failure
'''
ret = salt.utils.mac_utils.execute_return_result(
'systemsetup -getrestartpowerfailure')
return salt.utils.mac_utils.validate_enabled(
salt.utils.mac_utils.parse_return(ret)) == 'on' | [
"def",
"get_restart_power_failure",
"(",
")",
":",
"ret",
"=",
"salt",
".",
"utils",
".",
"mac_utils",
".",
"execute_return_result",
"(",
"'systemsetup -getrestartpowerfailure'",
")",
"return",
"salt",
".",
"utils",
".",
"mac_utils",
".",
"validate_enabled",
"(",
... | Displays whether 'restart on power failure' is on or off if supported
:return: A string value representing the "restart on power failure" settings
:rtype: string
CLI Example:
.. code-block:: bash
salt '*' power.get_restart_power_failure | [
"Displays",
"whether",
"restart",
"on",
"power",
"failure",
"is",
"on",
"or",
"off",
"if",
"supported"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_power.py#L360-L376 | train |
saltstack/salt | salt/modules/mac_power.py | set_restart_power_failure | def set_restart_power_failure(enabled):
'''
Set whether or not the computer will automatically restart after a power
failure.
:param bool enabled: True to enable, False to disable. "On" and "Off" are
also acceptable values. Additionally you can pass 1 and 0 to represent
True and False respectively
:return: True if successful, False if not
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' power.set_restart_power_failure True
'''
state = salt.utils.mac_utils.validate_enabled(enabled)
cmd = 'systemsetup -setrestartpowerfailure {0}'.format(state)
salt.utils.mac_utils.execute_return_success(cmd)
return salt.utils.mac_utils.confirm_updated(
state,
get_restart_power_failure,
) | python | def set_restart_power_failure(enabled):
'''
Set whether or not the computer will automatically restart after a power
failure.
:param bool enabled: True to enable, False to disable. "On" and "Off" are
also acceptable values. Additionally you can pass 1 and 0 to represent
True and False respectively
:return: True if successful, False if not
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' power.set_restart_power_failure True
'''
state = salt.utils.mac_utils.validate_enabled(enabled)
cmd = 'systemsetup -setrestartpowerfailure {0}'.format(state)
salt.utils.mac_utils.execute_return_success(cmd)
return salt.utils.mac_utils.confirm_updated(
state,
get_restart_power_failure,
) | [
"def",
"set_restart_power_failure",
"(",
"enabled",
")",
":",
"state",
"=",
"salt",
".",
"utils",
".",
"mac_utils",
".",
"validate_enabled",
"(",
"enabled",
")",
"cmd",
"=",
"'systemsetup -setrestartpowerfailure {0}'",
".",
"format",
"(",
"state",
")",
"salt",
"... | Set whether or not the computer will automatically restart after a power
failure.
:param bool enabled: True to enable, False to disable. "On" and "Off" are
also acceptable values. Additionally you can pass 1 and 0 to represent
True and False respectively
:return: True if successful, False if not
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' power.set_restart_power_failure True | [
"Set",
"whether",
"or",
"not",
"the",
"computer",
"will",
"automatically",
"restart",
"after",
"a",
"power",
"failure",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_power.py#L379-L404 | train |
saltstack/salt | salt/modules/mac_power.py | get_restart_freeze | def get_restart_freeze():
'''
Displays whether 'restart on freeze' is on or off if supported
:return: A string value representing the "restart on freeze" settings
:rtype: string
CLI Example:
.. code-block:: bash
salt '*' power.get_restart_freeze
'''
ret = salt.utils.mac_utils.execute_return_result(
'systemsetup -getrestartfreeze')
return salt.utils.mac_utils.validate_enabled(
salt.utils.mac_utils.parse_return(ret)) == 'on' | python | def get_restart_freeze():
'''
Displays whether 'restart on freeze' is on or off if supported
:return: A string value representing the "restart on freeze" settings
:rtype: string
CLI Example:
.. code-block:: bash
salt '*' power.get_restart_freeze
'''
ret = salt.utils.mac_utils.execute_return_result(
'systemsetup -getrestartfreeze')
return salt.utils.mac_utils.validate_enabled(
salt.utils.mac_utils.parse_return(ret)) == 'on' | [
"def",
"get_restart_freeze",
"(",
")",
":",
"ret",
"=",
"salt",
".",
"utils",
".",
"mac_utils",
".",
"execute_return_result",
"(",
"'systemsetup -getrestartfreeze'",
")",
"return",
"salt",
".",
"utils",
".",
"mac_utils",
".",
"validate_enabled",
"(",
"salt",
"."... | Displays whether 'restart on freeze' is on or off if supported
:return: A string value representing the "restart on freeze" settings
:rtype: string
CLI Example:
.. code-block:: bash
salt '*' power.get_restart_freeze | [
"Displays",
"whether",
"restart",
"on",
"freeze",
"is",
"on",
"or",
"off",
"if",
"supported"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_power.py#L407-L423 | train |
saltstack/salt | salt/modules/mac_power.py | set_restart_freeze | def set_restart_freeze(enabled):
'''
Specifies whether the server restarts automatically after a system freeze.
This setting doesn't seem to be editable. The command completes successfully
but the setting isn't actually updated. This is probably a macOS. The
functions remains in case they ever fix the bug.
:param bool enabled: True to enable, False to disable. "On" and "Off" are
also acceptable values. Additionally you can pass 1 and 0 to represent
True and False respectively
:return: True if successful, False if not
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' power.set_restart_freeze True
'''
state = salt.utils.mac_utils.validate_enabled(enabled)
cmd = 'systemsetup -setrestartfreeze {0}'.format(state)
salt.utils.mac_utils.execute_return_success(cmd)
return salt.utils.mac_utils.confirm_updated(
state,
get_restart_freeze,
True
) | python | def set_restart_freeze(enabled):
'''
Specifies whether the server restarts automatically after a system freeze.
This setting doesn't seem to be editable. The command completes successfully
but the setting isn't actually updated. This is probably a macOS. The
functions remains in case they ever fix the bug.
:param bool enabled: True to enable, False to disable. "On" and "Off" are
also acceptable values. Additionally you can pass 1 and 0 to represent
True and False respectively
:return: True if successful, False if not
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' power.set_restart_freeze True
'''
state = salt.utils.mac_utils.validate_enabled(enabled)
cmd = 'systemsetup -setrestartfreeze {0}'.format(state)
salt.utils.mac_utils.execute_return_success(cmd)
return salt.utils.mac_utils.confirm_updated(
state,
get_restart_freeze,
True
) | [
"def",
"set_restart_freeze",
"(",
"enabled",
")",
":",
"state",
"=",
"salt",
".",
"utils",
".",
"mac_utils",
".",
"validate_enabled",
"(",
"enabled",
")",
"cmd",
"=",
"'systemsetup -setrestartfreeze {0}'",
".",
"format",
"(",
"state",
")",
"salt",
".",
"utils"... | Specifies whether the server restarts automatically after a system freeze.
This setting doesn't seem to be editable. The command completes successfully
but the setting isn't actually updated. This is probably a macOS. The
functions remains in case they ever fix the bug.
:param bool enabled: True to enable, False to disable. "On" and "Off" are
also acceptable values. Additionally you can pass 1 and 0 to represent
True and False respectively
:return: True if successful, False if not
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' power.set_restart_freeze True | [
"Specifies",
"whether",
"the",
"server",
"restarts",
"automatically",
"after",
"a",
"system",
"freeze",
".",
"This",
"setting",
"doesn",
"t",
"seem",
"to",
"be",
"editable",
".",
"The",
"command",
"completes",
"successfully",
"but",
"the",
"setting",
"isn",
"t... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_power.py#L426-L454 | train |
saltstack/salt | salt/modules/mac_power.py | get_sleep_on_power_button | def get_sleep_on_power_button():
'''
Displays whether 'allow power button to sleep computer' is on or off if
supported
:return: A string value representing the "allow power button to sleep
computer" settings
:rtype: string
CLI Example:
.. code-block:: bash
salt '*' power.get_sleep_on_power_button
'''
ret = salt.utils.mac_utils.execute_return_result(
'systemsetup -getallowpowerbuttontosleepcomputer')
return salt.utils.mac_utils.validate_enabled(
salt.utils.mac_utils.parse_return(ret)) == 'on' | python | def get_sleep_on_power_button():
'''
Displays whether 'allow power button to sleep computer' is on or off if
supported
:return: A string value representing the "allow power button to sleep
computer" settings
:rtype: string
CLI Example:
.. code-block:: bash
salt '*' power.get_sleep_on_power_button
'''
ret = salt.utils.mac_utils.execute_return_result(
'systemsetup -getallowpowerbuttontosleepcomputer')
return salt.utils.mac_utils.validate_enabled(
salt.utils.mac_utils.parse_return(ret)) == 'on' | [
"def",
"get_sleep_on_power_button",
"(",
")",
":",
"ret",
"=",
"salt",
".",
"utils",
".",
"mac_utils",
".",
"execute_return_result",
"(",
"'systemsetup -getallowpowerbuttontosleepcomputer'",
")",
"return",
"salt",
".",
"utils",
".",
"mac_utils",
".",
"validate_enabled... | Displays whether 'allow power button to sleep computer' is on or off if
supported
:return: A string value representing the "allow power button to sleep
computer" settings
:rtype: string
CLI Example:
.. code-block:: bash
salt '*' power.get_sleep_on_power_button | [
"Displays",
"whether",
"allow",
"power",
"button",
"to",
"sleep",
"computer",
"is",
"on",
"or",
"off",
"if",
"supported"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_power.py#L457-L476 | train |
saltstack/salt | salt/modules/mac_power.py | set_sleep_on_power_button | def set_sleep_on_power_button(enabled):
'''
Set whether or not the power button can sleep the computer.
:param bool enabled: True to enable, False to disable. "On" and "Off" are
also acceptable values. Additionally you can pass 1 and 0 to represent
True and False respectively
:return: True if successful, False if not
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' power.set_sleep_on_power_button True
'''
state = salt.utils.mac_utils.validate_enabled(enabled)
cmd = 'systemsetup -setallowpowerbuttontosleepcomputer {0}'.format(state)
salt.utils.mac_utils.execute_return_success(cmd)
return salt.utils.mac_utils.confirm_updated(
state,
get_sleep_on_power_button,
) | python | def set_sleep_on_power_button(enabled):
'''
Set whether or not the power button can sleep the computer.
:param bool enabled: True to enable, False to disable. "On" and "Off" are
also acceptable values. Additionally you can pass 1 and 0 to represent
True and False respectively
:return: True if successful, False if not
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' power.set_sleep_on_power_button True
'''
state = salt.utils.mac_utils.validate_enabled(enabled)
cmd = 'systemsetup -setallowpowerbuttontosleepcomputer {0}'.format(state)
salt.utils.mac_utils.execute_return_success(cmd)
return salt.utils.mac_utils.confirm_updated(
state,
get_sleep_on_power_button,
) | [
"def",
"set_sleep_on_power_button",
"(",
"enabled",
")",
":",
"state",
"=",
"salt",
".",
"utils",
".",
"mac_utils",
".",
"validate_enabled",
"(",
"enabled",
")",
"cmd",
"=",
"'systemsetup -setallowpowerbuttontosleepcomputer {0}'",
".",
"format",
"(",
"state",
")",
... | Set whether or not the power button can sleep the computer.
:param bool enabled: True to enable, False to disable. "On" and "Off" are
also acceptable values. Additionally you can pass 1 and 0 to represent
True and False respectively
:return: True if successful, False if not
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' power.set_sleep_on_power_button True | [
"Set",
"whether",
"or",
"not",
"the",
"power",
"button",
"can",
"sleep",
"the",
"computer",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_power.py#L479-L503 | train |
saltstack/salt | salt/cloud/clouds/pyrax.py | get_conn | def get_conn(conn_type):
'''
Return a conn object for the passed VM data
'''
vm_ = get_configured_provider()
kwargs = vm_.copy() # pylint: disable=E1103
kwargs['username'] = vm_['username']
kwargs['auth_endpoint'] = vm_.get('identity_url', None)
kwargs['region'] = vm_['compute_region']
conn = getattr(suop, conn_type)
return conn(**kwargs) | python | def get_conn(conn_type):
'''
Return a conn object for the passed VM data
'''
vm_ = get_configured_provider()
kwargs = vm_.copy() # pylint: disable=E1103
kwargs['username'] = vm_['username']
kwargs['auth_endpoint'] = vm_.get('identity_url', None)
kwargs['region'] = vm_['compute_region']
conn = getattr(suop, conn_type)
return conn(**kwargs) | [
"def",
"get_conn",
"(",
"conn_type",
")",
":",
"vm_",
"=",
"get_configured_provider",
"(",
")",
"kwargs",
"=",
"vm_",
".",
"copy",
"(",
")",
"# pylint: disable=E1103",
"kwargs",
"[",
"'username'",
"]",
"=",
"vm_",
"[",
"'username'",
"]",
"kwargs",
"[",
"'a... | Return a conn object for the passed VM data | [
"Return",
"a",
"conn",
"object",
"for",
"the",
"passed",
"VM",
"data"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/pyrax.py#L63-L77 | train |
saltstack/salt | salt/modules/swarm.py | swarm_init | def swarm_init(advertise_addr=str,
listen_addr=int,
force_new_cluster=bool):
'''
Initalize Docker on Minion as a Swarm Manager
advertise_addr
The ip of the manager
listen_addr
Listen address used for inter-manager communication,
as well as determining the networking interface used
for the VXLAN Tunnel Endpoint (VTEP).
This can either be an address/port combination in
the form 192.168.1.1:4567,
or an interface followed by a port number,
like eth0:4567
force_new_cluster
Force a new cluster if True is passed
CLI Example:
.. code-block:: bash
salt '*' swarm.swarm_init advertise_addr='192.168.50.10' listen_addr='0.0.0.0' force_new_cluster=False
'''
try:
salt_return = {}
__context__['client'].swarm.init(advertise_addr,
listen_addr,
force_new_cluster)
output = 'Docker swarm has been initialized on {0} ' \
'and the worker/manager Join token is below'.format(__context__['server_name'])
salt_return.update({'Comment': output,
'Tokens': swarm_tokens()})
except TypeError:
salt_return = {}
salt_return.update({'Error': 'Please make sure you are passing advertise_addr, '
'listen_addr and force_new_cluster correctly.'})
return salt_return | python | def swarm_init(advertise_addr=str,
listen_addr=int,
force_new_cluster=bool):
'''
Initalize Docker on Minion as a Swarm Manager
advertise_addr
The ip of the manager
listen_addr
Listen address used for inter-manager communication,
as well as determining the networking interface used
for the VXLAN Tunnel Endpoint (VTEP).
This can either be an address/port combination in
the form 192.168.1.1:4567,
or an interface followed by a port number,
like eth0:4567
force_new_cluster
Force a new cluster if True is passed
CLI Example:
.. code-block:: bash
salt '*' swarm.swarm_init advertise_addr='192.168.50.10' listen_addr='0.0.0.0' force_new_cluster=False
'''
try:
salt_return = {}
__context__['client'].swarm.init(advertise_addr,
listen_addr,
force_new_cluster)
output = 'Docker swarm has been initialized on {0} ' \
'and the worker/manager Join token is below'.format(__context__['server_name'])
salt_return.update({'Comment': output,
'Tokens': swarm_tokens()})
except TypeError:
salt_return = {}
salt_return.update({'Error': 'Please make sure you are passing advertise_addr, '
'listen_addr and force_new_cluster correctly.'})
return salt_return | [
"def",
"swarm_init",
"(",
"advertise_addr",
"=",
"str",
",",
"listen_addr",
"=",
"int",
",",
"force_new_cluster",
"=",
"bool",
")",
":",
"try",
":",
"salt_return",
"=",
"{",
"}",
"__context__",
"[",
"'client'",
"]",
".",
"swarm",
".",
"init",
"(",
"adver... | Initalize Docker on Minion as a Swarm Manager
advertise_addr
The ip of the manager
listen_addr
Listen address used for inter-manager communication,
as well as determining the networking interface used
for the VXLAN Tunnel Endpoint (VTEP).
This can either be an address/port combination in
the form 192.168.1.1:4567,
or an interface followed by a port number,
like eth0:4567
force_new_cluster
Force a new cluster if True is passed
CLI Example:
.. code-block:: bash
salt '*' swarm.swarm_init advertise_addr='192.168.50.10' listen_addr='0.0.0.0' force_new_cluster=False | [
"Initalize",
"Docker",
"on",
"Minion",
"as",
"a",
"Swarm",
"Manager"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/swarm.py#L72-L112 | train |
saltstack/salt | salt/modules/swarm.py | joinswarm | def joinswarm(remote_addr=int,
listen_addr=int,
token=str):
'''
Join a Swarm Worker to the cluster
remote_addr
The manager node you want to connect to for the swarm
listen_addr
Listen address used for inter-manager communication if the node gets promoted to manager,
as well as determining the networking interface used for the VXLAN Tunnel Endpoint (VTEP)
token
Either the manager join token or the worker join token.
You can get the worker or manager token via ``salt '*' swarm.swarm_tokens``
CLI Example:
.. code-block:: bash
salt '*' swarm.joinswarm remote_addr=192.168.50.10 listen_addr='0.0.0.0' \
token='SWMTKN-1-64tux2g0701r84ofq93zppcih0pe081akq45owe9ts61f30x4t-06trjugdu7x2z47j938s54il'
'''
try:
salt_return = {}
__context__['client'].swarm.join(remote_addrs=[remote_addr],
listen_addr=listen_addr,
join_token=token)
output = __context__['server_name'] + ' has joined the Swarm'
salt_return.update({'Comment': output, 'Manager_Addr': remote_addr})
except TypeError:
salt_return = {}
salt_return.update({'Error': 'Please make sure this minion is not part of a swarm and you are '
'passing remote_addr, listen_addr and token correctly.'})
return salt_return | python | def joinswarm(remote_addr=int,
listen_addr=int,
token=str):
'''
Join a Swarm Worker to the cluster
remote_addr
The manager node you want to connect to for the swarm
listen_addr
Listen address used for inter-manager communication if the node gets promoted to manager,
as well as determining the networking interface used for the VXLAN Tunnel Endpoint (VTEP)
token
Either the manager join token or the worker join token.
You can get the worker or manager token via ``salt '*' swarm.swarm_tokens``
CLI Example:
.. code-block:: bash
salt '*' swarm.joinswarm remote_addr=192.168.50.10 listen_addr='0.0.0.0' \
token='SWMTKN-1-64tux2g0701r84ofq93zppcih0pe081akq45owe9ts61f30x4t-06trjugdu7x2z47j938s54il'
'''
try:
salt_return = {}
__context__['client'].swarm.join(remote_addrs=[remote_addr],
listen_addr=listen_addr,
join_token=token)
output = __context__['server_name'] + ' has joined the Swarm'
salt_return.update({'Comment': output, 'Manager_Addr': remote_addr})
except TypeError:
salt_return = {}
salt_return.update({'Error': 'Please make sure this minion is not part of a swarm and you are '
'passing remote_addr, listen_addr and token correctly.'})
return salt_return | [
"def",
"joinswarm",
"(",
"remote_addr",
"=",
"int",
",",
"listen_addr",
"=",
"int",
",",
"token",
"=",
"str",
")",
":",
"try",
":",
"salt_return",
"=",
"{",
"}",
"__context__",
"[",
"'client'",
"]",
".",
"swarm",
".",
"join",
"(",
"remote_addrs",
"=",
... | Join a Swarm Worker to the cluster
remote_addr
The manager node you want to connect to for the swarm
listen_addr
Listen address used for inter-manager communication if the node gets promoted to manager,
as well as determining the networking interface used for the VXLAN Tunnel Endpoint (VTEP)
token
Either the manager join token or the worker join token.
You can get the worker or manager token via ``salt '*' swarm.swarm_tokens``
CLI Example:
.. code-block:: bash
salt '*' swarm.joinswarm remote_addr=192.168.50.10 listen_addr='0.0.0.0' \
token='SWMTKN-1-64tux2g0701r84ofq93zppcih0pe081akq45owe9ts61f30x4t-06trjugdu7x2z47j938s54il' | [
"Join",
"a",
"Swarm",
"Worker",
"to",
"the",
"cluster"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/swarm.py#L115-L150 | train |
saltstack/salt | salt/modules/swarm.py | leave_swarm | def leave_swarm(force=bool):
'''
Force the minion to leave the swarm
force
Will force the minion/worker/manager to leave the swarm
CLI Example:
.. code-block:: bash
salt '*' swarm.leave_swarm force=False
'''
salt_return = {}
__context__['client'].swarm.leave(force=force)
output = __context__['server_name'] + ' has left the swarm'
salt_return.update({'Comment': output})
return salt_return | python | def leave_swarm(force=bool):
'''
Force the minion to leave the swarm
force
Will force the minion/worker/manager to leave the swarm
CLI Example:
.. code-block:: bash
salt '*' swarm.leave_swarm force=False
'''
salt_return = {}
__context__['client'].swarm.leave(force=force)
output = __context__['server_name'] + ' has left the swarm'
salt_return.update({'Comment': output})
return salt_return | [
"def",
"leave_swarm",
"(",
"force",
"=",
"bool",
")",
":",
"salt_return",
"=",
"{",
"}",
"__context__",
"[",
"'client'",
"]",
".",
"swarm",
".",
"leave",
"(",
"force",
"=",
"force",
")",
"output",
"=",
"__context__",
"[",
"'server_name'",
"]",
"+",
"' ... | Force the minion to leave the swarm
force
Will force the minion/worker/manager to leave the swarm
CLI Example:
.. code-block:: bash
salt '*' swarm.leave_swarm force=False | [
"Force",
"the",
"minion",
"to",
"leave",
"the",
"swarm"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/swarm.py#L153-L170 | train |
saltstack/salt | salt/modules/swarm.py | service_create | def service_create(image=str,
name=str,
command=str,
hostname=str,
replicas=int,
target_port=int,
published_port=int):
'''
Create Docker Swarm Service Create
image
The docker image
name
Is the service name
command
The docker command to run in the container at launch
hostname
The hostname of the containers
replicas
How many replicas you want running in the swarm
target_port
The target port on the container
published_port
port thats published on the host/os
CLI Example:
.. code-block:: bash
salt '*' swarm.service_create image=httpd name=Test_Service \
command=None hostname=salthttpd replicas=6 target_port=80 published_port=80
'''
try:
salt_return = {}
replica_mode = docker.types.ServiceMode('replicated', replicas=replicas)
ports = docker.types.EndpointSpec(ports={target_port: published_port})
__context__['client'].services.create(name=name,
image=image,
command=command,
mode=replica_mode,
endpoint_spec=ports)
echoback = __context__['server_name'] + ' has a Docker Swarm Service running named ' + name
salt_return.update({'Info': echoback,
'Minion': __context__['server_name'],
'Name': name,
'Image': image,
'Command': command,
'Hostname': hostname,
'Replicas': replicas,
'Target_Port': target_port,
'Published_Port': published_port})
except TypeError:
salt_return = {}
salt_return.update({'Error': 'Please make sure you are passing arguments correctly '
'[image, name, command, hostname, replicas, target_port and published_port]'})
return salt_return | python | def service_create(image=str,
name=str,
command=str,
hostname=str,
replicas=int,
target_port=int,
published_port=int):
'''
Create Docker Swarm Service Create
image
The docker image
name
Is the service name
command
The docker command to run in the container at launch
hostname
The hostname of the containers
replicas
How many replicas you want running in the swarm
target_port
The target port on the container
published_port
port thats published on the host/os
CLI Example:
.. code-block:: bash
salt '*' swarm.service_create image=httpd name=Test_Service \
command=None hostname=salthttpd replicas=6 target_port=80 published_port=80
'''
try:
salt_return = {}
replica_mode = docker.types.ServiceMode('replicated', replicas=replicas)
ports = docker.types.EndpointSpec(ports={target_port: published_port})
__context__['client'].services.create(name=name,
image=image,
command=command,
mode=replica_mode,
endpoint_spec=ports)
echoback = __context__['server_name'] + ' has a Docker Swarm Service running named ' + name
salt_return.update({'Info': echoback,
'Minion': __context__['server_name'],
'Name': name,
'Image': image,
'Command': command,
'Hostname': hostname,
'Replicas': replicas,
'Target_Port': target_port,
'Published_Port': published_port})
except TypeError:
salt_return = {}
salt_return.update({'Error': 'Please make sure you are passing arguments correctly '
'[image, name, command, hostname, replicas, target_port and published_port]'})
return salt_return | [
"def",
"service_create",
"(",
"image",
"=",
"str",
",",
"name",
"=",
"str",
",",
"command",
"=",
"str",
",",
"hostname",
"=",
"str",
",",
"replicas",
"=",
"int",
",",
"target_port",
"=",
"int",
",",
"published_port",
"=",
"int",
")",
":",
"try",
":",... | Create Docker Swarm Service Create
image
The docker image
name
Is the service name
command
The docker command to run in the container at launch
hostname
The hostname of the containers
replicas
How many replicas you want running in the swarm
target_port
The target port on the container
published_port
port thats published on the host/os
CLI Example:
.. code-block:: bash
salt '*' swarm.service_create image=httpd name=Test_Service \
command=None hostname=salthttpd replicas=6 target_port=80 published_port=80 | [
"Create",
"Docker",
"Swarm",
"Service",
"Create"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/swarm.py#L173-L234 | train |
saltstack/salt | salt/modules/swarm.py | swarm_service_info | def swarm_service_info(service_name=str):
'''
Swarm Service Information
service_name
The name of the service that you want information on about the service
CLI Example:
.. code-block:: bash
salt '*' swarm.swarm_service_info service_name=Test_Service
'''
try:
salt_return = {}
client = docker.APIClient(base_url='unix://var/run/docker.sock')
service = client.inspect_service(service=service_name)
getdata = salt.utils.json.dumps(service)
dump = salt.utils.json.loads(getdata)
version = dump['Version']['Index']
name = dump['Spec']['Name']
network_mode = dump['Spec']['EndpointSpec']['Mode']
ports = dump['Spec']['EndpointSpec']['Ports']
swarm_id = dump['ID']
create_date = dump['CreatedAt']
update_date = dump['UpdatedAt']
labels = dump['Spec']['Labels']
replicas = dump['Spec']['Mode']['Replicated']['Replicas']
network = dump['Endpoint']['VirtualIPs']
image = dump['Spec']['TaskTemplate']['ContainerSpec']['Image']
for items in ports:
published_port = items['PublishedPort']
target_port = items['TargetPort']
published_mode = items['PublishMode']
protocol = items['Protocol']
salt_return.update({'Service Name': name,
'Replicas': replicas,
'Service ID': swarm_id,
'Network': network,
'Network Mode': network_mode,
'Creation Date': create_date,
'Update Date': update_date,
'Published Port': published_port,
'Target Port': target_port,
'Published Mode': published_mode,
'Protocol': protocol,
'Docker Image': image,
'Minion Id': __context__['server_name'],
'Version': version})
except TypeError:
salt_return = {}
salt_return.update({'Error': 'service_name arg is missing?'})
return salt_return | python | def swarm_service_info(service_name=str):
'''
Swarm Service Information
service_name
The name of the service that you want information on about the service
CLI Example:
.. code-block:: bash
salt '*' swarm.swarm_service_info service_name=Test_Service
'''
try:
salt_return = {}
client = docker.APIClient(base_url='unix://var/run/docker.sock')
service = client.inspect_service(service=service_name)
getdata = salt.utils.json.dumps(service)
dump = salt.utils.json.loads(getdata)
version = dump['Version']['Index']
name = dump['Spec']['Name']
network_mode = dump['Spec']['EndpointSpec']['Mode']
ports = dump['Spec']['EndpointSpec']['Ports']
swarm_id = dump['ID']
create_date = dump['CreatedAt']
update_date = dump['UpdatedAt']
labels = dump['Spec']['Labels']
replicas = dump['Spec']['Mode']['Replicated']['Replicas']
network = dump['Endpoint']['VirtualIPs']
image = dump['Spec']['TaskTemplate']['ContainerSpec']['Image']
for items in ports:
published_port = items['PublishedPort']
target_port = items['TargetPort']
published_mode = items['PublishMode']
protocol = items['Protocol']
salt_return.update({'Service Name': name,
'Replicas': replicas,
'Service ID': swarm_id,
'Network': network,
'Network Mode': network_mode,
'Creation Date': create_date,
'Update Date': update_date,
'Published Port': published_port,
'Target Port': target_port,
'Published Mode': published_mode,
'Protocol': protocol,
'Docker Image': image,
'Minion Id': __context__['server_name'],
'Version': version})
except TypeError:
salt_return = {}
salt_return.update({'Error': 'service_name arg is missing?'})
return salt_return | [
"def",
"swarm_service_info",
"(",
"service_name",
"=",
"str",
")",
":",
"try",
":",
"salt_return",
"=",
"{",
"}",
"client",
"=",
"docker",
".",
"APIClient",
"(",
"base_url",
"=",
"'unix://var/run/docker.sock'",
")",
"service",
"=",
"client",
".",
"inspect_serv... | Swarm Service Information
service_name
The name of the service that you want information on about the service
CLI Example:
.. code-block:: bash
salt '*' swarm.swarm_service_info service_name=Test_Service | [
"Swarm",
"Service",
"Information"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/swarm.py#L237-L289 | train |
saltstack/salt | salt/modules/swarm.py | remove_service | def remove_service(service=str):
'''
Remove Swarm Service
service
The name of the service
CLI Example:
.. code-block:: bash
salt '*' swarm.remove_service service=Test_Service
'''
try:
salt_return = {}
client = docker.APIClient(base_url='unix://var/run/docker.sock')
service = client.remove_service(service)
salt_return.update({'Service Deleted': service,
'Minion ID': __context__['server_name']})
except TypeError:
salt_return = {}
salt_return.update({'Error': 'service arg is missing?'})
return salt_return | python | def remove_service(service=str):
'''
Remove Swarm Service
service
The name of the service
CLI Example:
.. code-block:: bash
salt '*' swarm.remove_service service=Test_Service
'''
try:
salt_return = {}
client = docker.APIClient(base_url='unix://var/run/docker.sock')
service = client.remove_service(service)
salt_return.update({'Service Deleted': service,
'Minion ID': __context__['server_name']})
except TypeError:
salt_return = {}
salt_return.update({'Error': 'service arg is missing?'})
return salt_return | [
"def",
"remove_service",
"(",
"service",
"=",
"str",
")",
":",
"try",
":",
"salt_return",
"=",
"{",
"}",
"client",
"=",
"docker",
".",
"APIClient",
"(",
"base_url",
"=",
"'unix://var/run/docker.sock'",
")",
"service",
"=",
"client",
".",
"remove_service",
"(... | Remove Swarm Service
service
The name of the service
CLI Example:
.. code-block:: bash
salt '*' swarm.remove_service service=Test_Service | [
"Remove",
"Swarm",
"Service"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/swarm.py#L292-L314 | train |
saltstack/salt | salt/modules/swarm.py | node_ls | def node_ls(server=str):
'''
Displays Information about Swarm Nodes with passing in the server
server
The minion/server name
CLI Example:
.. code-block:: bash
salt '*' swarm.node_ls server=minion1
'''
try:
salt_return = {}
client = docker.APIClient(base_url='unix://var/run/docker.sock')
service = client.nodes(filters=({'name': server}))
getdata = salt.utils.json.dumps(service)
dump = salt.utils.json.loads(getdata)
for items in dump:
docker_version = items['Description']['Engine']['EngineVersion']
platform = items['Description']['Platform']
hostnames = items['Description']['Hostname']
ids = items['ID']
role = items['Spec']['Role']
availability = items['Spec']['Availability']
status = items['Status']
version = items['Version']['Index']
salt_return.update({'Docker Version': docker_version,
'Platform': platform,
'Hostname': hostnames,
'ID': ids,
'Roles': role,
'Availability': availability,
'Status': status,
'Version': version})
except TypeError:
salt_return = {}
salt_return.update({'Error': 'The server arg is missing or you not targeting a Manager node?'})
return salt_return | python | def node_ls(server=str):
'''
Displays Information about Swarm Nodes with passing in the server
server
The minion/server name
CLI Example:
.. code-block:: bash
salt '*' swarm.node_ls server=minion1
'''
try:
salt_return = {}
client = docker.APIClient(base_url='unix://var/run/docker.sock')
service = client.nodes(filters=({'name': server}))
getdata = salt.utils.json.dumps(service)
dump = salt.utils.json.loads(getdata)
for items in dump:
docker_version = items['Description']['Engine']['EngineVersion']
platform = items['Description']['Platform']
hostnames = items['Description']['Hostname']
ids = items['ID']
role = items['Spec']['Role']
availability = items['Spec']['Availability']
status = items['Status']
version = items['Version']['Index']
salt_return.update({'Docker Version': docker_version,
'Platform': platform,
'Hostname': hostnames,
'ID': ids,
'Roles': role,
'Availability': availability,
'Status': status,
'Version': version})
except TypeError:
salt_return = {}
salt_return.update({'Error': 'The server arg is missing or you not targeting a Manager node?'})
return salt_return | [
"def",
"node_ls",
"(",
"server",
"=",
"str",
")",
":",
"try",
":",
"salt_return",
"=",
"{",
"}",
"client",
"=",
"docker",
".",
"APIClient",
"(",
"base_url",
"=",
"'unix://var/run/docker.sock'",
")",
"service",
"=",
"client",
".",
"nodes",
"(",
"filters",
... | Displays Information about Swarm Nodes with passing in the server
server
The minion/server name
CLI Example:
.. code-block:: bash
salt '*' swarm.node_ls server=minion1 | [
"Displays",
"Information",
"about",
"Swarm",
"Nodes",
"with",
"passing",
"in",
"the",
"server"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/swarm.py#L317-L356 | train |
saltstack/salt | salt/modules/swarm.py | remove_node | def remove_node(node_id=str, force=bool):
'''
Remove a node from a swarm and the target needs to be a swarm manager
node_id
The node id from the return of swarm.node_ls
force
Forcefully remove the node/minion from the service
CLI Example:
.. code-block:: bash
salt '*' swarm.remove_node node_id=z4gjbe9rwmqahc2a91snvolm5 force=false
'''
client = docker.APIClient(base_url='unix://var/run/docker.sock')
try:
if force == 'True':
service = client.remove_node(node_id, force=True)
return service
else:
service = client.remove_node(node_id, force=False)
return service
except TypeError:
salt_return = {}
salt_return.update({'Error': 'Is the node_id and/or force=True/False missing?'})
return salt_return | python | def remove_node(node_id=str, force=bool):
'''
Remove a node from a swarm and the target needs to be a swarm manager
node_id
The node id from the return of swarm.node_ls
force
Forcefully remove the node/minion from the service
CLI Example:
.. code-block:: bash
salt '*' swarm.remove_node node_id=z4gjbe9rwmqahc2a91snvolm5 force=false
'''
client = docker.APIClient(base_url='unix://var/run/docker.sock')
try:
if force == 'True':
service = client.remove_node(node_id, force=True)
return service
else:
service = client.remove_node(node_id, force=False)
return service
except TypeError:
salt_return = {}
salt_return.update({'Error': 'Is the node_id and/or force=True/False missing?'})
return salt_return | [
"def",
"remove_node",
"(",
"node_id",
"=",
"str",
",",
"force",
"=",
"bool",
")",
":",
"client",
"=",
"docker",
".",
"APIClient",
"(",
"base_url",
"=",
"'unix://var/run/docker.sock'",
")",
"try",
":",
"if",
"force",
"==",
"'True'",
":",
"service",
"=",
"... | Remove a node from a swarm and the target needs to be a swarm manager
node_id
The node id from the return of swarm.node_ls
force
Forcefully remove the node/minion from the service
CLI Example:
.. code-block:: bash
salt '*' swarm.remove_node node_id=z4gjbe9rwmqahc2a91snvolm5 force=false | [
"Remove",
"a",
"node",
"from",
"a",
"swarm",
"and",
"the",
"target",
"needs",
"to",
"be",
"a",
"swarm",
"manager"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/swarm.py#L359-L386 | train |
saltstack/salt | salt/modules/swarm.py | update_node | def update_node(availability=str,
node_name=str,
role=str,
node_id=str,
version=int):
'''
Updates docker swarm nodes/needs to target a manager node/minion
availability
Drain or Active
node_name
minion/node
role
role of manager or worker
node_id
The Id and that can be obtained via swarm.node_ls
version
Is obtained by swarm.node_ls
CLI Example:
.. code-block:: bash
salt '*' swarm.update_node availability=drain node_name=minion2 \
role=worker node_id=3k9x7t8m4pel9c0nqr3iajnzp version=19
'''
client = docker.APIClient(base_url='unix://var/run/docker.sock')
try:
salt_return = {}
node_spec = {'Availability': availability,
'Name': node_name,
'Role': role}
client.update_node(node_id=node_id,
version=version,
node_spec=node_spec)
salt_return.update({'Node Information': node_spec})
except TypeError:
salt_return = {}
salt_return.update({'Error': 'Make sure all args are passed [availability, node_name, role, node_id, version]'})
return salt_return | python | def update_node(availability=str,
node_name=str,
role=str,
node_id=str,
version=int):
'''
Updates docker swarm nodes/needs to target a manager node/minion
availability
Drain or Active
node_name
minion/node
role
role of manager or worker
node_id
The Id and that can be obtained via swarm.node_ls
version
Is obtained by swarm.node_ls
CLI Example:
.. code-block:: bash
salt '*' swarm.update_node availability=drain node_name=minion2 \
role=worker node_id=3k9x7t8m4pel9c0nqr3iajnzp version=19
'''
client = docker.APIClient(base_url='unix://var/run/docker.sock')
try:
salt_return = {}
node_spec = {'Availability': availability,
'Name': node_name,
'Role': role}
client.update_node(node_id=node_id,
version=version,
node_spec=node_spec)
salt_return.update({'Node Information': node_spec})
except TypeError:
salt_return = {}
salt_return.update({'Error': 'Make sure all args are passed [availability, node_name, role, node_id, version]'})
return salt_return | [
"def",
"update_node",
"(",
"availability",
"=",
"str",
",",
"node_name",
"=",
"str",
",",
"role",
"=",
"str",
",",
"node_id",
"=",
"str",
",",
"version",
"=",
"int",
")",
":",
"client",
"=",
"docker",
".",
"APIClient",
"(",
"base_url",
"=",
"'unix://va... | Updates docker swarm nodes/needs to target a manager node/minion
availability
Drain or Active
node_name
minion/node
role
role of manager or worker
node_id
The Id and that can be obtained via swarm.node_ls
version
Is obtained by swarm.node_ls
CLI Example:
.. code-block:: bash
salt '*' swarm.update_node availability=drain node_name=minion2 \
role=worker node_id=3k9x7t8m4pel9c0nqr3iajnzp version=19 | [
"Updates",
"docker",
"swarm",
"nodes",
"/",
"needs",
"to",
"target",
"a",
"manager",
"node",
"/",
"minion"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/swarm.py#L389-L432 | train |
saltstack/salt | salt/states/boto_iam_role.py | present | def present(
name,
policy_document=None,
policy_document_from_pillars=None,
path=None,
policies=None,
policies_from_pillars=None,
managed_policies=None,
create_instance_profile=True,
region=None,
key=None,
keyid=None,
profile=None,
delete_policies=True):
'''
Ensure the IAM role exists.
name
Name of the IAM role.
policy_document
The policy that grants an entity permission to assume the role.
(See https://boto.readthedocs.io/en/latest/ref/iam.html#boto.iam.connection.IAMConnection.create_role)
policy_document_from_pillars
A pillar key that contains a role policy document. The statements
defined here will be appended with the policy document statements
defined in the policy_document argument.
.. versionadded:: 2017.7.0
path
The path to the role/instance profile.
(See https://boto.readthedocs.io/en/latest/ref/iam.html#boto.iam.connection.IAMConnection.create_role)
policies
A dict of IAM role policies.
policies_from_pillars
A list of pillars that contain role policy dicts. Policies in the
pillars will be merged in the order defined in the list and key
conflicts will be handled by later defined keys overriding earlier
defined keys. The policies defined here will be merged with the
policies defined in the policies argument. If keys conflict, the keys
in the policies argument will override the keys defined in
policies_from_pillars.
managed_policies
A list of (AWS or Customer) managed policies to be attached to the role.
create_instance_profile
A boolean of whether or not to create an instance profile and associate
it with this role.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
delete_policies
Deletes existing policies that are not in the given list of policies. Default
value is ``True``. If ``False`` is specified, existing policies will not be deleted
allowing manual modifications on the IAM role to be persistent.
.. versionadded:: 2015.8.0
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
# Build up _policy_document
_policy_document = {}
if policy_document_from_pillars:
from_pillars = __salt__['pillar.get'](policy_document_from_pillars)
if from_pillars:
_policy_document['Version'] = from_pillars['Version']
_policy_document.setdefault('Statement', [])
_policy_document['Statement'].extend(from_pillars['Statement'])
if policy_document:
_policy_document['Version'] = policy_document['Version']
_policy_document.setdefault('Statement', [])
_policy_document['Statement'].extend(policy_document['Statement'])
_ret = _role_present(name, _policy_document, path, region, key, keyid,
profile)
# Build up _policies
if not policies:
policies = {}
if not policies_from_pillars:
policies_from_pillars = []
if not managed_policies:
managed_policies = []
_policies = {}
for policy in policies_from_pillars:
_policy = __salt__['pillar.get'](policy)
_policies.update(_policy)
_policies.update(policies)
ret['changes'] = _ret['changes']
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
if ret['result'] is False:
return ret
if create_instance_profile:
_ret = _instance_profile_present(name, region, key, keyid, profile)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
if ret['result'] is False:
return ret
_ret = _instance_profile_associated(name, region, key, keyid, profile)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
if ret['result'] is False:
return ret
_ret = _policies_present(name, _policies, region, key, keyid, profile,
delete_policies)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
_ret = _policies_attached(name, managed_policies, region, key, keyid, profile)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
return ret | python | def present(
name,
policy_document=None,
policy_document_from_pillars=None,
path=None,
policies=None,
policies_from_pillars=None,
managed_policies=None,
create_instance_profile=True,
region=None,
key=None,
keyid=None,
profile=None,
delete_policies=True):
'''
Ensure the IAM role exists.
name
Name of the IAM role.
policy_document
The policy that grants an entity permission to assume the role.
(See https://boto.readthedocs.io/en/latest/ref/iam.html#boto.iam.connection.IAMConnection.create_role)
policy_document_from_pillars
A pillar key that contains a role policy document. The statements
defined here will be appended with the policy document statements
defined in the policy_document argument.
.. versionadded:: 2017.7.0
path
The path to the role/instance profile.
(See https://boto.readthedocs.io/en/latest/ref/iam.html#boto.iam.connection.IAMConnection.create_role)
policies
A dict of IAM role policies.
policies_from_pillars
A list of pillars that contain role policy dicts. Policies in the
pillars will be merged in the order defined in the list and key
conflicts will be handled by later defined keys overriding earlier
defined keys. The policies defined here will be merged with the
policies defined in the policies argument. If keys conflict, the keys
in the policies argument will override the keys defined in
policies_from_pillars.
managed_policies
A list of (AWS or Customer) managed policies to be attached to the role.
create_instance_profile
A boolean of whether or not to create an instance profile and associate
it with this role.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
delete_policies
Deletes existing policies that are not in the given list of policies. Default
value is ``True``. If ``False`` is specified, existing policies will not be deleted
allowing manual modifications on the IAM role to be persistent.
.. versionadded:: 2015.8.0
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
# Build up _policy_document
_policy_document = {}
if policy_document_from_pillars:
from_pillars = __salt__['pillar.get'](policy_document_from_pillars)
if from_pillars:
_policy_document['Version'] = from_pillars['Version']
_policy_document.setdefault('Statement', [])
_policy_document['Statement'].extend(from_pillars['Statement'])
if policy_document:
_policy_document['Version'] = policy_document['Version']
_policy_document.setdefault('Statement', [])
_policy_document['Statement'].extend(policy_document['Statement'])
_ret = _role_present(name, _policy_document, path, region, key, keyid,
profile)
# Build up _policies
if not policies:
policies = {}
if not policies_from_pillars:
policies_from_pillars = []
if not managed_policies:
managed_policies = []
_policies = {}
for policy in policies_from_pillars:
_policy = __salt__['pillar.get'](policy)
_policies.update(_policy)
_policies.update(policies)
ret['changes'] = _ret['changes']
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
if ret['result'] is False:
return ret
if create_instance_profile:
_ret = _instance_profile_present(name, region, key, keyid, profile)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
if ret['result'] is False:
return ret
_ret = _instance_profile_associated(name, region, key, keyid, profile)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
if ret['result'] is False:
return ret
_ret = _policies_present(name, _policies, region, key, keyid, profile,
delete_policies)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
_ret = _policies_attached(name, managed_policies, region, key, keyid, profile)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
return ret | [
"def",
"present",
"(",
"name",
",",
"policy_document",
"=",
"None",
",",
"policy_document_from_pillars",
"=",
"None",
",",
"path",
"=",
"None",
",",
"policies",
"=",
"None",
",",
"policies_from_pillars",
"=",
"None",
",",
"managed_policies",
"=",
"None",
",",
... | Ensure the IAM role exists.
name
Name of the IAM role.
policy_document
The policy that grants an entity permission to assume the role.
(See https://boto.readthedocs.io/en/latest/ref/iam.html#boto.iam.connection.IAMConnection.create_role)
policy_document_from_pillars
A pillar key that contains a role policy document. The statements
defined here will be appended with the policy document statements
defined in the policy_document argument.
.. versionadded:: 2017.7.0
path
The path to the role/instance profile.
(See https://boto.readthedocs.io/en/latest/ref/iam.html#boto.iam.connection.IAMConnection.create_role)
policies
A dict of IAM role policies.
policies_from_pillars
A list of pillars that contain role policy dicts. Policies in the
pillars will be merged in the order defined in the list and key
conflicts will be handled by later defined keys overriding earlier
defined keys. The policies defined here will be merged with the
policies defined in the policies argument. If keys conflict, the keys
in the policies argument will override the keys defined in
policies_from_pillars.
managed_policies
A list of (AWS or Customer) managed policies to be attached to the role.
create_instance_profile
A boolean of whether or not to create an instance profile and associate
it with this role.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
delete_policies
Deletes existing policies that are not in the given list of policies. Default
value is ``True``. If ``False`` is specified, existing policies will not be deleted
allowing manual modifications on the IAM role to be persistent.
.. versionadded:: 2015.8.0 | [
"Ensure",
"the",
"IAM",
"role",
"exists",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_iam_role.py#L106-L240 | train |
saltstack/salt | salt/states/boto_iam_role.py | _sort_policy | def _sort_policy(doc):
'''
List-type sub-items in policies don't happen to be order-sensitive, but
compare operations will render them unequal, leading to non-idempotent
state runs. We'll sort any list-type subitems before comparison to reduce
the likelihood of false negatives.
'''
if isinstance(doc, list):
return sorted([_sort_policy(i) for i in doc])
elif isinstance(doc, (dict, OrderedDict)):
return dict([(k, _sort_policy(v)) for k, v in six.iteritems(doc)])
return doc | python | def _sort_policy(doc):
'''
List-type sub-items in policies don't happen to be order-sensitive, but
compare operations will render them unequal, leading to non-idempotent
state runs. We'll sort any list-type subitems before comparison to reduce
the likelihood of false negatives.
'''
if isinstance(doc, list):
return sorted([_sort_policy(i) for i in doc])
elif isinstance(doc, (dict, OrderedDict)):
return dict([(k, _sort_policy(v)) for k, v in six.iteritems(doc)])
return doc | [
"def",
"_sort_policy",
"(",
"doc",
")",
":",
"if",
"isinstance",
"(",
"doc",
",",
"list",
")",
":",
"return",
"sorted",
"(",
"[",
"_sort_policy",
"(",
"i",
")",
"for",
"i",
"in",
"doc",
"]",
")",
"elif",
"isinstance",
"(",
"doc",
",",
"(",
"dict",
... | List-type sub-items in policies don't happen to be order-sensitive, but
compare operations will render them unequal, leading to non-idempotent
state runs. We'll sort any list-type subitems before comparison to reduce
the likelihood of false negatives. | [
"List",
"-",
"type",
"sub",
"-",
"items",
"in",
"policies",
"don",
"t",
"happen",
"to",
"be",
"order",
"-",
"sensitive",
"but",
"compare",
"operations",
"will",
"render",
"them",
"unequal",
"leading",
"to",
"non",
"-",
"idempotent",
"state",
"runs",
".",
... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_iam_role.py#L355-L366 | train |
saltstack/salt | salt/states/boto_iam_role.py | absent | def absent(
name,
region=None,
key=None,
keyid=None,
profile=None):
'''
Ensure the IAM role is deleted.
name
Name of the IAM role.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
_ret = _policies_absent(name, region, key, keyid, profile)
ret['changes'] = _ret['changes']
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
if ret['result'] is False:
return ret
_ret = _policies_detached(name, region, key, keyid, profile)
ret['changes'] = _ret['changes']
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
if ret['result'] is False:
return ret
_ret = _instance_profile_disassociated(name, region, key, keyid, profile)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
if ret['result'] is False:
return ret
_ret = _instance_profile_absent(name, region, key, keyid, profile)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
if ret['result'] is False:
return ret
_ret = _role_absent(name, region, key, keyid, profile)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
return ret | python | def absent(
name,
region=None,
key=None,
keyid=None,
profile=None):
'''
Ensure the IAM role is deleted.
name
Name of the IAM role.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
_ret = _policies_absent(name, region, key, keyid, profile)
ret['changes'] = _ret['changes']
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
if ret['result'] is False:
return ret
_ret = _policies_detached(name, region, key, keyid, profile)
ret['changes'] = _ret['changes']
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
if ret['result'] is False:
return ret
_ret = _instance_profile_disassociated(name, region, key, keyid, profile)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
if ret['result'] is False:
return ret
_ret = _instance_profile_absent(name, region, key, keyid, profile)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
if ret['result'] is False:
return ret
_ret = _role_absent(name, region, key, keyid, profile)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
return ret | [
"def",
"absent",
"(",
"name",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",
"''"... | Ensure the IAM role is deleted.
name
Name of the IAM role.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid. | [
"Ensure",
"the",
"IAM",
"role",
"is",
"deleted",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_iam_role.py#L511-L570 | train |
saltstack/salt | salt/beacons/diskusage.py | beacon | def beacon(config):
r'''
Monitor the disk usage of the minion
Specify thresholds for each disk and only emit a beacon if any of them are
exceeded.
.. code-block:: yaml
beacons:
diskusage:
- /: 63%
- /mnt/nfs: 50%
Windows drives must be quoted to avoid yaml syntax errors
.. code-block:: yaml
beacons:
diskusage:
- interval: 120
- 'c:\\': 90%
- 'd:\\': 50%
Regular expressions can be used as mount points.
.. code-block:: yaml
beacons:
diskusage:
- '^\/(?!home).*$': 90%
- '^[a-zA-Z]:\\$': 50%
The first one will match all mounted disks beginning with "/", except /home
The second one will match disks from A:\ to Z:\ on a Windows system
Note that if a regular expression are evaluated after static mount points,
which means that if a regular expression matches another defined mount point,
it will override the previously defined threshold.
'''
parts = psutil.disk_partitions(all=True)
ret = []
for mounts in config:
mount = next(iter(mounts))
# Because we're using regular expressions
# if our mount doesn't end with a $, insert one.
mount_re = mount
if not mount.endswith('$'):
mount_re = '{0}$'.format(mount)
if salt.utils.platform.is_windows():
# mount_re comes in formatted with a $ at the end
# can be `C:\\$` or `C:\\\\$`
# re string must be like `C:\\\\` regardless of \\ or \\\\
# also, psutil returns uppercase
mount_re = re.sub(r':\\\$', r':\\\\', mount_re)
mount_re = re.sub(r':\\\\\$', r':\\\\', mount_re)
mount_re = mount_re.upper()
for part in parts:
if re.match(mount_re, part.mountpoint):
_mount = part.mountpoint
try:
_current_usage = psutil.disk_usage(_mount)
except OSError:
log.warning('%s is not a valid mount point.', _mount)
continue
current_usage = _current_usage.percent
monitor_usage = mounts[mount]
if '%' in monitor_usage:
monitor_usage = re.sub('%', '', monitor_usage)
monitor_usage = float(monitor_usage)
if current_usage >= monitor_usage:
ret.append({'diskusage': current_usage, 'mount': _mount})
return ret | python | def beacon(config):
r'''
Monitor the disk usage of the minion
Specify thresholds for each disk and only emit a beacon if any of them are
exceeded.
.. code-block:: yaml
beacons:
diskusage:
- /: 63%
- /mnt/nfs: 50%
Windows drives must be quoted to avoid yaml syntax errors
.. code-block:: yaml
beacons:
diskusage:
- interval: 120
- 'c:\\': 90%
- 'd:\\': 50%
Regular expressions can be used as mount points.
.. code-block:: yaml
beacons:
diskusage:
- '^\/(?!home).*$': 90%
- '^[a-zA-Z]:\\$': 50%
The first one will match all mounted disks beginning with "/", except /home
The second one will match disks from A:\ to Z:\ on a Windows system
Note that if a regular expression are evaluated after static mount points,
which means that if a regular expression matches another defined mount point,
it will override the previously defined threshold.
'''
parts = psutil.disk_partitions(all=True)
ret = []
for mounts in config:
mount = next(iter(mounts))
# Because we're using regular expressions
# if our mount doesn't end with a $, insert one.
mount_re = mount
if not mount.endswith('$'):
mount_re = '{0}$'.format(mount)
if salt.utils.platform.is_windows():
# mount_re comes in formatted with a $ at the end
# can be `C:\\$` or `C:\\\\$`
# re string must be like `C:\\\\` regardless of \\ or \\\\
# also, psutil returns uppercase
mount_re = re.sub(r':\\\$', r':\\\\', mount_re)
mount_re = re.sub(r':\\\\\$', r':\\\\', mount_re)
mount_re = mount_re.upper()
for part in parts:
if re.match(mount_re, part.mountpoint):
_mount = part.mountpoint
try:
_current_usage = psutil.disk_usage(_mount)
except OSError:
log.warning('%s is not a valid mount point.', _mount)
continue
current_usage = _current_usage.percent
monitor_usage = mounts[mount]
if '%' in monitor_usage:
monitor_usage = re.sub('%', '', monitor_usage)
monitor_usage = float(monitor_usage)
if current_usage >= monitor_usage:
ret.append({'diskusage': current_usage, 'mount': _mount})
return ret | [
"def",
"beacon",
"(",
"config",
")",
":",
"parts",
"=",
"psutil",
".",
"disk_partitions",
"(",
"all",
"=",
"True",
")",
"ret",
"=",
"[",
"]",
"for",
"mounts",
"in",
"config",
":",
"mount",
"=",
"next",
"(",
"iter",
"(",
"mounts",
")",
")",
"# Becau... | r'''
Monitor the disk usage of the minion
Specify thresholds for each disk and only emit a beacon if any of them are
exceeded.
.. code-block:: yaml
beacons:
diskusage:
- /: 63%
- /mnt/nfs: 50%
Windows drives must be quoted to avoid yaml syntax errors
.. code-block:: yaml
beacons:
diskusage:
- interval: 120
- 'c:\\': 90%
- 'd:\\': 50%
Regular expressions can be used as mount points.
.. code-block:: yaml
beacons:
diskusage:
- '^\/(?!home).*$': 90%
- '^[a-zA-Z]:\\$': 50%
The first one will match all mounted disks beginning with "/", except /home
The second one will match disks from A:\ to Z:\ on a Windows system
Note that if a regular expression are evaluated after static mount points,
which means that if a regular expression matches another defined mount point,
it will override the previously defined threshold. | [
"r",
"Monitor",
"the",
"disk",
"usage",
"of",
"the",
"minion"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/beacons/diskusage.py#L47-L125 | train |
saltstack/salt | salt/tops/saltclass.py | top | def top(**kwargs):
'''
Compile tops
'''
# Node definitions path will be retrieved from args (or set to default),
# then added to 'salt_data' dict that is passed to the 'get_pillars'
# function. The dictionary contains:
# - __opts__
# - __salt__
# - __grains__
# - __pillar__
# - minion_id
# - path
#
# If successful, the function will return a pillar dict for minion_id.
# If path has not been set, make a default
_opts = __opts__['master_tops']['saltclass']
if 'path' not in _opts:
path = '/srv/saltclass'
log.warning('path variable unset, using default: %s', path)
else:
path = _opts['path']
# Create a dict that will contain our salt objects
# to send to get_tops function
if 'id' not in kwargs['opts']:
log.warning('Minion id not found - Returning empty dict')
return {}
else:
minion_id = kwargs['opts']['id']
salt_data = {
'__opts__': kwargs['opts'],
'__salt__': {},
'__grains__': kwargs['grains'],
'__pillar__': {},
'minion_id': minion_id,
'path': path
}
return sc.get_tops(minion_id, salt_data) | python | def top(**kwargs):
'''
Compile tops
'''
# Node definitions path will be retrieved from args (or set to default),
# then added to 'salt_data' dict that is passed to the 'get_pillars'
# function. The dictionary contains:
# - __opts__
# - __salt__
# - __grains__
# - __pillar__
# - minion_id
# - path
#
# If successful, the function will return a pillar dict for minion_id.
# If path has not been set, make a default
_opts = __opts__['master_tops']['saltclass']
if 'path' not in _opts:
path = '/srv/saltclass'
log.warning('path variable unset, using default: %s', path)
else:
path = _opts['path']
# Create a dict that will contain our salt objects
# to send to get_tops function
if 'id' not in kwargs['opts']:
log.warning('Minion id not found - Returning empty dict')
return {}
else:
minion_id = kwargs['opts']['id']
salt_data = {
'__opts__': kwargs['opts'],
'__salt__': {},
'__grains__': kwargs['grains'],
'__pillar__': {},
'minion_id': minion_id,
'path': path
}
return sc.get_tops(minion_id, salt_data) | [
"def",
"top",
"(",
"*",
"*",
"kwargs",
")",
":",
"# Node definitions path will be retrieved from args (or set to default),",
"# then added to 'salt_data' dict that is passed to the 'get_pillars'",
"# function. The dictionary contains:",
"# - __opts__",
"# - __salt__",
"# - __gr... | Compile tops | [
"Compile",
"tops"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/tops/saltclass.py#L229-L270 | train |
saltstack/salt | salt/proxy/cisconso.py | ping | def ping():
'''
Check to see if the host is responding. Returns False if the host didn't
respond, True otherwise.
CLI Example:
.. code-block:: bash
salt cisco-nso test.ping
'''
try:
client = _get_client()
client.info()
except SaltSystemExit as err:
log.warning(err)
return False
return True | python | def ping():
'''
Check to see if the host is responding. Returns False if the host didn't
respond, True otherwise.
CLI Example:
.. code-block:: bash
salt cisco-nso test.ping
'''
try:
client = _get_client()
client.info()
except SaltSystemExit as err:
log.warning(err)
return False
return True | [
"def",
"ping",
"(",
")",
":",
"try",
":",
"client",
"=",
"_get_client",
"(",
")",
"client",
".",
"info",
"(",
")",
"except",
"SaltSystemExit",
"as",
"err",
":",
"log",
".",
"warning",
"(",
"err",
")",
"return",
"False",
"return",
"True"
] | Check to see if the host is responding. Returns False if the host didn't
respond, True otherwise.
CLI Example:
.. code-block:: bash
salt cisco-nso test.ping | [
"Check",
"to",
"see",
"if",
"the",
"host",
"is",
"responding",
".",
"Returns",
"False",
"if",
"the",
"host",
"didn",
"t",
"respond",
"True",
"otherwise",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/cisconso.py#L235-L253 | train |
saltstack/salt | salt/proxy/cisconso.py | set_data_value | def set_data_value(datastore, path, data):
'''
Get a data entry in a datastore
:param datastore: The datastore, e.g. running, operational.
One of the NETCONF store IETF types
:type datastore: :class:`DatastoreType` (``str`` enum).
:param path: The device path to set the value at,
a list of element names in order, comma separated
:type path: ``list`` of ``str`` OR ``tuple``
:param data: The new value at the given path
:type data: ``dict``
:rtype: ``bool``
:return: ``True`` if successful, otherwise error.
'''
client = _get_client()
return client.set_data_value(datastore, path, data) | python | def set_data_value(datastore, path, data):
'''
Get a data entry in a datastore
:param datastore: The datastore, e.g. running, operational.
One of the NETCONF store IETF types
:type datastore: :class:`DatastoreType` (``str`` enum).
:param path: The device path to set the value at,
a list of element names in order, comma separated
:type path: ``list`` of ``str`` OR ``tuple``
:param data: The new value at the given path
:type data: ``dict``
:rtype: ``bool``
:return: ``True`` if successful, otherwise error.
'''
client = _get_client()
return client.set_data_value(datastore, path, data) | [
"def",
"set_data_value",
"(",
"datastore",
",",
"path",
",",
"data",
")",
":",
"client",
"=",
"_get_client",
"(",
")",
"return",
"client",
".",
"set_data_value",
"(",
"datastore",
",",
"path",
",",
"data",
")"
] | Get a data entry in a datastore
:param datastore: The datastore, e.g. running, operational.
One of the NETCONF store IETF types
:type datastore: :class:`DatastoreType` (``str`` enum).
:param path: The device path to set the value at,
a list of element names in order, comma separated
:type path: ``list`` of ``str`` OR ``tuple``
:param data: The new value at the given path
:type data: ``dict``
:rtype: ``bool``
:return: ``True`` if successful, otherwise error. | [
"Get",
"a",
"data",
"entry",
"in",
"a",
"datastore"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/cisconso.py#L287-L306 | train |
saltstack/salt | salt/proxy/cisconso.py | _grains | def _grains():
'''
Helper function to the grains from the proxied devices.
'''
client = _get_client()
# This is a collection of the configuration of all running devices under NSO
ret = client.get_datastore(DatastoreType.RUNNING)
GRAINS_CACHE.update(ret)
return GRAINS_CACHE | python | def _grains():
'''
Helper function to the grains from the proxied devices.
'''
client = _get_client()
# This is a collection of the configuration of all running devices under NSO
ret = client.get_datastore(DatastoreType.RUNNING)
GRAINS_CACHE.update(ret)
return GRAINS_CACHE | [
"def",
"_grains",
"(",
")",
":",
"client",
"=",
"_get_client",
"(",
")",
"# This is a collection of the configuration of all running devices under NSO",
"ret",
"=",
"client",
".",
"get_datastore",
"(",
"DatastoreType",
".",
"RUNNING",
")",
"GRAINS_CACHE",
".",
"update",... | Helper function to the grains from the proxied devices. | [
"Helper",
"function",
"to",
"the",
"grains",
"from",
"the",
"proxied",
"devices",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/cisconso.py#L343-L351 | train |
saltstack/salt | salt/modules/mac_softwareupdate.py | _get_available | def _get_available(recommended=False, restart=False):
'''
Utility function to get all available update packages.
Sample return date:
{ 'updatename': '1.2.3-45', ... }
'''
cmd = ['softwareupdate', '--list']
out = salt.utils.mac_utils.execute_return_result(cmd)
# rexp parses lines that look like the following:
# * Safari6.1.2MountainLion-6.1.2
# Safari (6.1.2), 51679K [recommended]
# - iCal-1.0.2
# iCal, 1.0.2, 6520K
rexp = re.compile('(?m)^ [*|-] '
r'([^ ].*)[\r\n].*\(([^\)]+)')
if salt.utils.data.is_true(recommended):
# rexp parses lines that look like the following:
# * Safari6.1.2MountainLion-6.1.2
# Safari (6.1.2), 51679K [recommended]
rexp = re.compile('(?m)^ [*] '
r'([^ ].*)[\r\n].*\(([^\)]+)')
keys = ['name', 'version']
_get = lambda l, k: l[keys.index(k)]
updates = rexp.findall(out)
ret = {}
for line in updates:
name = _get(line, 'name')
version_num = _get(line, 'version')
ret[name] = version_num
if not salt.utils.data.is_true(restart):
return ret
# rexp parses lines that look like the following:
# * Safari6.1.2MountainLion-6.1.2
# Safari (6.1.2), 51679K [recommended] [restart]
rexp1 = re.compile('(?m)^ [*|-] '
r'([^ ].*)[\r\n].*restart*')
restart_updates = rexp1.findall(out)
ret_restart = {}
for update in ret:
if update in restart_updates:
ret_restart[update] = ret[update]
return ret_restart | python | def _get_available(recommended=False, restart=False):
'''
Utility function to get all available update packages.
Sample return date:
{ 'updatename': '1.2.3-45', ... }
'''
cmd = ['softwareupdate', '--list']
out = salt.utils.mac_utils.execute_return_result(cmd)
# rexp parses lines that look like the following:
# * Safari6.1.2MountainLion-6.1.2
# Safari (6.1.2), 51679K [recommended]
# - iCal-1.0.2
# iCal, 1.0.2, 6520K
rexp = re.compile('(?m)^ [*|-] '
r'([^ ].*)[\r\n].*\(([^\)]+)')
if salt.utils.data.is_true(recommended):
# rexp parses lines that look like the following:
# * Safari6.1.2MountainLion-6.1.2
# Safari (6.1.2), 51679K [recommended]
rexp = re.compile('(?m)^ [*] '
r'([^ ].*)[\r\n].*\(([^\)]+)')
keys = ['name', 'version']
_get = lambda l, k: l[keys.index(k)]
updates = rexp.findall(out)
ret = {}
for line in updates:
name = _get(line, 'name')
version_num = _get(line, 'version')
ret[name] = version_num
if not salt.utils.data.is_true(restart):
return ret
# rexp parses lines that look like the following:
# * Safari6.1.2MountainLion-6.1.2
# Safari (6.1.2), 51679K [recommended] [restart]
rexp1 = re.compile('(?m)^ [*|-] '
r'([^ ].*)[\r\n].*restart*')
restart_updates = rexp1.findall(out)
ret_restart = {}
for update in ret:
if update in restart_updates:
ret_restart[update] = ret[update]
return ret_restart | [
"def",
"_get_available",
"(",
"recommended",
"=",
"False",
",",
"restart",
"=",
"False",
")",
":",
"cmd",
"=",
"[",
"'softwareupdate'",
",",
"'--list'",
"]",
"out",
"=",
"salt",
".",
"utils",
".",
"mac_utils",
".",
"execute_return_result",
"(",
"cmd",
")",... | Utility function to get all available update packages.
Sample return date:
{ 'updatename': '1.2.3-45', ... } | [
"Utility",
"function",
"to",
"get",
"all",
"available",
"update",
"packages",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_softwareupdate.py#L34-L85 | train |
saltstack/salt | salt/modules/mac_softwareupdate.py | ignore | def ignore(name):
'''
Ignore a specific program update. When an update is ignored the '-' and
version number at the end will be omitted, so "SecUpd2014-001-1.0" becomes
"SecUpd2014-001". It will be removed automatically if present. An update
is successfully ignored when it no longer shows up after list_updates.
:param name: The name of the update to add to the ignore list.
:ptype: str
:return: True if successful, False if not
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' softwareupdate.ignore <update-name>
'''
# remove everything after and including the '-' in the updates name.
to_ignore = name.rsplit('-', 1)[0]
cmd = ['softwareupdate', '--ignore', to_ignore]
salt.utils.mac_utils.execute_return_success(cmd)
return to_ignore in list_ignored() | python | def ignore(name):
'''
Ignore a specific program update. When an update is ignored the '-' and
version number at the end will be omitted, so "SecUpd2014-001-1.0" becomes
"SecUpd2014-001". It will be removed automatically if present. An update
is successfully ignored when it no longer shows up after list_updates.
:param name: The name of the update to add to the ignore list.
:ptype: str
:return: True if successful, False if not
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' softwareupdate.ignore <update-name>
'''
# remove everything after and including the '-' in the updates name.
to_ignore = name.rsplit('-', 1)[0]
cmd = ['softwareupdate', '--ignore', to_ignore]
salt.utils.mac_utils.execute_return_success(cmd)
return to_ignore in list_ignored() | [
"def",
"ignore",
"(",
"name",
")",
":",
"# remove everything after and including the '-' in the updates name.",
"to_ignore",
"=",
"name",
".",
"rsplit",
"(",
"'-'",
",",
"1",
")",
"[",
"0",
"]",
"cmd",
"=",
"[",
"'softwareupdate'",
",",
"'--ignore'",
",",
"to_ig... | Ignore a specific program update. When an update is ignored the '-' and
version number at the end will be omitted, so "SecUpd2014-001-1.0" becomes
"SecUpd2014-001". It will be removed automatically if present. An update
is successfully ignored when it no longer shows up after list_updates.
:param name: The name of the update to add to the ignore list.
:ptype: str
:return: True if successful, False if not
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' softwareupdate.ignore <update-name> | [
"Ignore",
"a",
"specific",
"program",
"update",
".",
"When",
"an",
"update",
"is",
"ignored",
"the",
"-",
"and",
"version",
"number",
"at",
"the",
"end",
"will",
"be",
"omitted",
"so",
"SecUpd2014",
"-",
"001",
"-",
"1",
".",
"0",
"becomes",
"SecUpd2014"... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_softwareupdate.py#L108-L133 | train |
saltstack/salt | salt/modules/mac_softwareupdate.py | list_ignored | def list_ignored():
'''
List all updates that have been ignored. Ignored updates are shown
without the '-' and version number at the end, this is how the
softwareupdate command works.
:return: The list of ignored updates
:rtype: list
CLI Example:
.. code-block:: bash
salt '*' softwareupdate.list_ignored
'''
cmd = ['softwareupdate', '--list', '--ignore']
out = salt.utils.mac_utils.execute_return_result(cmd)
# rep parses lines that look like the following:
# "Safari6.1.2MountainLion-6.1.2",
# or:
# Safari6.1.2MountainLion-6.1.2
rexp = re.compile('(?m)^ ["]?'
r'([^,|\s].*[^"|\n|,])[,|"]?')
return rexp.findall(out) | python | def list_ignored():
'''
List all updates that have been ignored. Ignored updates are shown
without the '-' and version number at the end, this is how the
softwareupdate command works.
:return: The list of ignored updates
:rtype: list
CLI Example:
.. code-block:: bash
salt '*' softwareupdate.list_ignored
'''
cmd = ['softwareupdate', '--list', '--ignore']
out = salt.utils.mac_utils.execute_return_result(cmd)
# rep parses lines that look like the following:
# "Safari6.1.2MountainLion-6.1.2",
# or:
# Safari6.1.2MountainLion-6.1.2
rexp = re.compile('(?m)^ ["]?'
r'([^,|\s].*[^"|\n|,])[,|"]?')
return rexp.findall(out) | [
"def",
"list_ignored",
"(",
")",
":",
"cmd",
"=",
"[",
"'softwareupdate'",
",",
"'--list'",
",",
"'--ignore'",
"]",
"out",
"=",
"salt",
".",
"utils",
".",
"mac_utils",
".",
"execute_return_result",
"(",
"cmd",
")",
"# rep parses lines that look like the following:... | List all updates that have been ignored. Ignored updates are shown
without the '-' and version number at the end, this is how the
softwareupdate command works.
:return: The list of ignored updates
:rtype: list
CLI Example:
.. code-block:: bash
salt '*' softwareupdate.list_ignored | [
"List",
"all",
"updates",
"that",
"have",
"been",
"ignored",
".",
"Ignored",
"updates",
"are",
"shown",
"without",
"the",
"-",
"and",
"version",
"number",
"at",
"the",
"end",
"this",
"is",
"how",
"the",
"softwareupdate",
"command",
"works",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_softwareupdate.py#L136-L161 | train |
saltstack/salt | salt/modules/mac_softwareupdate.py | schedule_enabled | def schedule_enabled():
'''
Check the status of automatic update scheduling.
:return: True if scheduling is enabled, False if disabled
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' softwareupdate.schedule_enabled
'''
cmd = ['softwareupdate', '--schedule']
ret = salt.utils.mac_utils.execute_return_result(cmd)
enabled = ret.split()[-1]
return salt.utils.mac_utils.validate_enabled(enabled) == 'on' | python | def schedule_enabled():
'''
Check the status of automatic update scheduling.
:return: True if scheduling is enabled, False if disabled
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' softwareupdate.schedule_enabled
'''
cmd = ['softwareupdate', '--schedule']
ret = salt.utils.mac_utils.execute_return_result(cmd)
enabled = ret.split()[-1]
return salt.utils.mac_utils.validate_enabled(enabled) == 'on' | [
"def",
"schedule_enabled",
"(",
")",
":",
"cmd",
"=",
"[",
"'softwareupdate'",
",",
"'--schedule'",
"]",
"ret",
"=",
"salt",
".",
"utils",
".",
"mac_utils",
".",
"execute_return_result",
"(",
"cmd",
")",
"enabled",
"=",
"ret",
".",
"split",
"(",
")",
"["... | Check the status of automatic update scheduling.
:return: True if scheduling is enabled, False if disabled
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' softwareupdate.schedule_enabled | [
"Check",
"the",
"status",
"of",
"automatic",
"update",
"scheduling",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_softwareupdate.py#L184-L203 | train |
saltstack/salt | salt/modules/mac_softwareupdate.py | schedule_enable | def schedule_enable(enable):
'''
Enable/disable automatic update scheduling.
:param enable: True/On/Yes/1 to turn on automatic updates. False/No/Off/0
to turn off automatic updates. If this value is empty, the current
status will be returned.
:type: bool str
:return: True if scheduling is enabled, False if disabled
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' softwareupdate.schedule_enable on|off
'''
status = salt.utils.mac_utils.validate_enabled(enable)
cmd = ['softwareupdate',
'--schedule',
salt.utils.mac_utils.validate_enabled(status)]
salt.utils.mac_utils.execute_return_success(cmd)
return salt.utils.mac_utils.validate_enabled(schedule_enabled()) == status | python | def schedule_enable(enable):
'''
Enable/disable automatic update scheduling.
:param enable: True/On/Yes/1 to turn on automatic updates. False/No/Off/0
to turn off automatic updates. If this value is empty, the current
status will be returned.
:type: bool str
:return: True if scheduling is enabled, False if disabled
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' softwareupdate.schedule_enable on|off
'''
status = salt.utils.mac_utils.validate_enabled(enable)
cmd = ['softwareupdate',
'--schedule',
salt.utils.mac_utils.validate_enabled(status)]
salt.utils.mac_utils.execute_return_success(cmd)
return salt.utils.mac_utils.validate_enabled(schedule_enabled()) == status | [
"def",
"schedule_enable",
"(",
"enable",
")",
":",
"status",
"=",
"salt",
".",
"utils",
".",
"mac_utils",
".",
"validate_enabled",
"(",
"enable",
")",
"cmd",
"=",
"[",
"'softwareupdate'",
",",
"'--schedule'",
",",
"salt",
".",
"utils",
".",
"mac_utils",
".... | Enable/disable automatic update scheduling.
:param enable: True/On/Yes/1 to turn on automatic updates. False/No/Off/0
to turn off automatic updates. If this value is empty, the current
status will be returned.
:type: bool str
:return: True if scheduling is enabled, False if disabled
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' softwareupdate.schedule_enable on|off | [
"Enable",
"/",
"disable",
"automatic",
"update",
"scheduling",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_softwareupdate.py#L206-L232 | train |
saltstack/salt | salt/modules/mac_softwareupdate.py | update_all | def update_all(recommended=False, restart=True):
'''
Install all available updates. Returns a dictionary containing the name
of the update and the status of its installation.
:param bool recommended: If set to True, only install the recommended
updates. If set to False (default) all updates are installed.
:param bool restart: Set this to False if you do not want to install updates
that require a restart. Default is True
:return: A dictionary containing the updates that were installed and the
status of its installation. If no updates were installed an empty
dictionary is returned.
:rtype: dict
CLI Example:
.. code-block:: bash
salt '*' softwareupdate.update_all
'''
to_update = _get_available(recommended, restart)
if not to_update:
return {}
for _update in to_update:
cmd = ['softwareupdate', '--install', _update]
salt.utils.mac_utils.execute_return_success(cmd)
ret = {}
updates_left = _get_available()
for _update in to_update:
ret[_update] = True if _update not in updates_left else False
return ret | python | def update_all(recommended=False, restart=True):
'''
Install all available updates. Returns a dictionary containing the name
of the update and the status of its installation.
:param bool recommended: If set to True, only install the recommended
updates. If set to False (default) all updates are installed.
:param bool restart: Set this to False if you do not want to install updates
that require a restart. Default is True
:return: A dictionary containing the updates that were installed and the
status of its installation. If no updates were installed an empty
dictionary is returned.
:rtype: dict
CLI Example:
.. code-block:: bash
salt '*' softwareupdate.update_all
'''
to_update = _get_available(recommended, restart)
if not to_update:
return {}
for _update in to_update:
cmd = ['softwareupdate', '--install', _update]
salt.utils.mac_utils.execute_return_success(cmd)
ret = {}
updates_left = _get_available()
for _update in to_update:
ret[_update] = True if _update not in updates_left else False
return ret | [
"def",
"update_all",
"(",
"recommended",
"=",
"False",
",",
"restart",
"=",
"True",
")",
":",
"to_update",
"=",
"_get_available",
"(",
"recommended",
",",
"restart",
")",
"if",
"not",
"to_update",
":",
"return",
"{",
"}",
"for",
"_update",
"in",
"to_update... | Install all available updates. Returns a dictionary containing the name
of the update and the status of its installation.
:param bool recommended: If set to True, only install the recommended
updates. If set to False (default) all updates are installed.
:param bool restart: Set this to False if you do not want to install updates
that require a restart. Default is True
:return: A dictionary containing the updates that were installed and the
status of its installation. If no updates were installed an empty
dictionary is returned.
:rtype: dict
CLI Example:
.. code-block:: bash
salt '*' softwareupdate.update_all | [
"Install",
"all",
"available",
"updates",
".",
"Returns",
"a",
"dictionary",
"containing",
"the",
"name",
"of",
"the",
"update",
"and",
"the",
"status",
"of",
"its",
"installation",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_softwareupdate.py#L235-L273 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.