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/modules/lxc.py | _run | def _run(name,
cmd,
output=None,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=None,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
Common logic for lxc.run functions
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
'''
orig_state = state(name, path=path)
try:
if attachable(name, path=path):
ret = __salt__['container_resource.run'](
name,
cmd,
path=path,
container_type=__virtualname__,
exec_driver=EXEC_DRIVER,
output=output,
no_start=no_start,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
ignore_retcode=ignore_retcode,
use_vt=use_vt,
keep_env=keep_env)
else:
if not chroot_fallback:
raise CommandExecutionError(
'{0} is not attachable.'.format(name))
rootfs = info(name, path=path).get('rootfs')
# Set context var to make cmd.run_chroot run cmd.run instead of
# cmd.run_all.
__context__['cmd.run_chroot.func'] = __salt__['cmd.run']
ret = __salt__['cmd.run_chroot'](rootfs,
cmd,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
ignore_retcode=ignore_retcode)
except Exception:
raise
finally:
# Make sure we honor preserve_state, even if there was an exception
new_state = state(name, path=path)
if preserve_state:
if orig_state == 'stopped' and new_state != 'stopped':
stop(name, path=path)
elif orig_state == 'frozen' and new_state != 'frozen':
freeze(name, start=True, path=path)
if output in (None, 'all'):
return ret
else:
return ret[output] | python | def _run(name,
cmd,
output=None,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=None,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
Common logic for lxc.run functions
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
'''
orig_state = state(name, path=path)
try:
if attachable(name, path=path):
ret = __salt__['container_resource.run'](
name,
cmd,
path=path,
container_type=__virtualname__,
exec_driver=EXEC_DRIVER,
output=output,
no_start=no_start,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
ignore_retcode=ignore_retcode,
use_vt=use_vt,
keep_env=keep_env)
else:
if not chroot_fallback:
raise CommandExecutionError(
'{0} is not attachable.'.format(name))
rootfs = info(name, path=path).get('rootfs')
# Set context var to make cmd.run_chroot run cmd.run instead of
# cmd.run_all.
__context__['cmd.run_chroot.func'] = __salt__['cmd.run']
ret = __salt__['cmd.run_chroot'](rootfs,
cmd,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
ignore_retcode=ignore_retcode)
except Exception:
raise
finally:
# Make sure we honor preserve_state, even if there was an exception
new_state = state(name, path=path)
if preserve_state:
if orig_state == 'stopped' and new_state != 'stopped':
stop(name, path=path)
elif orig_state == 'frozen' and new_state != 'frozen':
freeze(name, start=True, path=path)
if output in (None, 'all'):
return ret
else:
return ret[output] | [
"def",
"_run",
"(",
"name",
",",
"cmd",
",",
"output",
"=",
"None",
",",
"no_start",
"=",
"False",
",",
"preserve_state",
"=",
"True",
",",
"stdin",
"=",
"None",
",",
"python_shell",
"=",
"True",
",",
"output_loglevel",
"=",
"'debug'",
",",
"use_vt",
"... | Common logic for lxc.run functions
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0 | [
"Common",
"logic",
"for",
"lxc",
".",
"run",
"functions"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/lxc.py#L3623-L3691 | train |
saltstack/salt | salt/modules/lxc.py | run | def run(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.8.0
Run :mod:`cmd.run <salt.modules.cmdmod.run>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If no output is returned using this function, try using
:mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>` or
:mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console. Assumes
``output=all``.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
CLI Example:
.. code-block:: bash
salt myminion lxc.run mycontainer 'ifconfig -a'
'''
return _run(name,
cmd,
path=path,
output=None,
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env) | python | def run(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.8.0
Run :mod:`cmd.run <salt.modules.cmdmod.run>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If no output is returned using this function, try using
:mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>` or
:mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console. Assumes
``output=all``.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
CLI Example:
.. code-block:: bash
salt myminion lxc.run mycontainer 'ifconfig -a'
'''
return _run(name,
cmd,
path=path,
output=None,
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env) | [
"def",
"run",
"(",
"name",
",",
"cmd",
",",
"no_start",
"=",
"False",
",",
"preserve_state",
"=",
"True",
",",
"stdin",
"=",
"None",
",",
"python_shell",
"=",
"True",
",",
"output_loglevel",
"=",
"'debug'",
",",
"use_vt",
"=",
"False",
",",
"path",
"="... | .. versionadded:: 2015.8.0
Run :mod:`cmd.run <salt.modules.cmdmod.run>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If no output is returned using this function, try using
:mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>` or
:mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console. Assumes
``output=all``.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
CLI Example:
.. code-block:: bash
salt myminion lxc.run mycontainer 'ifconfig -a' | [
"..",
"versionadded",
"::",
"2015",
".",
"8",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/lxc.py#L3694-L3780 | train |
saltstack/salt | salt/modules/lxc.py | _get_md5 | def _get_md5(name, path):
'''
Get the MD5 checksum of a file from a container
'''
output = run_stdout(name, 'md5sum "{0}"'.format(path),
chroot_fallback=True,
ignore_retcode=True)
try:
return output.split()[0]
except IndexError:
# Destination file does not exist or could not be accessed
return None | python | def _get_md5(name, path):
'''
Get the MD5 checksum of a file from a container
'''
output = run_stdout(name, 'md5sum "{0}"'.format(path),
chroot_fallback=True,
ignore_retcode=True)
try:
return output.split()[0]
except IndexError:
# Destination file does not exist or could not be accessed
return None | [
"def",
"_get_md5",
"(",
"name",
",",
"path",
")",
":",
"output",
"=",
"run_stdout",
"(",
"name",
",",
"'md5sum \"{0}\"'",
".",
"format",
"(",
"path",
")",
",",
"chroot_fallback",
"=",
"True",
",",
"ignore_retcode",
"=",
"True",
")",
"try",
":",
"return",... | Get the MD5 checksum of a file from a container | [
"Get",
"the",
"MD5",
"checksum",
"of",
"a",
"file",
"from",
"a",
"container"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/lxc.py#L4141-L4152 | train |
saltstack/salt | salt/modules/lxc.py | copy_to | def copy_to(name, source, dest, overwrite=False, makedirs=False, path=None):
'''
.. versionchanged:: 2015.8.0
Function renamed from ``lxc.cp`` to ``lxc.copy_to`` for consistency
with other container types. ``lxc.cp`` will continue to work, however.
For versions 2015.2.x and earlier, use ``lxc.cp``.
Copy a file or directory from the host into a container
name
Container name
source
File to be copied to the container
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
dest
Destination on the container. Must be an absolute path.
.. versionchanged:: 2015.5.0
If the destination is a directory, the file will be copied into
that directory.
overwrite : False
Unless this option is set to ``True``, then if a file exists at the
location specified by the ``dest`` argument, an error will be raised.
.. versionadded:: 2015.8.0
makedirs : False
Create the parent directory on the container if it does not already
exist.
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt 'minion' lxc.copy_to /tmp/foo /root/foo
salt 'minion' lxc.cp /tmp/foo /root/foo
'''
_ensure_running(name, no_start=True, path=path)
return __salt__['container_resource.copy_to'](
name,
source,
dest,
container_type=__virtualname__,
path=path,
exec_driver=EXEC_DRIVER,
overwrite=overwrite,
makedirs=makedirs) | python | def copy_to(name, source, dest, overwrite=False, makedirs=False, path=None):
'''
.. versionchanged:: 2015.8.0
Function renamed from ``lxc.cp`` to ``lxc.copy_to`` for consistency
with other container types. ``lxc.cp`` will continue to work, however.
For versions 2015.2.x and earlier, use ``lxc.cp``.
Copy a file or directory from the host into a container
name
Container name
source
File to be copied to the container
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
dest
Destination on the container. Must be an absolute path.
.. versionchanged:: 2015.5.0
If the destination is a directory, the file will be copied into
that directory.
overwrite : False
Unless this option is set to ``True``, then if a file exists at the
location specified by the ``dest`` argument, an error will be raised.
.. versionadded:: 2015.8.0
makedirs : False
Create the parent directory on the container if it does not already
exist.
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt 'minion' lxc.copy_to /tmp/foo /root/foo
salt 'minion' lxc.cp /tmp/foo /root/foo
'''
_ensure_running(name, no_start=True, path=path)
return __salt__['container_resource.copy_to'](
name,
source,
dest,
container_type=__virtualname__,
path=path,
exec_driver=EXEC_DRIVER,
overwrite=overwrite,
makedirs=makedirs) | [
"def",
"copy_to",
"(",
"name",
",",
"source",
",",
"dest",
",",
"overwrite",
"=",
"False",
",",
"makedirs",
"=",
"False",
",",
"path",
"=",
"None",
")",
":",
"_ensure_running",
"(",
"name",
",",
"no_start",
"=",
"True",
",",
"path",
"=",
"path",
")",... | .. versionchanged:: 2015.8.0
Function renamed from ``lxc.cp`` to ``lxc.copy_to`` for consistency
with other container types. ``lxc.cp`` will continue to work, however.
For versions 2015.2.x and earlier, use ``lxc.cp``.
Copy a file or directory from the host into a container
name
Container name
source
File to be copied to the container
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
dest
Destination on the container. Must be an absolute path.
.. versionchanged:: 2015.5.0
If the destination is a directory, the file will be copied into
that directory.
overwrite : False
Unless this option is set to ``True``, then if a file exists at the
location specified by the ``dest`` argument, an error will be raised.
.. versionadded:: 2015.8.0
makedirs : False
Create the parent directory on the container if it does not already
exist.
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt 'minion' lxc.copy_to /tmp/foo /root/foo
salt 'minion' lxc.cp /tmp/foo /root/foo | [
"..",
"versionchanged",
"::",
"2015",
".",
"8",
".",
"0",
"Function",
"renamed",
"from",
"lxc",
".",
"cp",
"to",
"lxc",
".",
"copy_to",
"for",
"consistency",
"with",
"other",
"container",
"types",
".",
"lxc",
".",
"cp",
"will",
"continue",
"to",
"work",
... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/lxc.py#L4155-L4212 | train |
saltstack/salt | salt/modules/lxc.py | read_conf | def read_conf(conf_file, out_format='simple'):
'''
Read in an LXC configuration file. By default returns a simple, unsorted
dict, but can also return a more detailed structure including blank lines
and comments.
out_format:
set to 'simple' if you need the old and unsupported behavior.
This won't support the multiple lxc values (eg: multiple network nics)
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.read_conf /etc/lxc/mycontainer.conf
salt 'minion' lxc.read_conf /etc/lxc/mycontainer.conf out_format=commented
'''
ret_commented = []
ret_simple = {}
with salt.utils.files.fopen(conf_file, 'r') as fp_:
for line in salt.utils.data.decode(fp_.readlines()):
if '=' not in line:
ret_commented.append(line)
continue
comps = line.split('=')
value = '='.join(comps[1:]).strip()
comment = None
if value.strip().startswith('#'):
vcomps = value.strip().split('#')
value = vcomps[1].strip()
comment = '#'.join(vcomps[1:]).strip()
ret_commented.append({comps[0].strip(): {
'value': value,
'comment': comment,
}})
else:
ret_commented.append({comps[0].strip(): value})
ret_simple[comps[0].strip()] = value
if out_format == 'simple':
return ret_simple
return ret_commented | python | def read_conf(conf_file, out_format='simple'):
'''
Read in an LXC configuration file. By default returns a simple, unsorted
dict, but can also return a more detailed structure including blank lines
and comments.
out_format:
set to 'simple' if you need the old and unsupported behavior.
This won't support the multiple lxc values (eg: multiple network nics)
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.read_conf /etc/lxc/mycontainer.conf
salt 'minion' lxc.read_conf /etc/lxc/mycontainer.conf out_format=commented
'''
ret_commented = []
ret_simple = {}
with salt.utils.files.fopen(conf_file, 'r') as fp_:
for line in salt.utils.data.decode(fp_.readlines()):
if '=' not in line:
ret_commented.append(line)
continue
comps = line.split('=')
value = '='.join(comps[1:]).strip()
comment = None
if value.strip().startswith('#'):
vcomps = value.strip().split('#')
value = vcomps[1].strip()
comment = '#'.join(vcomps[1:]).strip()
ret_commented.append({comps[0].strip(): {
'value': value,
'comment': comment,
}})
else:
ret_commented.append({comps[0].strip(): value})
ret_simple[comps[0].strip()] = value
if out_format == 'simple':
return ret_simple
return ret_commented | [
"def",
"read_conf",
"(",
"conf_file",
",",
"out_format",
"=",
"'simple'",
")",
":",
"ret_commented",
"=",
"[",
"]",
"ret_simple",
"=",
"{",
"}",
"with",
"salt",
".",
"utils",
".",
"files",
".",
"fopen",
"(",
"conf_file",
",",
"'r'",
")",
"as",
"fp_",
... | Read in an LXC configuration file. By default returns a simple, unsorted
dict, but can also return a more detailed structure including blank lines
and comments.
out_format:
set to 'simple' if you need the old and unsupported behavior.
This won't support the multiple lxc values (eg: multiple network nics)
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.read_conf /etc/lxc/mycontainer.conf
salt 'minion' lxc.read_conf /etc/lxc/mycontainer.conf out_format=commented | [
"Read",
"in",
"an",
"LXC",
"configuration",
"file",
".",
"By",
"default",
"returns",
"a",
"simple",
"unsorted",
"dict",
"but",
"can",
"also",
"return",
"a",
"more",
"detailed",
"structure",
"including",
"blank",
"lines",
"and",
"comments",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/lxc.py#L4218-L4259 | train |
saltstack/salt | salt/modules/lxc.py | write_conf | def write_conf(conf_file, conf):
'''
Write out an LXC configuration file
This is normally only used internally. The format of the data structure
must match that which is returned from ``lxc.read_conf()``, with
``out_format`` set to ``commented``.
An example might look like:
.. code-block:: python
[
{'lxc.utsname': '$CONTAINER_NAME'},
'# This is a commented line\\n',
'\\n',
{'lxc.mount': '$CONTAINER_FSTAB'},
{'lxc.rootfs': {'comment': 'This is another test',
'value': 'This is another test'}},
'\\n',
{'lxc.network.type': 'veth'},
{'lxc.network.flags': 'up'},
{'lxc.network.link': 'br0'},
{'lxc.network.mac': '$CONTAINER_MACADDR'},
{'lxc.network.ipv4': '$CONTAINER_IPADDR'},
{'lxc.network.name': '$CONTAINER_DEVICENAME'},
]
CLI Example:
.. code-block:: bash
salt 'minion' lxc.write_conf /etc/lxc/mycontainer.conf \\
out_format=commented
'''
if not isinstance(conf, list):
raise SaltInvocationError('Configuration must be passed as a list')
# construct the content prior to write to the file
# to avoid half written configs
content = ''
for line in conf:
if isinstance(line, (six.text_type, six.string_types)):
content += line
elif isinstance(line, dict):
for key in list(line.keys()):
out_line = None
if isinstance(
line[key],
(six.text_type, six.string_types, six.integer_types, float)
):
out_line = ' = '.join((key, "{0}".format(line[key])))
elif isinstance(line[key], dict):
out_line = ' = '.join((key, line[key]['value']))
if 'comment' in line[key]:
out_line = ' # '.join((out_line, line[key]['comment']))
if out_line:
content += out_line
content += '\n'
with salt.utils.files.fopen(conf_file, 'w') as fp_:
fp_.write(salt.utils.stringutils.to_str(content))
return {} | python | def write_conf(conf_file, conf):
'''
Write out an LXC configuration file
This is normally only used internally. The format of the data structure
must match that which is returned from ``lxc.read_conf()``, with
``out_format`` set to ``commented``.
An example might look like:
.. code-block:: python
[
{'lxc.utsname': '$CONTAINER_NAME'},
'# This is a commented line\\n',
'\\n',
{'lxc.mount': '$CONTAINER_FSTAB'},
{'lxc.rootfs': {'comment': 'This is another test',
'value': 'This is another test'}},
'\\n',
{'lxc.network.type': 'veth'},
{'lxc.network.flags': 'up'},
{'lxc.network.link': 'br0'},
{'lxc.network.mac': '$CONTAINER_MACADDR'},
{'lxc.network.ipv4': '$CONTAINER_IPADDR'},
{'lxc.network.name': '$CONTAINER_DEVICENAME'},
]
CLI Example:
.. code-block:: bash
salt 'minion' lxc.write_conf /etc/lxc/mycontainer.conf \\
out_format=commented
'''
if not isinstance(conf, list):
raise SaltInvocationError('Configuration must be passed as a list')
# construct the content prior to write to the file
# to avoid half written configs
content = ''
for line in conf:
if isinstance(line, (six.text_type, six.string_types)):
content += line
elif isinstance(line, dict):
for key in list(line.keys()):
out_line = None
if isinstance(
line[key],
(six.text_type, six.string_types, six.integer_types, float)
):
out_line = ' = '.join((key, "{0}".format(line[key])))
elif isinstance(line[key], dict):
out_line = ' = '.join((key, line[key]['value']))
if 'comment' in line[key]:
out_line = ' # '.join((out_line, line[key]['comment']))
if out_line:
content += out_line
content += '\n'
with salt.utils.files.fopen(conf_file, 'w') as fp_:
fp_.write(salt.utils.stringutils.to_str(content))
return {} | [
"def",
"write_conf",
"(",
"conf_file",
",",
"conf",
")",
":",
"if",
"not",
"isinstance",
"(",
"conf",
",",
"list",
")",
":",
"raise",
"SaltInvocationError",
"(",
"'Configuration must be passed as a list'",
")",
"# construct the content prior to write to the file",
"# to... | Write out an LXC configuration file
This is normally only used internally. The format of the data structure
must match that which is returned from ``lxc.read_conf()``, with
``out_format`` set to ``commented``.
An example might look like:
.. code-block:: python
[
{'lxc.utsname': '$CONTAINER_NAME'},
'# This is a commented line\\n',
'\\n',
{'lxc.mount': '$CONTAINER_FSTAB'},
{'lxc.rootfs': {'comment': 'This is another test',
'value': 'This is another test'}},
'\\n',
{'lxc.network.type': 'veth'},
{'lxc.network.flags': 'up'},
{'lxc.network.link': 'br0'},
{'lxc.network.mac': '$CONTAINER_MACADDR'},
{'lxc.network.ipv4': '$CONTAINER_IPADDR'},
{'lxc.network.name': '$CONTAINER_DEVICENAME'},
]
CLI Example:
.. code-block:: bash
salt 'minion' lxc.write_conf /etc/lxc/mycontainer.conf \\
out_format=commented | [
"Write",
"out",
"an",
"LXC",
"configuration",
"file"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/lxc.py#L4262-L4323 | train |
saltstack/salt | salt/modules/lxc.py | edit_conf | def edit_conf(conf_file,
out_format='simple',
read_only=False,
lxc_config=None,
**kwargs):
'''
Edit an LXC configuration file. If a setting is already present inside the
file, its value will be replaced. If it does not exist, it will be appended
to the end of the file. Comments and blank lines will be kept in-tact if
they already exist in the file.
out_format:
Set to simple if you need backward compatibility (multiple items for a
simple key is not supported)
read_only:
return only the edited configuration without applying it
to the underlying lxc configuration file
lxc_config:
List of dict containning lxc configuration items
For network configuration, you also need to add the device it belongs
to, otherwise it will default to eth0.
Also, any change to a network parameter will result in the whole
network reconfiguration to avoid mismatchs, be aware of that !
After the file is edited, its contents will be returned. By default, it
will be returned in ``simple`` format, meaning an unordered dict (which
may not represent the actual file order). Passing in an ``out_format`` of
``commented`` will return a data structure which accurately represents the
order and content of the file.
CLI Example:
.. code-block:: bash
salt 'minion' lxc.edit_conf /etc/lxc/mycontainer.conf \\
out_format=commented lxc.network.type=veth
salt 'minion' lxc.edit_conf /etc/lxc/mycontainer.conf \\
out_format=commented \\
lxc_config="[{'lxc.network.name': 'eth0', \\
'lxc.network.ipv4': '1.2.3.4'},
{'lxc.network.name': 'eth2', \\
'lxc.network.ipv4': '1.2.3.5',\\
'lxc.network.gateway': '1.2.3.1'}]"
'''
data = []
try:
conf = read_conf(conf_file, out_format=out_format)
except Exception:
conf = []
if not lxc_config:
lxc_config = []
lxc_config = copy.deepcopy(lxc_config)
# search if we want to access net config
# in that case, we will replace all the net configuration
net_config = []
for lxc_kws in lxc_config + [kwargs]:
net_params = {}
for kwarg in [a for a in lxc_kws]:
if kwarg.startswith('__'):
continue
if kwarg.startswith('lxc.network.'):
net_params[kwarg] = lxc_kws[kwarg]
lxc_kws.pop(kwarg, None)
if net_params:
net_config.append(net_params)
nic_opts = salt.utils.odict.OrderedDict()
for params in net_config:
dev = params.get('lxc.network.name', DEFAULT_NIC)
dev_opts = nic_opts.setdefault(dev, salt.utils.odict.OrderedDict())
for param in params:
opt = param.replace('lxc.network.', '')
opt = {'hwaddr': 'mac'}.get(opt, opt)
dev_opts[opt] = params[param]
net_changes = []
if nic_opts:
net_changes = _config_list(conf, only_net=True,
**{'network_profile': DEFAULT_NIC,
'nic_opts': nic_opts})
if net_changes:
lxc_config.extend(net_changes)
for line in conf:
if not isinstance(line, dict):
data.append(line)
continue
else:
for key in list(line.keys()):
val = line[key]
if net_changes and key.startswith('lxc.network.'):
continue
found = False
for ix in range(len(lxc_config)):
kw = lxc_config[ix]
if key in kw:
found = True
data.append({key: kw[key]})
del kw[key]
if not found:
data.append({key: val})
for lxc_kws in lxc_config:
for kwarg in lxc_kws:
data.append({kwarg: lxc_kws[kwarg]})
if read_only:
return data
write_conf(conf_file, data)
return read_conf(conf_file, out_format) | python | def edit_conf(conf_file,
out_format='simple',
read_only=False,
lxc_config=None,
**kwargs):
'''
Edit an LXC configuration file. If a setting is already present inside the
file, its value will be replaced. If it does not exist, it will be appended
to the end of the file. Comments and blank lines will be kept in-tact if
they already exist in the file.
out_format:
Set to simple if you need backward compatibility (multiple items for a
simple key is not supported)
read_only:
return only the edited configuration without applying it
to the underlying lxc configuration file
lxc_config:
List of dict containning lxc configuration items
For network configuration, you also need to add the device it belongs
to, otherwise it will default to eth0.
Also, any change to a network parameter will result in the whole
network reconfiguration to avoid mismatchs, be aware of that !
After the file is edited, its contents will be returned. By default, it
will be returned in ``simple`` format, meaning an unordered dict (which
may not represent the actual file order). Passing in an ``out_format`` of
``commented`` will return a data structure which accurately represents the
order and content of the file.
CLI Example:
.. code-block:: bash
salt 'minion' lxc.edit_conf /etc/lxc/mycontainer.conf \\
out_format=commented lxc.network.type=veth
salt 'minion' lxc.edit_conf /etc/lxc/mycontainer.conf \\
out_format=commented \\
lxc_config="[{'lxc.network.name': 'eth0', \\
'lxc.network.ipv4': '1.2.3.4'},
{'lxc.network.name': 'eth2', \\
'lxc.network.ipv4': '1.2.3.5',\\
'lxc.network.gateway': '1.2.3.1'}]"
'''
data = []
try:
conf = read_conf(conf_file, out_format=out_format)
except Exception:
conf = []
if not lxc_config:
lxc_config = []
lxc_config = copy.deepcopy(lxc_config)
# search if we want to access net config
# in that case, we will replace all the net configuration
net_config = []
for lxc_kws in lxc_config + [kwargs]:
net_params = {}
for kwarg in [a for a in lxc_kws]:
if kwarg.startswith('__'):
continue
if kwarg.startswith('lxc.network.'):
net_params[kwarg] = lxc_kws[kwarg]
lxc_kws.pop(kwarg, None)
if net_params:
net_config.append(net_params)
nic_opts = salt.utils.odict.OrderedDict()
for params in net_config:
dev = params.get('lxc.network.name', DEFAULT_NIC)
dev_opts = nic_opts.setdefault(dev, salt.utils.odict.OrderedDict())
for param in params:
opt = param.replace('lxc.network.', '')
opt = {'hwaddr': 'mac'}.get(opt, opt)
dev_opts[opt] = params[param]
net_changes = []
if nic_opts:
net_changes = _config_list(conf, only_net=True,
**{'network_profile': DEFAULT_NIC,
'nic_opts': nic_opts})
if net_changes:
lxc_config.extend(net_changes)
for line in conf:
if not isinstance(line, dict):
data.append(line)
continue
else:
for key in list(line.keys()):
val = line[key]
if net_changes and key.startswith('lxc.network.'):
continue
found = False
for ix in range(len(lxc_config)):
kw = lxc_config[ix]
if key in kw:
found = True
data.append({key: kw[key]})
del kw[key]
if not found:
data.append({key: val})
for lxc_kws in lxc_config:
for kwarg in lxc_kws:
data.append({kwarg: lxc_kws[kwarg]})
if read_only:
return data
write_conf(conf_file, data)
return read_conf(conf_file, out_format) | [
"def",
"edit_conf",
"(",
"conf_file",
",",
"out_format",
"=",
"'simple'",
",",
"read_only",
"=",
"False",
",",
"lxc_config",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"data",
"=",
"[",
"]",
"try",
":",
"conf",
"=",
"read_conf",
"(",
"conf_file",
... | Edit an LXC configuration file. If a setting is already present inside the
file, its value will be replaced. If it does not exist, it will be appended
to the end of the file. Comments and blank lines will be kept in-tact if
they already exist in the file.
out_format:
Set to simple if you need backward compatibility (multiple items for a
simple key is not supported)
read_only:
return only the edited configuration without applying it
to the underlying lxc configuration file
lxc_config:
List of dict containning lxc configuration items
For network configuration, you also need to add the device it belongs
to, otherwise it will default to eth0.
Also, any change to a network parameter will result in the whole
network reconfiguration to avoid mismatchs, be aware of that !
After the file is edited, its contents will be returned. By default, it
will be returned in ``simple`` format, meaning an unordered dict (which
may not represent the actual file order). Passing in an ``out_format`` of
``commented`` will return a data structure which accurately represents the
order and content of the file.
CLI Example:
.. code-block:: bash
salt 'minion' lxc.edit_conf /etc/lxc/mycontainer.conf \\
out_format=commented lxc.network.type=veth
salt 'minion' lxc.edit_conf /etc/lxc/mycontainer.conf \\
out_format=commented \\
lxc_config="[{'lxc.network.name': 'eth0', \\
'lxc.network.ipv4': '1.2.3.4'},
{'lxc.network.name': 'eth2', \\
'lxc.network.ipv4': '1.2.3.5',\\
'lxc.network.gateway': '1.2.3.1'}]" | [
"Edit",
"an",
"LXC",
"configuration",
"file",
".",
"If",
"a",
"setting",
"is",
"already",
"present",
"inside",
"the",
"file",
"its",
"value",
"will",
"be",
"replaced",
".",
"If",
"it",
"does",
"not",
"exist",
"it",
"will",
"be",
"appended",
"to",
"the",
... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/lxc.py#L4326-L4436 | train |
saltstack/salt | salt/modules/lxc.py | reboot | def reboot(name, path=None):
'''
Reboot a container.
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.reboot myvm
'''
ret = {'result': True,
'changes': {},
'comment': '{0} rebooted'.format(name)}
does_exist = exists(name, path=path)
if does_exist and (state(name, path=path) == 'running'):
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
return ret
if does_exist and (state(name, path=path) != 'running'):
try:
start(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
return ret
ret['changes'][name] = 'rebooted'
return ret | python | def reboot(name, path=None):
'''
Reboot a container.
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.reboot myvm
'''
ret = {'result': True,
'changes': {},
'comment': '{0} rebooted'.format(name)}
does_exist = exists(name, path=path)
if does_exist and (state(name, path=path) == 'running'):
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
return ret
if does_exist and (state(name, path=path) != 'running'):
try:
start(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
return ret
ret['changes'][name] = 'rebooted'
return ret | [
"def",
"reboot",
"(",
"name",
",",
"path",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'result'",
":",
"True",
",",
"'changes'",
":",
"{",
"}",
",",
"'comment'",
":",
"'{0} rebooted'",
".",
"format",
"(",
"name",
")",
"}",
"does_exist",
"=",
"exists",
... | Reboot a container.
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.reboot myvm | [
"Reboot",
"a",
"container",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/lxc.py#L4439-L4476 | train |
saltstack/salt | salt/modules/lxc.py | reconfigure | def reconfigure(name,
cpu=None,
cpuset=None,
cpushare=None,
memory=None,
profile=None,
network_profile=None,
nic_opts=None,
bridge=None,
gateway=None,
autostart=None,
utsname=None,
rootfs=None,
path=None,
**kwargs):
'''
Reconfigure a container.
This only applies to a few property
name
Name of the container.
utsname
utsname of the container.
.. versionadded:: 2016.3.0
rootfs
rootfs of the container.
.. versionadded:: 2016.3.0
cpu
Select a random number of cpu cores and assign it to the cpuset, if the
cpuset option is set then this option will be ignored
cpuset
Explicitly define the cpus this container will be bound to
cpushare
cgroups cpu shares.
autostart
autostart container on reboot
memory
cgroups memory limit, in MB.
(0 for nolimit, None for old default 1024MB)
gateway
the ipv4 gateway to use
the default does nothing more than lxcutils does
bridge
the bridge to use
the default does nothing more than lxcutils does
nic
Network interfaces profile (defined in config or pillar).
nic_opts
Extra options for network interfaces, will override
``{"eth0": {"mac": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1", "ipv6": "2001:db8::ff00:42:8329"}}``
or
``{"eth0": {"mac": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1/24", "ipv6": "2001:db8::ff00:42:8329"}}``
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt-call -lall mc_lxc_fork.reconfigure foobar nic_opts="{'eth1': {'mac': '00:16:3e:dd:ee:44'}}" memory=4
'''
changes = {}
cpath = get_root_path(path)
path = os.path.join(cpath, name, 'config')
ret = {'name': name,
'comment': 'config for {0} up to date'.format(name),
'result': True,
'changes': changes}
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
if nic_opts is not None and not network_profile:
network_profile = DEFAULT_NIC
if autostart is not None:
autostart = select('autostart', autostart)
else:
autostart = 'keep'
if not utsname:
utsname = select('utsname', utsname)
if os.path.exists(path):
old_chunks = read_conf(path, out_format='commented')
make_kw = salt.utils.odict.OrderedDict([
('utsname', utsname),
('rootfs', rootfs),
('autostart', autostart),
('cpu', cpu),
('gateway', gateway),
('cpuset', cpuset),
('cpushare', cpushare),
('network_profile', network_profile),
('nic_opts', nic_opts),
('bridge', bridge)])
# match 0 and none as memory = 0 in lxc config is harmful
if memory:
make_kw['memory'] = memory
kw = salt.utils.odict.OrderedDict()
for key, val in six.iteritems(make_kw):
if val is not None:
kw[key] = val
new_cfg = _config_list(conf_tuples=old_chunks, **kw)
if new_cfg:
edit_conf(path, out_format='commented', lxc_config=new_cfg)
chunks = read_conf(path, out_format='commented')
if old_chunks != chunks:
ret['comment'] = '{0} lxc config updated'.format(name)
if state(name, path=path) == 'running':
cret = reboot(name, path=path)
ret['result'] = cret['result']
return ret | python | def reconfigure(name,
cpu=None,
cpuset=None,
cpushare=None,
memory=None,
profile=None,
network_profile=None,
nic_opts=None,
bridge=None,
gateway=None,
autostart=None,
utsname=None,
rootfs=None,
path=None,
**kwargs):
'''
Reconfigure a container.
This only applies to a few property
name
Name of the container.
utsname
utsname of the container.
.. versionadded:: 2016.3.0
rootfs
rootfs of the container.
.. versionadded:: 2016.3.0
cpu
Select a random number of cpu cores and assign it to the cpuset, if the
cpuset option is set then this option will be ignored
cpuset
Explicitly define the cpus this container will be bound to
cpushare
cgroups cpu shares.
autostart
autostart container on reboot
memory
cgroups memory limit, in MB.
(0 for nolimit, None for old default 1024MB)
gateway
the ipv4 gateway to use
the default does nothing more than lxcutils does
bridge
the bridge to use
the default does nothing more than lxcutils does
nic
Network interfaces profile (defined in config or pillar).
nic_opts
Extra options for network interfaces, will override
``{"eth0": {"mac": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1", "ipv6": "2001:db8::ff00:42:8329"}}``
or
``{"eth0": {"mac": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1/24", "ipv6": "2001:db8::ff00:42:8329"}}``
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt-call -lall mc_lxc_fork.reconfigure foobar nic_opts="{'eth1': {'mac': '00:16:3e:dd:ee:44'}}" memory=4
'''
changes = {}
cpath = get_root_path(path)
path = os.path.join(cpath, name, 'config')
ret = {'name': name,
'comment': 'config for {0} up to date'.format(name),
'result': True,
'changes': changes}
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
if nic_opts is not None and not network_profile:
network_profile = DEFAULT_NIC
if autostart is not None:
autostart = select('autostart', autostart)
else:
autostart = 'keep'
if not utsname:
utsname = select('utsname', utsname)
if os.path.exists(path):
old_chunks = read_conf(path, out_format='commented')
make_kw = salt.utils.odict.OrderedDict([
('utsname', utsname),
('rootfs', rootfs),
('autostart', autostart),
('cpu', cpu),
('gateway', gateway),
('cpuset', cpuset),
('cpushare', cpushare),
('network_profile', network_profile),
('nic_opts', nic_opts),
('bridge', bridge)])
# match 0 and none as memory = 0 in lxc config is harmful
if memory:
make_kw['memory'] = memory
kw = salt.utils.odict.OrderedDict()
for key, val in six.iteritems(make_kw):
if val is not None:
kw[key] = val
new_cfg = _config_list(conf_tuples=old_chunks, **kw)
if new_cfg:
edit_conf(path, out_format='commented', lxc_config=new_cfg)
chunks = read_conf(path, out_format='commented')
if old_chunks != chunks:
ret['comment'] = '{0} lxc config updated'.format(name)
if state(name, path=path) == 'running':
cret = reboot(name, path=path)
ret['result'] = cret['result']
return ret | [
"def",
"reconfigure",
"(",
"name",
",",
"cpu",
"=",
"None",
",",
"cpuset",
"=",
"None",
",",
"cpushare",
"=",
"None",
",",
"memory",
"=",
"None",
",",
"profile",
"=",
"None",
",",
"network_profile",
"=",
"None",
",",
"nic_opts",
"=",
"None",
",",
"br... | Reconfigure a container.
This only applies to a few property
name
Name of the container.
utsname
utsname of the container.
.. versionadded:: 2016.3.0
rootfs
rootfs of the container.
.. versionadded:: 2016.3.0
cpu
Select a random number of cpu cores and assign it to the cpuset, if the
cpuset option is set then this option will be ignored
cpuset
Explicitly define the cpus this container will be bound to
cpushare
cgroups cpu shares.
autostart
autostart container on reboot
memory
cgroups memory limit, in MB.
(0 for nolimit, None for old default 1024MB)
gateway
the ipv4 gateway to use
the default does nothing more than lxcutils does
bridge
the bridge to use
the default does nothing more than lxcutils does
nic
Network interfaces profile (defined in config or pillar).
nic_opts
Extra options for network interfaces, will override
``{"eth0": {"mac": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1", "ipv6": "2001:db8::ff00:42:8329"}}``
or
``{"eth0": {"mac": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1/24", "ipv6": "2001:db8::ff00:42:8329"}}``
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt-call -lall mc_lxc_fork.reconfigure foobar nic_opts="{'eth1': {'mac': '00:16:3e:dd:ee:44'}}" memory=4 | [
"Reconfigure",
"a",
"container",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/lxc.py#L4479-L4608 | train |
saltstack/salt | salt/modules/lxc.py | apply_network_profile | def apply_network_profile(name, network_profile, nic_opts=None, path=None):
'''
.. versionadded:: 2015.5.0
Apply a network profile to a container
network_profile
profile name or default values (dict)
nic_opts
values to override in defaults (dict)
indexed by nic card names
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.apply_network_profile web1 centos
salt 'minion' lxc.apply_network_profile web1 centos \\
nic_opts="{'eth0': {'mac': 'xx:xx:xx:xx:xx:xx'}}"
salt 'minion' lxc.apply_network_profile web1 \\
"{'eth0': {'mac': 'xx:xx:xx:xx:xx:yy'}}"
nic_opts="{'eth0': {'mac': 'xx:xx:xx:xx:xx:xx'}}"
The special case to disable use of ethernet nics:
.. code-block:: bash
salt 'minion' lxc.apply_network_profile web1 centos \\
"{eth0: {disable: true}}"
'''
cpath = get_root_path(path)
cfgpath = os.path.join(cpath, name, 'config')
before = []
with salt.utils.files.fopen(cfgpath, 'r') as fp_:
for line in fp_:
before.append(line)
lxcconfig = _LXCConfig(name=name, path=path)
old_net = lxcconfig._filter_data('lxc.network')
network_params = {}
for param in _network_conf(
conf_tuples=old_net,
network_profile=network_profile, nic_opts=nic_opts
):
network_params.update(param)
if network_params:
edit_conf(cfgpath, out_format='commented', **network_params)
after = []
with salt.utils.files.fopen(cfgpath, 'r') as fp_:
for line in fp_:
after.append(line)
diff = ''
for line in difflib.unified_diff(before,
after,
fromfile='before',
tofile='after'):
diff += line
return diff | python | def apply_network_profile(name, network_profile, nic_opts=None, path=None):
'''
.. versionadded:: 2015.5.0
Apply a network profile to a container
network_profile
profile name or default values (dict)
nic_opts
values to override in defaults (dict)
indexed by nic card names
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.apply_network_profile web1 centos
salt 'minion' lxc.apply_network_profile web1 centos \\
nic_opts="{'eth0': {'mac': 'xx:xx:xx:xx:xx:xx'}}"
salt 'minion' lxc.apply_network_profile web1 \\
"{'eth0': {'mac': 'xx:xx:xx:xx:xx:yy'}}"
nic_opts="{'eth0': {'mac': 'xx:xx:xx:xx:xx:xx'}}"
The special case to disable use of ethernet nics:
.. code-block:: bash
salt 'minion' lxc.apply_network_profile web1 centos \\
"{eth0: {disable: true}}"
'''
cpath = get_root_path(path)
cfgpath = os.path.join(cpath, name, 'config')
before = []
with salt.utils.files.fopen(cfgpath, 'r') as fp_:
for line in fp_:
before.append(line)
lxcconfig = _LXCConfig(name=name, path=path)
old_net = lxcconfig._filter_data('lxc.network')
network_params = {}
for param in _network_conf(
conf_tuples=old_net,
network_profile=network_profile, nic_opts=nic_opts
):
network_params.update(param)
if network_params:
edit_conf(cfgpath, out_format='commented', **network_params)
after = []
with salt.utils.files.fopen(cfgpath, 'r') as fp_:
for line in fp_:
after.append(line)
diff = ''
for line in difflib.unified_diff(before,
after,
fromfile='before',
tofile='after'):
diff += line
return diff | [
"def",
"apply_network_profile",
"(",
"name",
",",
"network_profile",
",",
"nic_opts",
"=",
"None",
",",
"path",
"=",
"None",
")",
":",
"cpath",
"=",
"get_root_path",
"(",
"path",
")",
"cfgpath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"cpath",
",",
"... | .. versionadded:: 2015.5.0
Apply a network profile to a container
network_profile
profile name or default values (dict)
nic_opts
values to override in defaults (dict)
indexed by nic card names
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.apply_network_profile web1 centos
salt 'minion' lxc.apply_network_profile web1 centos \\
nic_opts="{'eth0': {'mac': 'xx:xx:xx:xx:xx:xx'}}"
salt 'minion' lxc.apply_network_profile web1 \\
"{'eth0': {'mac': 'xx:xx:xx:xx:xx:yy'}}"
nic_opts="{'eth0': {'mac': 'xx:xx:xx:xx:xx:xx'}}"
The special case to disable use of ethernet nics:
.. code-block:: bash
salt 'minion' lxc.apply_network_profile web1 centos \\
"{eth0: {disable: true}}" | [
"..",
"versionadded",
"::",
"2015",
".",
"5",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/lxc.py#L4611-L4678 | train |
saltstack/salt | salt/modules/lxc.py | get_pid | def get_pid(name, path=None):
'''
Returns a container pid.
Throw an exception if the container isn't running.
CLI Example:
.. code-block:: bash
salt '*' lxc.get_pid name
'''
if name not in list_(limit='running', path=path):
raise CommandExecutionError('Container {0} is not running, can\'t determine PID'.format(name))
info = __salt__['cmd.run']('lxc-info -n {0}'.format(name)).split("\n")
pid = [line.split(':')[1].strip() for line in info if re.match(r'\s*PID', line)][0]
return pid | python | def get_pid(name, path=None):
'''
Returns a container pid.
Throw an exception if the container isn't running.
CLI Example:
.. code-block:: bash
salt '*' lxc.get_pid name
'''
if name not in list_(limit='running', path=path):
raise CommandExecutionError('Container {0} is not running, can\'t determine PID'.format(name))
info = __salt__['cmd.run']('lxc-info -n {0}'.format(name)).split("\n")
pid = [line.split(':')[1].strip() for line in info if re.match(r'\s*PID', line)][0]
return pid | [
"def",
"get_pid",
"(",
"name",
",",
"path",
"=",
"None",
")",
":",
"if",
"name",
"not",
"in",
"list_",
"(",
"limit",
"=",
"'running'",
",",
"path",
"=",
"path",
")",
":",
"raise",
"CommandExecutionError",
"(",
"'Container {0} is not running, can\\'t determine ... | Returns a container pid.
Throw an exception if the container isn't running.
CLI Example:
.. code-block:: bash
salt '*' lxc.get_pid name | [
"Returns",
"a",
"container",
"pid",
".",
"Throw",
"an",
"exception",
"if",
"the",
"container",
"isn",
"t",
"running",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/lxc.py#L4681-L4696 | train |
saltstack/salt | salt/modules/lxc.py | add_veth | def add_veth(name, interface_name, bridge=None, path=None):
'''
Add a veth to a container.
Note : this function doesn't update the container config, just add the interface at runtime
name
Name of the container
interface_name
Name of the interface in the container
bridge
Name of the bridge to attach the interface to (facultative)
CLI Examples:
.. code-block:: bash
salt '*' lxc.add_veth container_name eth1 br1
salt '*' lxc.add_veth container_name eth1
'''
# Get container init PID
pid = get_pid(name, path=path)
# Generate a ramdom string for veth and ensure that is isn't present on the system
while True:
random_veth = 'veth'+''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(6))
if random_veth not in __salt__['network.interfaces']().keys():
break
# Check prerequisites
if not __salt__['file.directory_exists']('/var/run/'):
raise CommandExecutionError('Directory /var/run required for lxc.add_veth doesn\'t exists')
if not __salt__['file.file_exists']('/proc/{0}/ns/net'.format(pid)):
raise CommandExecutionError('Proc file for container {0} network namespace doesn\'t exists'.format(name))
if not __salt__['file.directory_exists']('/var/run/netns'):
__salt__['file.mkdir']('/var/run/netns')
# Ensure that the symlink is up to date (change on container restart)
if __salt__['file.is_link']('/var/run/netns/{0}'.format(name)):
__salt__['file.remove']('/var/run/netns/{0}'.format(name))
__salt__['file.symlink']('/proc/{0}/ns/net'.format(pid), '/var/run/netns/{0}'.format(name))
# Ensure that interface doesn't exists
interface_exists = 0 == __salt__['cmd.retcode']('ip netns exec {netns} ip address list {interface}'.format(
netns=name,
interface=interface_name
))
if interface_exists:
raise CommandExecutionError('Interface {interface} already exists in {container}'.format(
interface=interface_name,
container=name
))
# Create veth and bring it up
if __salt__['cmd.retcode']('ip link add name {veth} type veth peer name {veth}_c'.format(veth=random_veth)) != 0:
raise CommandExecutionError('Error while creating the veth pair {0}'.format(random_veth))
if __salt__['cmd.retcode']('ip link set dev {0} up'.format(random_veth)) != 0:
raise CommandExecutionError('Error while bringing up host-side veth {0}'.format(random_veth))
# Attach it to the container
attached = 0 == __salt__['cmd.retcode']('ip link set dev {veth}_c netns {container} name {interface_name}'.format(
veth=random_veth,
container=name,
interface_name=interface_name
))
if not attached:
raise CommandExecutionError('Error while attaching the veth {veth} to container {container}'.format(
veth=random_veth,
container=name
))
__salt__['file.remove']('/var/run/netns/{0}'.format(name))
if bridge is not None:
__salt__['bridge.addif'](bridge, random_veth) | python | def add_veth(name, interface_name, bridge=None, path=None):
'''
Add a veth to a container.
Note : this function doesn't update the container config, just add the interface at runtime
name
Name of the container
interface_name
Name of the interface in the container
bridge
Name of the bridge to attach the interface to (facultative)
CLI Examples:
.. code-block:: bash
salt '*' lxc.add_veth container_name eth1 br1
salt '*' lxc.add_veth container_name eth1
'''
# Get container init PID
pid = get_pid(name, path=path)
# Generate a ramdom string for veth and ensure that is isn't present on the system
while True:
random_veth = 'veth'+''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(6))
if random_veth not in __salt__['network.interfaces']().keys():
break
# Check prerequisites
if not __salt__['file.directory_exists']('/var/run/'):
raise CommandExecutionError('Directory /var/run required for lxc.add_veth doesn\'t exists')
if not __salt__['file.file_exists']('/proc/{0}/ns/net'.format(pid)):
raise CommandExecutionError('Proc file for container {0} network namespace doesn\'t exists'.format(name))
if not __salt__['file.directory_exists']('/var/run/netns'):
__salt__['file.mkdir']('/var/run/netns')
# Ensure that the symlink is up to date (change on container restart)
if __salt__['file.is_link']('/var/run/netns/{0}'.format(name)):
__salt__['file.remove']('/var/run/netns/{0}'.format(name))
__salt__['file.symlink']('/proc/{0}/ns/net'.format(pid), '/var/run/netns/{0}'.format(name))
# Ensure that interface doesn't exists
interface_exists = 0 == __salt__['cmd.retcode']('ip netns exec {netns} ip address list {interface}'.format(
netns=name,
interface=interface_name
))
if interface_exists:
raise CommandExecutionError('Interface {interface} already exists in {container}'.format(
interface=interface_name,
container=name
))
# Create veth and bring it up
if __salt__['cmd.retcode']('ip link add name {veth} type veth peer name {veth}_c'.format(veth=random_veth)) != 0:
raise CommandExecutionError('Error while creating the veth pair {0}'.format(random_veth))
if __salt__['cmd.retcode']('ip link set dev {0} up'.format(random_veth)) != 0:
raise CommandExecutionError('Error while bringing up host-side veth {0}'.format(random_veth))
# Attach it to the container
attached = 0 == __salt__['cmd.retcode']('ip link set dev {veth}_c netns {container} name {interface_name}'.format(
veth=random_veth,
container=name,
interface_name=interface_name
))
if not attached:
raise CommandExecutionError('Error while attaching the veth {veth} to container {container}'.format(
veth=random_veth,
container=name
))
__salt__['file.remove']('/var/run/netns/{0}'.format(name))
if bridge is not None:
__salt__['bridge.addif'](bridge, random_veth) | [
"def",
"add_veth",
"(",
"name",
",",
"interface_name",
",",
"bridge",
"=",
"None",
",",
"path",
"=",
"None",
")",
":",
"# Get container init PID",
"pid",
"=",
"get_pid",
"(",
"name",
",",
"path",
"=",
"path",
")",
"# Generate a ramdom string for veth and ensure ... | Add a veth to a container.
Note : this function doesn't update the container config, just add the interface at runtime
name
Name of the container
interface_name
Name of the interface in the container
bridge
Name of the bridge to attach the interface to (facultative)
CLI Examples:
.. code-block:: bash
salt '*' lxc.add_veth container_name eth1 br1
salt '*' lxc.add_veth container_name eth1 | [
"Add",
"a",
"veth",
"to",
"a",
"container",
".",
"Note",
":",
"this",
"function",
"doesn",
"t",
"update",
"the",
"container",
"config",
"just",
"add",
"the",
"interface",
"at",
"runtime"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/lxc.py#L4699-L4778 | train |
saltstack/salt | salt/modules/lxc.py | _LXCConfig._filter_data | def _filter_data(self, pattern):
'''
Removes parameters which match the pattern from the config data
'''
removed = []
filtered = []
for param in self.data:
if not param[0].startswith(pattern):
filtered.append(param)
else:
removed.append(param)
self.data = filtered
return removed | python | def _filter_data(self, pattern):
'''
Removes parameters which match the pattern from the config data
'''
removed = []
filtered = []
for param in self.data:
if not param[0].startswith(pattern):
filtered.append(param)
else:
removed.append(param)
self.data = filtered
return removed | [
"def",
"_filter_data",
"(",
"self",
",",
"pattern",
")",
":",
"removed",
"=",
"[",
"]",
"filtered",
"=",
"[",
"]",
"for",
"param",
"in",
"self",
".",
"data",
":",
"if",
"not",
"param",
"[",
"0",
"]",
".",
"startswith",
"(",
"pattern",
")",
":",
"... | Removes parameters which match the pattern from the config data | [
"Removes",
"parameters",
"which",
"match",
"the",
"pattern",
"from",
"the",
"config",
"data"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/lxc.py#L1055-L1067 | train |
saltstack/salt | salt/engines/script.py | _get_serializer | def _get_serializer(output):
'''
Helper to return known serializer based on
pass output argument
'''
serializers = salt.loader.serializers(__opts__)
try:
return getattr(serializers, output)
except AttributeError:
raise CommandExecutionError(
"Unknown serializer '{0}' found for output option".format(output)
) | python | def _get_serializer(output):
'''
Helper to return known serializer based on
pass output argument
'''
serializers = salt.loader.serializers(__opts__)
try:
return getattr(serializers, output)
except AttributeError:
raise CommandExecutionError(
"Unknown serializer '{0}' found for output option".format(output)
) | [
"def",
"_get_serializer",
"(",
"output",
")",
":",
"serializers",
"=",
"salt",
".",
"loader",
".",
"serializers",
"(",
"__opts__",
")",
"try",
":",
"return",
"getattr",
"(",
"serializers",
",",
"output",
")",
"except",
"AttributeError",
":",
"raise",
"Comman... | Helper to return known serializer based on
pass output argument | [
"Helper",
"to",
"return",
"known",
"serializer",
"based",
"on",
"pass",
"output",
"argument"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/script.py#L51-L62 | train |
saltstack/salt | salt/engines/script.py | start | def start(cmd, output='json', interval=1):
'''
Parse stdout of a command and generate an event
The script engine will scrap stdout of the
given script and generate an event based on the
presence of the 'tag' key and it's value.
If there is a data obj available, that will also
be fired along with the tag.
Example:
Given the following json output from a script:
{ "tag" : "lots/of/tacos",
"data" : { "toppings" : "cilantro" }
}
This will fire the event 'lots/of/tacos'
on the event bus with the data obj as is.
:param cmd: The command to execute
:param output: How to deserialize stdout of the script
:param interval: How often to execute the script.
'''
try:
cmd = shlex.split(cmd)
except AttributeError:
cmd = shlex.split(six.text_type(cmd))
log.debug("script engine using command %s", cmd)
serializer = _get_serializer(output)
if __opts__.get('__role') == 'master':
fire_master = salt.utils.event.get_master_event(
__opts__,
__opts__['sock_dir']).fire_event
else:
fire_master = __salt__['event.send']
while True:
try:
proc = subprocess.Popen(cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
log.debug("Starting script with pid %d", proc.pid)
for raw_event in _read_stdout(proc):
log.debug(raw_event)
event = serializer.deserialize(raw_event)
tag = event.get('tag', None)
data = event.get('data', {})
if data and 'id' not in data:
data['id'] = __opts__['id']
if tag:
log.info("script engine firing event with tag %s", tag)
fire_master(tag=tag, data=data)
log.debug("Closing script with pid %d", proc.pid)
proc.stdout.close()
rc = proc.wait()
if rc:
raise subprocess.CalledProcessError(rc, cmd)
except subprocess.CalledProcessError as e:
log.error(e)
finally:
if proc.poll is None:
proc.terminate()
time.sleep(interval) | python | def start(cmd, output='json', interval=1):
'''
Parse stdout of a command and generate an event
The script engine will scrap stdout of the
given script and generate an event based on the
presence of the 'tag' key and it's value.
If there is a data obj available, that will also
be fired along with the tag.
Example:
Given the following json output from a script:
{ "tag" : "lots/of/tacos",
"data" : { "toppings" : "cilantro" }
}
This will fire the event 'lots/of/tacos'
on the event bus with the data obj as is.
:param cmd: The command to execute
:param output: How to deserialize stdout of the script
:param interval: How often to execute the script.
'''
try:
cmd = shlex.split(cmd)
except AttributeError:
cmd = shlex.split(six.text_type(cmd))
log.debug("script engine using command %s", cmd)
serializer = _get_serializer(output)
if __opts__.get('__role') == 'master':
fire_master = salt.utils.event.get_master_event(
__opts__,
__opts__['sock_dir']).fire_event
else:
fire_master = __salt__['event.send']
while True:
try:
proc = subprocess.Popen(cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
log.debug("Starting script with pid %d", proc.pid)
for raw_event in _read_stdout(proc):
log.debug(raw_event)
event = serializer.deserialize(raw_event)
tag = event.get('tag', None)
data = event.get('data', {})
if data and 'id' not in data:
data['id'] = __opts__['id']
if tag:
log.info("script engine firing event with tag %s", tag)
fire_master(tag=tag, data=data)
log.debug("Closing script with pid %d", proc.pid)
proc.stdout.close()
rc = proc.wait()
if rc:
raise subprocess.CalledProcessError(rc, cmd)
except subprocess.CalledProcessError as e:
log.error(e)
finally:
if proc.poll is None:
proc.terminate()
time.sleep(interval) | [
"def",
"start",
"(",
"cmd",
",",
"output",
"=",
"'json'",
",",
"interval",
"=",
"1",
")",
":",
"try",
":",
"cmd",
"=",
"shlex",
".",
"split",
"(",
"cmd",
")",
"except",
"AttributeError",
":",
"cmd",
"=",
"shlex",
".",
"split",
"(",
"six",
".",
"t... | Parse stdout of a command and generate an event
The script engine will scrap stdout of the
given script and generate an event based on the
presence of the 'tag' key and it's value.
If there is a data obj available, that will also
be fired along with the tag.
Example:
Given the following json output from a script:
{ "tag" : "lots/of/tacos",
"data" : { "toppings" : "cilantro" }
}
This will fire the event 'lots/of/tacos'
on the event bus with the data obj as is.
:param cmd: The command to execute
:param output: How to deserialize stdout of the script
:param interval: How often to execute the script. | [
"Parse",
"stdout",
"of",
"a",
"command",
"and",
"generate",
"an",
"event"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/script.py#L65-L141 | train |
saltstack/salt | salt/modules/bluez_bluetooth.py | version | def version():
'''
Return Bluez version from bluetoothd -v
CLI Example:
.. code-block:: bash
salt '*' bluetoothd.version
'''
cmd = 'bluetoothctl -v'
out = __salt__['cmd.run'](cmd).splitlines()
bluez_version = out[0]
pybluez_version = '<= 0.18 (Unknown, but installed)'
try:
pybluez_version = bluetooth.__version__
except Exception as exc:
pass
return {'Bluez': bluez_version, 'PyBluez': pybluez_version} | python | def version():
'''
Return Bluez version from bluetoothd -v
CLI Example:
.. code-block:: bash
salt '*' bluetoothd.version
'''
cmd = 'bluetoothctl -v'
out = __salt__['cmd.run'](cmd).splitlines()
bluez_version = out[0]
pybluez_version = '<= 0.18 (Unknown, but installed)'
try:
pybluez_version = bluetooth.__version__
except Exception as exc:
pass
return {'Bluez': bluez_version, 'PyBluez': pybluez_version} | [
"def",
"version",
"(",
")",
":",
"cmd",
"=",
"'bluetoothctl -v'",
"out",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"cmd",
")",
".",
"splitlines",
"(",
")",
"bluez_version",
"=",
"out",
"[",
"0",
"]",
"pybluez_version",
"=",
"'<= 0.18 (Unknown, but install... | Return Bluez version from bluetoothd -v
CLI Example:
.. code-block:: bash
salt '*' bluetoothd.version | [
"Return",
"Bluez",
"version",
"from",
"bluetoothd",
"-",
"v"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bluez_bluetooth.py#L48-L66 | train |
saltstack/salt | salt/modules/bluez_bluetooth.py | address_ | def address_():
'''
Get the many addresses of the Bluetooth adapter
CLI Example:
.. code-block:: bash
salt '*' bluetooth.address
'''
ret = {}
cmd = 'hciconfig'
out = __salt__['cmd.run'](cmd).splitlines()
dev = ''
for line in out:
if line.startswith('hci'):
comps = line.split(':')
dev = comps[0]
ret[dev] = {
'device': dev,
'path': '/sys/class/bluetooth/{0}'.format(dev),
}
if 'BD Address' in line:
comps = line.split()
ret[dev]['address'] = comps[2]
if 'DOWN' in line:
ret[dev]['power'] = 'off'
if 'UP RUNNING' in line:
ret[dev]['power'] = 'on'
return ret | python | def address_():
'''
Get the many addresses of the Bluetooth adapter
CLI Example:
.. code-block:: bash
salt '*' bluetooth.address
'''
ret = {}
cmd = 'hciconfig'
out = __salt__['cmd.run'](cmd).splitlines()
dev = ''
for line in out:
if line.startswith('hci'):
comps = line.split(':')
dev = comps[0]
ret[dev] = {
'device': dev,
'path': '/sys/class/bluetooth/{0}'.format(dev),
}
if 'BD Address' in line:
comps = line.split()
ret[dev]['address'] = comps[2]
if 'DOWN' in line:
ret[dev]['power'] = 'off'
if 'UP RUNNING' in line:
ret[dev]['power'] = 'on'
return ret | [
"def",
"address_",
"(",
")",
":",
"ret",
"=",
"{",
"}",
"cmd",
"=",
"'hciconfig'",
"out",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"cmd",
")",
".",
"splitlines",
"(",
")",
"dev",
"=",
"''",
"for",
"line",
"in",
"out",
":",
"if",
"line",
".",
... | Get the many addresses of the Bluetooth adapter
CLI Example:
.. code-block:: bash
salt '*' bluetooth.address | [
"Get",
"the",
"many",
"addresses",
"of",
"the",
"Bluetooth",
"adapter"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bluez_bluetooth.py#L69-L98 | train |
saltstack/salt | salt/modules/bluez_bluetooth.py | power | def power(dev, mode):
'''
Power a bluetooth device on or off
CLI Examples:
.. code-block:: bash
salt '*' bluetooth.power hci0 on
salt '*' bluetooth.power hci0 off
'''
if dev not in address_():
raise CommandExecutionError('Invalid dev passed to bluetooth.power')
if mode == 'on' or mode is True:
state = 'up'
mode = 'on'
else:
state = 'down'
mode = 'off'
cmd = 'hciconfig {0} {1}'.format(dev, state)
__salt__['cmd.run'](cmd).splitlines()
info = address_()
if info[dev]['power'] == mode:
return True
return False | python | def power(dev, mode):
'''
Power a bluetooth device on or off
CLI Examples:
.. code-block:: bash
salt '*' bluetooth.power hci0 on
salt '*' bluetooth.power hci0 off
'''
if dev not in address_():
raise CommandExecutionError('Invalid dev passed to bluetooth.power')
if mode == 'on' or mode is True:
state = 'up'
mode = 'on'
else:
state = 'down'
mode = 'off'
cmd = 'hciconfig {0} {1}'.format(dev, state)
__salt__['cmd.run'](cmd).splitlines()
info = address_()
if info[dev]['power'] == mode:
return True
return False | [
"def",
"power",
"(",
"dev",
",",
"mode",
")",
":",
"if",
"dev",
"not",
"in",
"address_",
"(",
")",
":",
"raise",
"CommandExecutionError",
"(",
"'Invalid dev passed to bluetooth.power'",
")",
"if",
"mode",
"==",
"'on'",
"or",
"mode",
"is",
"True",
":",
"sta... | Power a bluetooth device on or off
CLI Examples:
.. code-block:: bash
salt '*' bluetooth.power hci0 on
salt '*' bluetooth.power hci0 off | [
"Power",
"a",
"bluetooth",
"device",
"on",
"or",
"off"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bluez_bluetooth.py#L101-L126 | train |
saltstack/salt | salt/modules/bluez_bluetooth.py | discoverable | def discoverable(dev):
'''
Enable this bluetooth device to be discoverable.
CLI Example:
.. code-block:: bash
salt '*' bluetooth.discoverable hci0
'''
if dev not in address_():
raise CommandExecutionError(
'Invalid dev passed to bluetooth.discoverable'
)
cmd = 'hciconfig {0} iscan'.format(dev)
__salt__['cmd.run'](cmd).splitlines()
cmd = 'hciconfig {0}'.format(dev)
out = __salt__['cmd.run'](cmd)
if 'UP RUNNING ISCAN' in out:
return True
return False | python | def discoverable(dev):
'''
Enable this bluetooth device to be discoverable.
CLI Example:
.. code-block:: bash
salt '*' bluetooth.discoverable hci0
'''
if dev not in address_():
raise CommandExecutionError(
'Invalid dev passed to bluetooth.discoverable'
)
cmd = 'hciconfig {0} iscan'.format(dev)
__salt__['cmd.run'](cmd).splitlines()
cmd = 'hciconfig {0}'.format(dev)
out = __salt__['cmd.run'](cmd)
if 'UP RUNNING ISCAN' in out:
return True
return False | [
"def",
"discoverable",
"(",
"dev",
")",
":",
"if",
"dev",
"not",
"in",
"address_",
"(",
")",
":",
"raise",
"CommandExecutionError",
"(",
"'Invalid dev passed to bluetooth.discoverable'",
")",
"cmd",
"=",
"'hciconfig {0} iscan'",
".",
"format",
"(",
"dev",
")",
"... | Enable this bluetooth device to be discoverable.
CLI Example:
.. code-block:: bash
salt '*' bluetooth.discoverable hci0 | [
"Enable",
"this",
"bluetooth",
"device",
"to",
"be",
"discoverable",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bluez_bluetooth.py#L129-L150 | train |
saltstack/salt | salt/modules/bluez_bluetooth.py | scan | def scan():
'''
Scan for bluetooth devices in the area
CLI Example:
.. code-block:: bash
salt '*' bluetooth.scan
'''
ret = []
devices = bluetooth.discover_devices(lookup_names=True)
for device in devices:
ret.append({device[0]: device[1]})
return ret | python | def scan():
'''
Scan for bluetooth devices in the area
CLI Example:
.. code-block:: bash
salt '*' bluetooth.scan
'''
ret = []
devices = bluetooth.discover_devices(lookup_names=True)
for device in devices:
ret.append({device[0]: device[1]})
return ret | [
"def",
"scan",
"(",
")",
":",
"ret",
"=",
"[",
"]",
"devices",
"=",
"bluetooth",
".",
"discover_devices",
"(",
"lookup_names",
"=",
"True",
")",
"for",
"device",
"in",
"devices",
":",
"ret",
".",
"append",
"(",
"{",
"device",
"[",
"0",
"]",
":",
"d... | Scan for bluetooth devices in the area
CLI Example:
.. code-block:: bash
salt '*' bluetooth.scan | [
"Scan",
"for",
"bluetooth",
"devices",
"in",
"the",
"area"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bluez_bluetooth.py#L175-L189 | train |
saltstack/salt | salt/modules/bluez_bluetooth.py | block | def block(bdaddr):
'''
Block a specific bluetooth device by BD Address
CLI Example:
.. code-block:: bash
salt '*' bluetooth.block DE:AD:BE:EF:CA:FE
'''
if not salt.utils.validate.net.mac(bdaddr):
raise CommandExecutionError(
'Invalid BD address passed to bluetooth.block'
)
cmd = 'hciconfig {0} block'.format(bdaddr)
__salt__['cmd.run'](cmd).splitlines() | python | def block(bdaddr):
'''
Block a specific bluetooth device by BD Address
CLI Example:
.. code-block:: bash
salt '*' bluetooth.block DE:AD:BE:EF:CA:FE
'''
if not salt.utils.validate.net.mac(bdaddr):
raise CommandExecutionError(
'Invalid BD address passed to bluetooth.block'
)
cmd = 'hciconfig {0} block'.format(bdaddr)
__salt__['cmd.run'](cmd).splitlines() | [
"def",
"block",
"(",
"bdaddr",
")",
":",
"if",
"not",
"salt",
".",
"utils",
".",
"validate",
".",
"net",
".",
"mac",
"(",
"bdaddr",
")",
":",
"raise",
"CommandExecutionError",
"(",
"'Invalid BD address passed to bluetooth.block'",
")",
"cmd",
"=",
"'hciconfig ... | Block a specific bluetooth device by BD Address
CLI Example:
.. code-block:: bash
salt '*' bluetooth.block DE:AD:BE:EF:CA:FE | [
"Block",
"a",
"specific",
"bluetooth",
"device",
"by",
"BD",
"Address"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bluez_bluetooth.py#L192-L208 | train |
saltstack/salt | salt/modules/bluez_bluetooth.py | pair | def pair(address, key):
'''
Pair the bluetooth adapter with a device
CLI Example:
.. code-block:: bash
salt '*' bluetooth.pair DE:AD:BE:EF:CA:FE 1234
Where DE:AD:BE:EF:CA:FE is the address of the device to pair with, and 1234
is the passphrase.
TODO: This function is currently broken, as the bluez-simple-agent program
no longer ships with BlueZ >= 5.0. It needs to be refactored.
'''
if not salt.utils.validate.net.mac(address):
raise CommandExecutionError(
'Invalid BD address passed to bluetooth.pair'
)
try:
int(key)
except Exception:
raise CommandExecutionError(
'bluetooth.pair requires a numerical key to be used'
)
addy = address_()
cmd = 'echo {0} | bluez-simple-agent {1} {2}'.format(
_cmd_quote(addy['device']), _cmd_quote(address), _cmd_quote(key)
)
out = __salt__['cmd.run'](cmd, python_shell=True).splitlines()
return out | python | def pair(address, key):
'''
Pair the bluetooth adapter with a device
CLI Example:
.. code-block:: bash
salt '*' bluetooth.pair DE:AD:BE:EF:CA:FE 1234
Where DE:AD:BE:EF:CA:FE is the address of the device to pair with, and 1234
is the passphrase.
TODO: This function is currently broken, as the bluez-simple-agent program
no longer ships with BlueZ >= 5.0. It needs to be refactored.
'''
if not salt.utils.validate.net.mac(address):
raise CommandExecutionError(
'Invalid BD address passed to bluetooth.pair'
)
try:
int(key)
except Exception:
raise CommandExecutionError(
'bluetooth.pair requires a numerical key to be used'
)
addy = address_()
cmd = 'echo {0} | bluez-simple-agent {1} {2}'.format(
_cmd_quote(addy['device']), _cmd_quote(address), _cmd_quote(key)
)
out = __salt__['cmd.run'](cmd, python_shell=True).splitlines()
return out | [
"def",
"pair",
"(",
"address",
",",
"key",
")",
":",
"if",
"not",
"salt",
".",
"utils",
".",
"validate",
".",
"net",
".",
"mac",
"(",
"address",
")",
":",
"raise",
"CommandExecutionError",
"(",
"'Invalid BD address passed to bluetooth.pair'",
")",
"try",
":"... | Pair the bluetooth adapter with a device
CLI Example:
.. code-block:: bash
salt '*' bluetooth.pair DE:AD:BE:EF:CA:FE 1234
Where DE:AD:BE:EF:CA:FE is the address of the device to pair with, and 1234
is the passphrase.
TODO: This function is currently broken, as the bluez-simple-agent program
no longer ships with BlueZ >= 5.0. It needs to be refactored. | [
"Pair",
"the",
"bluetooth",
"adapter",
"with",
"a",
"device"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bluez_bluetooth.py#L230-L263 | train |
saltstack/salt | salt/modules/bluez_bluetooth.py | unpair | def unpair(address):
'''
Unpair the bluetooth adapter from a device
CLI Example:
.. code-block:: bash
salt '*' bluetooth.unpair DE:AD:BE:EF:CA:FE
Where DE:AD:BE:EF:CA:FE is the address of the device to unpair.
TODO: This function is currently broken, as the bluez-simple-agent program
no longer ships with BlueZ >= 5.0. It needs to be refactored.
'''
if not salt.utils.validate.net.mac(address):
raise CommandExecutionError(
'Invalid BD address passed to bluetooth.unpair'
)
cmd = 'bluez-test-device remove {0}'.format(address)
out = __salt__['cmd.run'](cmd).splitlines()
return out | python | def unpair(address):
'''
Unpair the bluetooth adapter from a device
CLI Example:
.. code-block:: bash
salt '*' bluetooth.unpair DE:AD:BE:EF:CA:FE
Where DE:AD:BE:EF:CA:FE is the address of the device to unpair.
TODO: This function is currently broken, as the bluez-simple-agent program
no longer ships with BlueZ >= 5.0. It needs to be refactored.
'''
if not salt.utils.validate.net.mac(address):
raise CommandExecutionError(
'Invalid BD address passed to bluetooth.unpair'
)
cmd = 'bluez-test-device remove {0}'.format(address)
out = __salt__['cmd.run'](cmd).splitlines()
return out | [
"def",
"unpair",
"(",
"address",
")",
":",
"if",
"not",
"salt",
".",
"utils",
".",
"validate",
".",
"net",
".",
"mac",
"(",
"address",
")",
":",
"raise",
"CommandExecutionError",
"(",
"'Invalid BD address passed to bluetooth.unpair'",
")",
"cmd",
"=",
"'bluez-... | Unpair the bluetooth adapter from a device
CLI Example:
.. code-block:: bash
salt '*' bluetooth.unpair DE:AD:BE:EF:CA:FE
Where DE:AD:BE:EF:CA:FE is the address of the device to unpair.
TODO: This function is currently broken, as the bluez-simple-agent program
no longer ships with BlueZ >= 5.0. It needs to be refactored. | [
"Unpair",
"the",
"bluetooth",
"adapter",
"from",
"a",
"device"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bluez_bluetooth.py#L266-L288 | train |
saltstack/salt | salt/modules/msteams.py | post_card | def post_card(message,
hook_url=None,
title=None,
theme_color=None):
'''
Send a message to an MS Teams channel.
:param message: The message to send to the MS Teams channel.
:param hook_url: The Teams webhook URL, if not specified in the configuration.
:param title: Optional title for the posted card
:param theme_color: Optional hex color highlight for the posted card
:return: Boolean if message was sent successfully.
CLI Example:
.. code-block:: bash
salt '*' msteams.post_card message="Build is done"
'''
if not hook_url:
hook_url = _get_hook_url()
if not message:
log.error('message is a required option.')
payload = {
"text": message,
"title": title,
"themeColor": theme_color
}
result = salt.utils.http.query(hook_url,
method='POST',
data=salt.utils.json.dumps(payload),
status=True)
if result['status'] <= 201:
return True
else:
return {
'res': False,
'message': result.get('body', result['status'])
} | python | def post_card(message,
hook_url=None,
title=None,
theme_color=None):
'''
Send a message to an MS Teams channel.
:param message: The message to send to the MS Teams channel.
:param hook_url: The Teams webhook URL, if not specified in the configuration.
:param title: Optional title for the posted card
:param theme_color: Optional hex color highlight for the posted card
:return: Boolean if message was sent successfully.
CLI Example:
.. code-block:: bash
salt '*' msteams.post_card message="Build is done"
'''
if not hook_url:
hook_url = _get_hook_url()
if not message:
log.error('message is a required option.')
payload = {
"text": message,
"title": title,
"themeColor": theme_color
}
result = salt.utils.http.query(hook_url,
method='POST',
data=salt.utils.json.dumps(payload),
status=True)
if result['status'] <= 201:
return True
else:
return {
'res': False,
'message': result.get('body', result['status'])
} | [
"def",
"post_card",
"(",
"message",
",",
"hook_url",
"=",
"None",
",",
"title",
"=",
"None",
",",
"theme_color",
"=",
"None",
")",
":",
"if",
"not",
"hook_url",
":",
"hook_url",
"=",
"_get_hook_url",
"(",
")",
"if",
"not",
"message",
":",
"log",
".",
... | Send a message to an MS Teams channel.
:param message: The message to send to the MS Teams channel.
:param hook_url: The Teams webhook URL, if not specified in the configuration.
:param title: Optional title for the posted card
:param theme_color: Optional hex color highlight for the posted card
:return: Boolean if message was sent successfully.
CLI Example:
.. code-block:: bash
salt '*' msteams.post_card message="Build is done" | [
"Send",
"a",
"message",
"to",
"an",
"MS",
"Teams",
"channel",
".",
":",
"param",
"message",
":",
"The",
"message",
"to",
"send",
"to",
"the",
"MS",
"Teams",
"channel",
".",
":",
"param",
"hook_url",
":",
"The",
"Teams",
"webhook",
"URL",
"if",
"not",
... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/msteams.py#L54-L96 | train |
saltstack/salt | salt/beacons/ps.py | beacon | def beacon(config):
'''
Scan for processes and fire events
Example Config
.. code-block:: yaml
beacons:
ps:
- processes:
salt-master: running
mysql: stopped
The config above sets up beacons to check that
processes are running or stopped.
'''
ret = []
procs = []
for proc in psutil.process_iter():
_name = proc.name()
if _name not in procs:
procs.append(_name)
_config = {}
list(map(_config.update, config))
for process in _config.get('processes', {}):
ret_dict = {}
if _config['processes'][process] == 'running':
if process in procs:
ret_dict[process] = 'Running'
ret.append(ret_dict)
elif _config['processes'][process] == 'stopped':
if process not in procs:
ret_dict[process] = 'Stopped'
ret.append(ret_dict)
else:
if process not in procs:
ret_dict[process] = False
ret.append(ret_dict)
return ret | python | def beacon(config):
'''
Scan for processes and fire events
Example Config
.. code-block:: yaml
beacons:
ps:
- processes:
salt-master: running
mysql: stopped
The config above sets up beacons to check that
processes are running or stopped.
'''
ret = []
procs = []
for proc in psutil.process_iter():
_name = proc.name()
if _name not in procs:
procs.append(_name)
_config = {}
list(map(_config.update, config))
for process in _config.get('processes', {}):
ret_dict = {}
if _config['processes'][process] == 'running':
if process in procs:
ret_dict[process] = 'Running'
ret.append(ret_dict)
elif _config['processes'][process] == 'stopped':
if process not in procs:
ret_dict[process] = 'Stopped'
ret.append(ret_dict)
else:
if process not in procs:
ret_dict[process] = False
ret.append(ret_dict)
return ret | [
"def",
"beacon",
"(",
"config",
")",
":",
"ret",
"=",
"[",
"]",
"procs",
"=",
"[",
"]",
"for",
"proc",
"in",
"psutil",
".",
"process_iter",
"(",
")",
":",
"_name",
"=",
"proc",
".",
"name",
"(",
")",
"if",
"_name",
"not",
"in",
"procs",
":",
"p... | Scan for processes and fire events
Example Config
.. code-block:: yaml
beacons:
ps:
- processes:
salt-master: running
mysql: stopped
The config above sets up beacons to check that
processes are running or stopped. | [
"Scan",
"for",
"processes",
"and",
"fire",
"events"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/beacons/ps.py#L53-L94 | train |
saltstack/salt | salt/cloud/clouds/vagrant.py | list_nodes_full | def list_nodes_full(call=None):
'''
List the nodes, ask all 'vagrant' minions, return dict of grains (enhanced).
CLI Example:
.. code-block:: bash
salt-call -F
'''
ret = _list_nodes(call)
for key, grains in ret.items(): # clean up some hyperverbose grains -- everything is too much
try:
del grains['cpu_flags'], grains['disks'], grains['pythonpath'], grains['dns'], grains['gpus']
except KeyError:
pass # ignore absence of things we are eliminating
except TypeError:
del ret[key] # eliminate all reference to unexpected (None) values.
reqs = _build_required_items(ret)
for name in ret:
ret[name].update(reqs[name])
return ret | python | def list_nodes_full(call=None):
'''
List the nodes, ask all 'vagrant' minions, return dict of grains (enhanced).
CLI Example:
.. code-block:: bash
salt-call -F
'''
ret = _list_nodes(call)
for key, grains in ret.items(): # clean up some hyperverbose grains -- everything is too much
try:
del grains['cpu_flags'], grains['disks'], grains['pythonpath'], grains['dns'], grains['gpus']
except KeyError:
pass # ignore absence of things we are eliminating
except TypeError:
del ret[key] # eliminate all reference to unexpected (None) values.
reqs = _build_required_items(ret)
for name in ret:
ret[name].update(reqs[name])
return ret | [
"def",
"list_nodes_full",
"(",
"call",
"=",
"None",
")",
":",
"ret",
"=",
"_list_nodes",
"(",
"call",
")",
"for",
"key",
",",
"grains",
"in",
"ret",
".",
"items",
"(",
")",
":",
"# clean up some hyperverbose grains -- everything is too much",
"try",
":",
"del"... | List the nodes, ask all 'vagrant' minions, return dict of grains (enhanced).
CLI Example:
.. code-block:: bash
salt-call -F | [
"List",
"the",
"nodes",
"ask",
"all",
"vagrant",
"minions",
"return",
"dict",
"of",
"grains",
"(",
"enhanced",
")",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/vagrant.py#L125-L148 | train |
saltstack/salt | salt/cloud/clouds/vagrant.py | _list_nodes | def _list_nodes(call=None):
'''
List the nodes, ask all 'vagrant' minions, return dict of grains.
'''
local = salt.client.LocalClient()
ret = local.cmd('salt-cloud:driver:vagrant', 'grains.items', '', tgt_type='grain')
return ret | python | def _list_nodes(call=None):
'''
List the nodes, ask all 'vagrant' minions, return dict of grains.
'''
local = salt.client.LocalClient()
ret = local.cmd('salt-cloud:driver:vagrant', 'grains.items', '', tgt_type='grain')
return ret | [
"def",
"_list_nodes",
"(",
"call",
"=",
"None",
")",
":",
"local",
"=",
"salt",
".",
"client",
".",
"LocalClient",
"(",
")",
"ret",
"=",
"local",
".",
"cmd",
"(",
"'salt-cloud:driver:vagrant'",
",",
"'grains.items'",
",",
"''",
",",
"tgt_type",
"=",
"'gr... | List the nodes, ask all 'vagrant' minions, return dict of grains. | [
"List",
"the",
"nodes",
"ask",
"all",
"vagrant",
"minions",
"return",
"dict",
"of",
"grains",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/vagrant.py#L151-L157 | train |
saltstack/salt | salt/cloud/clouds/vagrant.py | create | def create(vm_):
'''
Provision a single machine
CLI Example:
.. code-block:: bash
salt-cloud -p my_profile new_node_1
'''
name = vm_['name']
machine = config.get_cloud_config_value(
'machine', vm_, __opts__, default='')
vm_['machine'] = machine
host = config.get_cloud_config_value(
'host', vm_, __opts__, default=NotImplemented)
vm_['cwd'] = config.get_cloud_config_value(
'cwd', vm_, __opts__, default='/')
vm_['runas'] = config.get_cloud_config_value(
'vagrant_runas', vm_, __opts__, default=os.getenv('SUDO_USER'))
vm_['timeout'] = config.get_cloud_config_value(
'vagrant_up_timeout', vm_, __opts__, default=300)
vm_['vagrant_provider'] = config.get_cloud_config_value(
'vagrant_provider', vm_, __opts__, default='')
vm_['grains'] = {'salt-cloud:vagrant': {'host': host, 'machine': machine}}
log.info('sending \'vagrant.init %s machine=%s\' command to %s', name, machine, host)
local = salt.client.LocalClient()
ret = local.cmd(host, 'vagrant.init', [name], kwarg={'vm': vm_, 'start': True})
log.info('response ==> %s', ret[host])
network_mask = config.get_cloud_config_value(
'network_mask', vm_, __opts__, default='')
if 'ssh_host' not in vm_:
ret = local.cmd(host,
'vagrant.get_ssh_config',
[name],
kwarg={'network_mask': network_mask,
'get_private_key': True})[host]
with tempfile.NamedTemporaryFile() as pks:
if 'private_key' not in vm_ and ret and ret.get('private_key', False):
pks.write(ret['private_key'])
pks.flush()
log.debug('wrote private key to %s', pks.name)
vm_['key_filename'] = pks.name
if 'ssh_host' not in vm_:
try:
vm_.setdefault('ssh_username', ret['ssh_username'])
if ret.get('ip_address'):
vm_['ssh_host'] = ret['ip_address']
else: # if probe failed or not used, use Vagrant's reported ssh info
vm_['ssh_host'] = ret['ssh_host']
vm_.setdefault('ssh_port', ret['ssh_port'])
except (KeyError, TypeError):
raise SaltInvocationError(
'Insufficient SSH addressing information for {}'.format(name))
log.info('Provisioning machine %s as node %s using ssh %s',
machine, name, vm_['ssh_host'])
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
return ret | python | def create(vm_):
'''
Provision a single machine
CLI Example:
.. code-block:: bash
salt-cloud -p my_profile new_node_1
'''
name = vm_['name']
machine = config.get_cloud_config_value(
'machine', vm_, __opts__, default='')
vm_['machine'] = machine
host = config.get_cloud_config_value(
'host', vm_, __opts__, default=NotImplemented)
vm_['cwd'] = config.get_cloud_config_value(
'cwd', vm_, __opts__, default='/')
vm_['runas'] = config.get_cloud_config_value(
'vagrant_runas', vm_, __opts__, default=os.getenv('SUDO_USER'))
vm_['timeout'] = config.get_cloud_config_value(
'vagrant_up_timeout', vm_, __opts__, default=300)
vm_['vagrant_provider'] = config.get_cloud_config_value(
'vagrant_provider', vm_, __opts__, default='')
vm_['grains'] = {'salt-cloud:vagrant': {'host': host, 'machine': machine}}
log.info('sending \'vagrant.init %s machine=%s\' command to %s', name, machine, host)
local = salt.client.LocalClient()
ret = local.cmd(host, 'vagrant.init', [name], kwarg={'vm': vm_, 'start': True})
log.info('response ==> %s', ret[host])
network_mask = config.get_cloud_config_value(
'network_mask', vm_, __opts__, default='')
if 'ssh_host' not in vm_:
ret = local.cmd(host,
'vagrant.get_ssh_config',
[name],
kwarg={'network_mask': network_mask,
'get_private_key': True})[host]
with tempfile.NamedTemporaryFile() as pks:
if 'private_key' not in vm_ and ret and ret.get('private_key', False):
pks.write(ret['private_key'])
pks.flush()
log.debug('wrote private key to %s', pks.name)
vm_['key_filename'] = pks.name
if 'ssh_host' not in vm_:
try:
vm_.setdefault('ssh_username', ret['ssh_username'])
if ret.get('ip_address'):
vm_['ssh_host'] = ret['ip_address']
else: # if probe failed or not used, use Vagrant's reported ssh info
vm_['ssh_host'] = ret['ssh_host']
vm_.setdefault('ssh_port', ret['ssh_port'])
except (KeyError, TypeError):
raise SaltInvocationError(
'Insufficient SSH addressing information for {}'.format(name))
log.info('Provisioning machine %s as node %s using ssh %s',
machine, name, vm_['ssh_host'])
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
return ret | [
"def",
"create",
"(",
"vm_",
")",
":",
"name",
"=",
"vm_",
"[",
"'name'",
"]",
"machine",
"=",
"config",
".",
"get_cloud_config_value",
"(",
"'machine'",
",",
"vm_",
",",
"__opts__",
",",
"default",
"=",
"''",
")",
"vm_",
"[",
"'machine'",
"]",
"=",
... | Provision a single machine
CLI Example:
.. code-block:: bash
salt-cloud -p my_profile new_node_1 | [
"Provision",
"a",
"single",
"machine"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/vagrant.py#L186-L248 | train |
saltstack/salt | salt/cloud/clouds/vagrant.py | destroy | def destroy(name, call=None):
'''
Destroy a node.
CLI Example:
.. code-block:: bash
salt-cloud --destroy mymachine
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a, or --action.'
)
opts = __opts__
__utils__['cloud.fire_event'](
'event',
'destroying instance',
'salt/cloud/{0}/destroying'.format(name),
args={'name': name},
sock_dir=opts['sock_dir'],
transport=opts['transport']
)
my_info = _get_my_info(name)
if my_info:
profile_name = my_info[name]['profile']
profile = opts['profiles'][profile_name]
host = profile['host']
local = salt.client.LocalClient()
ret = local.cmd(host, 'vagrant.destroy', [name])
if ret[host]:
__utils__['cloud.fire_event'](
'event',
'destroyed instance',
'salt/cloud/{0}/destroyed'.format(name),
args={'name': name},
sock_dir=opts['sock_dir'],
transport=opts['transport']
)
if opts.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](
name, __active_provider_name__.split(':')[0], opts)
return {'Destroyed': '{0} was destroyed.'.format(name)}
else:
return {'Error': 'Error destroying {}'.format(name)}
else:
return {'Error': 'No response from {}. Cannot destroy.'.format(name)} | python | def destroy(name, call=None):
'''
Destroy a node.
CLI Example:
.. code-block:: bash
salt-cloud --destroy mymachine
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a, or --action.'
)
opts = __opts__
__utils__['cloud.fire_event'](
'event',
'destroying instance',
'salt/cloud/{0}/destroying'.format(name),
args={'name': name},
sock_dir=opts['sock_dir'],
transport=opts['transport']
)
my_info = _get_my_info(name)
if my_info:
profile_name = my_info[name]['profile']
profile = opts['profiles'][profile_name]
host = profile['host']
local = salt.client.LocalClient()
ret = local.cmd(host, 'vagrant.destroy', [name])
if ret[host]:
__utils__['cloud.fire_event'](
'event',
'destroyed instance',
'salt/cloud/{0}/destroyed'.format(name),
args={'name': name},
sock_dir=opts['sock_dir'],
transport=opts['transport']
)
if opts.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](
name, __active_provider_name__.split(':')[0], opts)
return {'Destroyed': '{0} was destroyed.'.format(name)}
else:
return {'Error': 'Error destroying {}'.format(name)}
else:
return {'Error': 'No response from {}. Cannot destroy.'.format(name)} | [
"def",
"destroy",
"(",
"name",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"==",
"'function'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The destroy action must be called with -d, --destroy, '",
"'-a, or --action.'",
")",
"opts",
"=",
"__opts__",
"__utils__",
... | Destroy a node.
CLI Example:
.. code-block:: bash
salt-cloud --destroy mymachine | [
"Destroy",
"a",
"node",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/vagrant.py#L264-L316 | train |
saltstack/salt | salt/cloud/clouds/vagrant.py | reboot | def reboot(name, call=None):
'''
Reboot a vagrant minion.
name
The name of the VM to reboot.
CLI Example:
.. code-block:: bash
salt-cloud -a reboot vm_name
'''
if call != 'action':
raise SaltCloudException(
'The reboot action must be called with -a or --action.'
)
my_info = _get_my_info(name)
profile_name = my_info[name]['profile']
profile = __opts__['profiles'][profile_name]
host = profile['host']
local = salt.client.LocalClient()
return local.cmd(host, 'vagrant.reboot', [name]) | python | def reboot(name, call=None):
'''
Reboot a vagrant minion.
name
The name of the VM to reboot.
CLI Example:
.. code-block:: bash
salt-cloud -a reboot vm_name
'''
if call != 'action':
raise SaltCloudException(
'The reboot action must be called with -a or --action.'
)
my_info = _get_my_info(name)
profile_name = my_info[name]['profile']
profile = __opts__['profiles'][profile_name]
host = profile['host']
local = salt.client.LocalClient()
return local.cmd(host, 'vagrant.reboot', [name]) | [
"def",
"reboot",
"(",
"name",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'action'",
":",
"raise",
"SaltCloudException",
"(",
"'The reboot action must be called with -a or --action.'",
")",
"my_info",
"=",
"_get_my_info",
"(",
"name",
")",
"profile_na... | Reboot a vagrant minion.
name
The name of the VM to reboot.
CLI Example:
.. code-block:: bash
salt-cloud -a reboot vm_name | [
"Reboot",
"a",
"vagrant",
"minion",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/vagrant.py#L320-L342 | train |
saltstack/salt | salt/utils/pkg/__init__.py | clear_rtag | def clear_rtag(opts):
'''
Remove the rtag file
'''
try:
os.remove(rtag(opts))
except OSError as exc:
if exc.errno != errno.ENOENT:
# Using __str__() here to get the fully-formatted error message
# (error number, error message, path)
log.warning('Encountered error removing rtag: %s', exc.__str__()) | python | def clear_rtag(opts):
'''
Remove the rtag file
'''
try:
os.remove(rtag(opts))
except OSError as exc:
if exc.errno != errno.ENOENT:
# Using __str__() here to get the fully-formatted error message
# (error number, error message, path)
log.warning('Encountered error removing rtag: %s', exc.__str__()) | [
"def",
"clear_rtag",
"(",
"opts",
")",
":",
"try",
":",
"os",
".",
"remove",
"(",
"rtag",
"(",
"opts",
")",
")",
"except",
"OSError",
"as",
"exc",
":",
"if",
"exc",
".",
"errno",
"!=",
"errno",
".",
"ENOENT",
":",
"# Using __str__() here to get the fully... | Remove the rtag file | [
"Remove",
"the",
"rtag",
"file"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/pkg/__init__.py#L28-L38 | train |
saltstack/salt | salt/utils/pkg/__init__.py | write_rtag | def write_rtag(opts):
'''
Write the rtag file
'''
rtag_file = rtag(opts)
if not os.path.exists(rtag_file):
try:
with salt.utils.files.fopen(rtag_file, 'w+'):
pass
except OSError as exc:
log.warning('Encountered error writing rtag: %s', exc.__str__()) | python | def write_rtag(opts):
'''
Write the rtag file
'''
rtag_file = rtag(opts)
if not os.path.exists(rtag_file):
try:
with salt.utils.files.fopen(rtag_file, 'w+'):
pass
except OSError as exc:
log.warning('Encountered error writing rtag: %s', exc.__str__()) | [
"def",
"write_rtag",
"(",
"opts",
")",
":",
"rtag_file",
"=",
"rtag",
"(",
"opts",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"rtag_file",
")",
":",
"try",
":",
"with",
"salt",
".",
"utils",
".",
"files",
".",
"fopen",
"(",
"rtag_file... | Write the rtag file | [
"Write",
"the",
"rtag",
"file"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/pkg/__init__.py#L41-L51 | train |
saltstack/salt | salt/utils/pkg/__init__.py | check_refresh | def check_refresh(opts, refresh=None):
'''
Check whether or not a refresh is necessary
Returns:
- True if refresh evaluates as True
- False if refresh is False
- A boolean if refresh is not False and the rtag file exists
'''
return bool(
salt.utils.data.is_true(refresh) or
(os.path.isfile(rtag(opts)) and refresh is not False)
) | python | def check_refresh(opts, refresh=None):
'''
Check whether or not a refresh is necessary
Returns:
- True if refresh evaluates as True
- False if refresh is False
- A boolean if refresh is not False and the rtag file exists
'''
return bool(
salt.utils.data.is_true(refresh) or
(os.path.isfile(rtag(opts)) and refresh is not False)
) | [
"def",
"check_refresh",
"(",
"opts",
",",
"refresh",
"=",
"None",
")",
":",
"return",
"bool",
"(",
"salt",
".",
"utils",
".",
"data",
".",
"is_true",
"(",
"refresh",
")",
"or",
"(",
"os",
".",
"path",
".",
"isfile",
"(",
"rtag",
"(",
"opts",
")",
... | Check whether or not a refresh is necessary
Returns:
- True if refresh evaluates as True
- False if refresh is False
- A boolean if refresh is not False and the rtag file exists | [
"Check",
"whether",
"or",
"not",
"a",
"refresh",
"is",
"necessary"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/pkg/__init__.py#L54-L67 | train |
saltstack/salt | salt/utils/pkg/__init__.py | match_version | def match_version(desired, available, cmp_func=None, ignore_epoch=False):
'''
Returns the first version of the list of available versions which matches
the desired version comparison expression, or None if no match is found.
'''
oper, version = split_comparison(desired)
if not oper:
oper = '=='
for candidate in available:
if salt.utils.versions.compare(ver1=candidate,
oper=oper,
ver2=version,
cmp_func=cmp_func,
ignore_epoch=ignore_epoch):
return candidate
return None | python | def match_version(desired, available, cmp_func=None, ignore_epoch=False):
'''
Returns the first version of the list of available versions which matches
the desired version comparison expression, or None if no match is found.
'''
oper, version = split_comparison(desired)
if not oper:
oper = '=='
for candidate in available:
if salt.utils.versions.compare(ver1=candidate,
oper=oper,
ver2=version,
cmp_func=cmp_func,
ignore_epoch=ignore_epoch):
return candidate
return None | [
"def",
"match_version",
"(",
"desired",
",",
"available",
",",
"cmp_func",
"=",
"None",
",",
"ignore_epoch",
"=",
"False",
")",
":",
"oper",
",",
"version",
"=",
"split_comparison",
"(",
"desired",
")",
"if",
"not",
"oper",
":",
"oper",
"=",
"'=='",
"for... | Returns the first version of the list of available versions which matches
the desired version comparison expression, or None if no match is found. | [
"Returns",
"the",
"first",
"version",
"of",
"the",
"list",
"of",
"available",
"versions",
"which",
"matches",
"the",
"desired",
"version",
"comparison",
"expression",
"or",
"None",
"if",
"no",
"match",
"is",
"found",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/pkg/__init__.py#L80-L95 | train |
saltstack/salt | salt/modules/swift.py | _auth | def _auth(profile=None):
'''
Set up openstack credentials
'''
if profile:
credentials = __salt__['config.option'](profile)
user = credentials['keystone.user']
password = credentials.get('keystone.password', None)
tenant = credentials['keystone.tenant']
auth_url = credentials['keystone.auth_url']
auth_version = credentials.get('keystone.auth_version', 2)
region_name = credentials.get('keystone.region_name', None)
api_key = credentials.get('keystone.api_key', None)
os_auth_system = credentials.get('keystone.os_auth_system', None)
else:
user = __salt__['config.option']('keystone.user')
password = __salt__['config.option']('keystone.password', None)
tenant = __salt__['config.option']('keystone.tenant')
auth_url = __salt__['config.option']('keystone.auth_url')
auth_version = __salt__['config.option']('keystone.auth_version', 2)
region_name = __salt__['config.option']('keystone.region_name')
api_key = __salt__['config.option']('keystone.api_key')
os_auth_system = __salt__['config.option']('keystone.os_auth_system')
kwargs = {
'user': user,
'password': password,
'key': api_key,
'tenant_name': tenant,
'auth_url': auth_url,
'auth_version': auth_version,
'region_name': region_name
}
return suos.SaltSwift(**kwargs) | python | def _auth(profile=None):
'''
Set up openstack credentials
'''
if profile:
credentials = __salt__['config.option'](profile)
user = credentials['keystone.user']
password = credentials.get('keystone.password', None)
tenant = credentials['keystone.tenant']
auth_url = credentials['keystone.auth_url']
auth_version = credentials.get('keystone.auth_version', 2)
region_name = credentials.get('keystone.region_name', None)
api_key = credentials.get('keystone.api_key', None)
os_auth_system = credentials.get('keystone.os_auth_system', None)
else:
user = __salt__['config.option']('keystone.user')
password = __salt__['config.option']('keystone.password', None)
tenant = __salt__['config.option']('keystone.tenant')
auth_url = __salt__['config.option']('keystone.auth_url')
auth_version = __salt__['config.option']('keystone.auth_version', 2)
region_name = __salt__['config.option']('keystone.region_name')
api_key = __salt__['config.option']('keystone.api_key')
os_auth_system = __salt__['config.option']('keystone.os_auth_system')
kwargs = {
'user': user,
'password': password,
'key': api_key,
'tenant_name': tenant,
'auth_url': auth_url,
'auth_version': auth_version,
'region_name': region_name
}
return suos.SaltSwift(**kwargs) | [
"def",
"_auth",
"(",
"profile",
"=",
"None",
")",
":",
"if",
"profile",
":",
"credentials",
"=",
"__salt__",
"[",
"'config.option'",
"]",
"(",
"profile",
")",
"user",
"=",
"credentials",
"[",
"'keystone.user'",
"]",
"password",
"=",
"credentials",
".",
"ge... | Set up openstack credentials | [
"Set",
"up",
"openstack",
"credentials"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/swift.py#L71-L104 | train |
saltstack/salt | salt/modules/swift.py | delete | def delete(cont, path=None, profile=None):
'''
Delete a container, or delete an object from a container.
CLI Example to delete a container::
salt myminion swift.delete mycontainer
CLI Example to delete an object from a container::
salt myminion swift.delete mycontainer remoteobject
'''
swift_conn = _auth(profile)
if path is None:
return swift_conn.delete_container(cont)
else:
return swift_conn.delete_object(cont, path) | python | def delete(cont, path=None, profile=None):
'''
Delete a container, or delete an object from a container.
CLI Example to delete a container::
salt myminion swift.delete mycontainer
CLI Example to delete an object from a container::
salt myminion swift.delete mycontainer remoteobject
'''
swift_conn = _auth(profile)
if path is None:
return swift_conn.delete_container(cont)
else:
return swift_conn.delete_object(cont, path) | [
"def",
"delete",
"(",
"cont",
",",
"path",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"swift_conn",
"=",
"_auth",
"(",
"profile",
")",
"if",
"path",
"is",
"None",
":",
"return",
"swift_conn",
".",
"delete_container",
"(",
"cont",
")",
"else",
... | Delete a container, or delete an object from a container.
CLI Example to delete a container::
salt myminion swift.delete mycontainer
CLI Example to delete an object from a container::
salt myminion swift.delete mycontainer remoteobject | [
"Delete",
"a",
"container",
"or",
"delete",
"an",
"object",
"from",
"a",
"container",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/swift.py#L107-L124 | train |
saltstack/salt | salt/modules/swift.py | get | def get(cont=None, path=None, local_file=None, return_bin=False, profile=None):
'''
List the contents of a container, or return an object from a container. Set
return_bin to True in order to retrieve an object wholesale. Otherwise,
Salt will attempt to parse an XML response.
CLI Example to list containers:
.. code-block:: bash
salt myminion swift.get
CLI Example to list the contents of a container:
.. code-block:: bash
salt myminion swift.get mycontainer
CLI Example to return the binary contents of an object:
.. code-block:: bash
salt myminion swift.get mycontainer myfile.png return_bin=True
CLI Example to save the binary contents of an object to a local file:
.. code-block:: bash
salt myminion swift.get mycontainer myfile.png local_file=/tmp/myfile.png
'''
swift_conn = _auth(profile)
if cont is None:
return swift_conn.get_account()
if path is None:
return swift_conn.get_container(cont)
if return_bin is True:
return swift_conn.get_object(cont, path, return_bin)
if local_file is not None:
return swift_conn.get_object(cont, path, local_file)
return False | python | def get(cont=None, path=None, local_file=None, return_bin=False, profile=None):
'''
List the contents of a container, or return an object from a container. Set
return_bin to True in order to retrieve an object wholesale. Otherwise,
Salt will attempt to parse an XML response.
CLI Example to list containers:
.. code-block:: bash
salt myminion swift.get
CLI Example to list the contents of a container:
.. code-block:: bash
salt myminion swift.get mycontainer
CLI Example to return the binary contents of an object:
.. code-block:: bash
salt myminion swift.get mycontainer myfile.png return_bin=True
CLI Example to save the binary contents of an object to a local file:
.. code-block:: bash
salt myminion swift.get mycontainer myfile.png local_file=/tmp/myfile.png
'''
swift_conn = _auth(profile)
if cont is None:
return swift_conn.get_account()
if path is None:
return swift_conn.get_container(cont)
if return_bin is True:
return swift_conn.get_object(cont, path, return_bin)
if local_file is not None:
return swift_conn.get_object(cont, path, local_file)
return False | [
"def",
"get",
"(",
"cont",
"=",
"None",
",",
"path",
"=",
"None",
",",
"local_file",
"=",
"None",
",",
"return_bin",
"=",
"False",
",",
"profile",
"=",
"None",
")",
":",
"swift_conn",
"=",
"_auth",
"(",
"profile",
")",
"if",
"cont",
"is",
"None",
"... | List the contents of a container, or return an object from a container. Set
return_bin to True in order to retrieve an object wholesale. Otherwise,
Salt will attempt to parse an XML response.
CLI Example to list containers:
.. code-block:: bash
salt myminion swift.get
CLI Example to list the contents of a container:
.. code-block:: bash
salt myminion swift.get mycontainer
CLI Example to return the binary contents of an object:
.. code-block:: bash
salt myminion swift.get mycontainer myfile.png return_bin=True
CLI Example to save the binary contents of an object to a local file:
.. code-block:: bash
salt myminion swift.get mycontainer myfile.png local_file=/tmp/myfile.png | [
"List",
"the",
"contents",
"of",
"a",
"container",
"or",
"return",
"an",
"object",
"from",
"a",
"container",
".",
"Set",
"return_bin",
"to",
"True",
"in",
"order",
"to",
"retrieve",
"an",
"object",
"wholesale",
".",
"Otherwise",
"Salt",
"will",
"attempt",
... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/swift.py#L127-L172 | train |
saltstack/salt | salt/modules/swift.py | put | def put(cont, path=None, local_file=None, profile=None):
'''
Create a new container, or upload an object to a container.
CLI Example to create a container:
.. code-block:: bash
salt myminion swift.put mycontainer
CLI Example to upload an object to a container:
.. code-block:: bash
salt myminion swift.put mycontainer remotepath local_file=/path/to/file
'''
swift_conn = _auth(profile)
if path is None:
return swift_conn.put_container(cont)
elif local_file is not None:
return swift_conn.put_object(cont, path, local_file)
else:
return False | python | def put(cont, path=None, local_file=None, profile=None):
'''
Create a new container, or upload an object to a container.
CLI Example to create a container:
.. code-block:: bash
salt myminion swift.put mycontainer
CLI Example to upload an object to a container:
.. code-block:: bash
salt myminion swift.put mycontainer remotepath local_file=/path/to/file
'''
swift_conn = _auth(profile)
if path is None:
return swift_conn.put_container(cont)
elif local_file is not None:
return swift_conn.put_object(cont, path, local_file)
else:
return False | [
"def",
"put",
"(",
"cont",
",",
"path",
"=",
"None",
",",
"local_file",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"swift_conn",
"=",
"_auth",
"(",
"profile",
")",
"if",
"path",
"is",
"None",
":",
"return",
"swift_conn",
".",
"put_container",
... | Create a new container, or upload an object to a container.
CLI Example to create a container:
.. code-block:: bash
salt myminion swift.put mycontainer
CLI Example to upload an object to a container:
.. code-block:: bash
salt myminion swift.put mycontainer remotepath local_file=/path/to/file | [
"Create",
"a",
"new",
"container",
"or",
"upload",
"an",
"object",
"to",
"a",
"container",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/swift.py#L179-L202 | train |
saltstack/salt | salt/modules/mac_shadow.py | _get_account_policy | def _get_account_policy(name):
'''
Get the entire accountPolicy and return it as a dictionary. For use by this
module only
:param str name: The user name
:return: a dictionary containing all values for the accountPolicy
:rtype: dict
:raises: CommandExecutionError on user not found or any other unknown error
'''
cmd = 'pwpolicy -u {0} -getpolicy'.format(name)
try:
ret = salt.utils.mac_utils.execute_return_result(cmd)
except CommandExecutionError as exc:
if 'Error: user <{0}> not found'.format(name) in exc.strerror:
raise CommandExecutionError('User not found: {0}'.format(name))
raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))
try:
policy_list = ret.split('\n')[1].split(' ')
policy_dict = {}
for policy in policy_list:
if '=' in policy:
key, value = policy.split('=')
policy_dict[key] = value
return policy_dict
except IndexError:
return {} | python | def _get_account_policy(name):
'''
Get the entire accountPolicy and return it as a dictionary. For use by this
module only
:param str name: The user name
:return: a dictionary containing all values for the accountPolicy
:rtype: dict
:raises: CommandExecutionError on user not found or any other unknown error
'''
cmd = 'pwpolicy -u {0} -getpolicy'.format(name)
try:
ret = salt.utils.mac_utils.execute_return_result(cmd)
except CommandExecutionError as exc:
if 'Error: user <{0}> not found'.format(name) in exc.strerror:
raise CommandExecutionError('User not found: {0}'.format(name))
raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))
try:
policy_list = ret.split('\n')[1].split(' ')
policy_dict = {}
for policy in policy_list:
if '=' in policy:
key, value = policy.split('=')
policy_dict[key] = value
return policy_dict
except IndexError:
return {} | [
"def",
"_get_account_policy",
"(",
"name",
")",
":",
"cmd",
"=",
"'pwpolicy -u {0} -getpolicy'",
".",
"format",
"(",
"name",
")",
"try",
":",
"ret",
"=",
"salt",
".",
"utils",
".",
"mac_utils",
".",
"execute_return_result",
"(",
"cmd",
")",
"except",
"Comman... | Get the entire accountPolicy and return it as a dictionary. For use by this
module only
:param str name: The user name
:return: a dictionary containing all values for the accountPolicy
:rtype: dict
:raises: CommandExecutionError on user not found or any other unknown error | [
"Get",
"the",
"entire",
"accountPolicy",
"and",
"return",
"it",
"as",
"a",
"dictionary",
".",
"For",
"use",
"by",
"this",
"module",
"only"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_shadow.py#L45-L75 | train |
saltstack/salt | salt/modules/mac_shadow.py | _set_account_policy | def _set_account_policy(name, policy):
'''
Set a value in the user accountPolicy. For use by this module only
:param str name: The user name
:param str policy: The policy to apply
:return: True if success, otherwise False
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
'''
cmd = 'pwpolicy -u {0} -setpolicy "{1}"'.format(name, policy)
try:
return salt.utils.mac_utils.execute_return_success(cmd)
except CommandExecutionError as exc:
if 'Error: user <{0}> not found'.format(name) in exc.strerror:
raise CommandExecutionError('User not found: {0}'.format(name))
raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror)) | python | def _set_account_policy(name, policy):
'''
Set a value in the user accountPolicy. For use by this module only
:param str name: The user name
:param str policy: The policy to apply
:return: True if success, otherwise False
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
'''
cmd = 'pwpolicy -u {0} -setpolicy "{1}"'.format(name, policy)
try:
return salt.utils.mac_utils.execute_return_success(cmd)
except CommandExecutionError as exc:
if 'Error: user <{0}> not found'.format(name) in exc.strerror:
raise CommandExecutionError('User not found: {0}'.format(name))
raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror)) | [
"def",
"_set_account_policy",
"(",
"name",
",",
"policy",
")",
":",
"cmd",
"=",
"'pwpolicy -u {0} -setpolicy \"{1}\"'",
".",
"format",
"(",
"name",
",",
"policy",
")",
"try",
":",
"return",
"salt",
".",
"utils",
".",
"mac_utils",
".",
"execute_return_success",
... | Set a value in the user accountPolicy. For use by this module only
:param str name: The user name
:param str policy: The policy to apply
:return: True if success, otherwise False
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error | [
"Set",
"a",
"value",
"in",
"the",
"user",
"accountPolicy",
".",
"For",
"use",
"by",
"this",
"module",
"only"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_shadow.py#L78-L97 | train |
saltstack/salt | salt/modules/mac_shadow.py | _get_account_policy_data_value | def _get_account_policy_data_value(name, key):
'''
Return the value for a key in the accountPolicy section of the user's plist
file. For use by this module only
:param str name: The username
:param str key: The accountPolicy key
:return: The value contained within the key
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
'''
cmd = 'dscl . -readpl /Users/{0} accountPolicyData {1}'.format(name, key)
try:
ret = salt.utils.mac_utils.execute_return_result(cmd)
except CommandExecutionError as exc:
if 'eDSUnknownNodeName' in exc.strerror:
raise CommandExecutionError('User not found: {0}'.format(name))
raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))
return ret | python | def _get_account_policy_data_value(name, key):
'''
Return the value for a key in the accountPolicy section of the user's plist
file. For use by this module only
:param str name: The username
:param str key: The accountPolicy key
:return: The value contained within the key
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
'''
cmd = 'dscl . -readpl /Users/{0} accountPolicyData {1}'.format(name, key)
try:
ret = salt.utils.mac_utils.execute_return_result(cmd)
except CommandExecutionError as exc:
if 'eDSUnknownNodeName' in exc.strerror:
raise CommandExecutionError('User not found: {0}'.format(name))
raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))
return ret | [
"def",
"_get_account_policy_data_value",
"(",
"name",
",",
"key",
")",
":",
"cmd",
"=",
"'dscl . -readpl /Users/{0} accountPolicyData {1}'",
".",
"format",
"(",
"name",
",",
"key",
")",
"try",
":",
"ret",
"=",
"salt",
".",
"utils",
".",
"mac_utils",
".",
"exec... | Return the value for a key in the accountPolicy section of the user's plist
file. For use by this module only
:param str name: The username
:param str key: The accountPolicy key
:return: The value contained within the key
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error | [
"Return",
"the",
"value",
"for",
"a",
"key",
"in",
"the",
"accountPolicy",
"section",
"of",
"the",
"user",
"s",
"plist",
"file",
".",
"For",
"use",
"by",
"this",
"module",
"only"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_shadow.py#L100-L121 | train |
saltstack/salt | salt/modules/mac_shadow.py | _convert_to_datetime | def _convert_to_datetime(unix_timestamp):
'''
Converts a unix timestamp to a human readable date/time
:param float unix_timestamp: A unix timestamp
:return: A date/time in the format YYYY-mm-dd HH:MM:SS
:rtype: str
'''
try:
unix_timestamp = float(unix_timestamp)
return datetime.fromtimestamp(unix_timestamp).strftime('%Y-%m-%d %H:%M:%S')
except (ValueError, TypeError):
return 'Invalid Timestamp' | python | def _convert_to_datetime(unix_timestamp):
'''
Converts a unix timestamp to a human readable date/time
:param float unix_timestamp: A unix timestamp
:return: A date/time in the format YYYY-mm-dd HH:MM:SS
:rtype: str
'''
try:
unix_timestamp = float(unix_timestamp)
return datetime.fromtimestamp(unix_timestamp).strftime('%Y-%m-%d %H:%M:%S')
except (ValueError, TypeError):
return 'Invalid Timestamp' | [
"def",
"_convert_to_datetime",
"(",
"unix_timestamp",
")",
":",
"try",
":",
"unix_timestamp",
"=",
"float",
"(",
"unix_timestamp",
")",
"return",
"datetime",
".",
"fromtimestamp",
"(",
"unix_timestamp",
")",
".",
"strftime",
"(",
"'%Y-%m-%d %H:%M:%S'",
")",
"excep... | Converts a unix timestamp to a human readable date/time
:param float unix_timestamp: A unix timestamp
:return: A date/time in the format YYYY-mm-dd HH:MM:SS
:rtype: str | [
"Converts",
"a",
"unix",
"timestamp",
"to",
"a",
"human",
"readable",
"date",
"/",
"time"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_shadow.py#L124-L137 | train |
saltstack/salt | salt/modules/mac_shadow.py | info | def info(name):
'''
Return information for the specified user
:param str name: The username
:return: A dictionary containing the user's shadow information
:rtype: dict
CLI Example:
.. code-block:: bash
salt '*' shadow.info admin
'''
try:
data = pwd.getpwnam(name)
return {'name': data.pw_name,
'passwd': data.pw_passwd,
'account_created': get_account_created(name),
'login_failed_count': get_login_failed_count(name),
'login_failed_last': get_login_failed_last(name),
'lstchg': get_last_change(name),
'max': get_maxdays(name),
'expire': get_expire(name),
'change': get_change(name),
'min': 'Unavailable',
'warn': 'Unavailable',
'inact': 'Unavailable'}
except KeyError:
log.debug('User not found: %s', name)
return {'name': '',
'passwd': '',
'account_created': '',
'login_failed_count': '',
'login_failed_last': '',
'lstchg': '',
'max': '',
'expire': '',
'change': '',
'min': '',
'warn': '',
'inact': ''} | python | def info(name):
'''
Return information for the specified user
:param str name: The username
:return: A dictionary containing the user's shadow information
:rtype: dict
CLI Example:
.. code-block:: bash
salt '*' shadow.info admin
'''
try:
data = pwd.getpwnam(name)
return {'name': data.pw_name,
'passwd': data.pw_passwd,
'account_created': get_account_created(name),
'login_failed_count': get_login_failed_count(name),
'login_failed_last': get_login_failed_last(name),
'lstchg': get_last_change(name),
'max': get_maxdays(name),
'expire': get_expire(name),
'change': get_change(name),
'min': 'Unavailable',
'warn': 'Unavailable',
'inact': 'Unavailable'}
except KeyError:
log.debug('User not found: %s', name)
return {'name': '',
'passwd': '',
'account_created': '',
'login_failed_count': '',
'login_failed_last': '',
'lstchg': '',
'max': '',
'expire': '',
'change': '',
'min': '',
'warn': '',
'inact': ''} | [
"def",
"info",
"(",
"name",
")",
":",
"try",
":",
"data",
"=",
"pwd",
".",
"getpwnam",
"(",
"name",
")",
"return",
"{",
"'name'",
":",
"data",
".",
"pw_name",
",",
"'passwd'",
":",
"data",
".",
"pw_passwd",
",",
"'account_created'",
":",
"get_account_c... | Return information for the specified user
:param str name: The username
:return: A dictionary containing the user's shadow information
:rtype: dict
CLI Example:
.. code-block:: bash
salt '*' shadow.info admin | [
"Return",
"information",
"for",
"the",
"specified",
"user"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_shadow.py#L140-L183 | train |
saltstack/salt | salt/modules/mac_shadow.py | get_account_created | def get_account_created(name):
'''
Get the date/time the account was created
:param str name: The username of the account
:return: The date/time the account was created (yyyy-mm-dd hh:mm:ss)
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_account_created admin
'''
ret = _get_account_policy_data_value(name, 'creationTime')
unix_timestamp = salt.utils.mac_utils.parse_return(ret)
date_text = _convert_to_datetime(unix_timestamp)
return date_text | python | def get_account_created(name):
'''
Get the date/time the account was created
:param str name: The username of the account
:return: The date/time the account was created (yyyy-mm-dd hh:mm:ss)
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_account_created admin
'''
ret = _get_account_policy_data_value(name, 'creationTime')
unix_timestamp = salt.utils.mac_utils.parse_return(ret)
date_text = _convert_to_datetime(unix_timestamp)
return date_text | [
"def",
"get_account_created",
"(",
"name",
")",
":",
"ret",
"=",
"_get_account_policy_data_value",
"(",
"name",
",",
"'creationTime'",
")",
"unix_timestamp",
"=",
"salt",
".",
"utils",
".",
"mac_utils",
".",
"parse_return",
"(",
"ret",
")",
"date_text",
"=",
"... | Get the date/time the account was created
:param str name: The username of the account
:return: The date/time the account was created (yyyy-mm-dd hh:mm:ss)
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_account_created admin | [
"Get",
"the",
"date",
"/",
"time",
"the",
"account",
"was",
"created"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_shadow.py#L186-L209 | train |
saltstack/salt | salt/modules/mac_shadow.py | get_login_failed_count | def get_login_failed_count(name):
'''
Get the the number of failed login attempts
:param str name: The username of the account
:return: The number of failed login attempts
:rtype: int
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_login_failed_count admin
'''
ret = _get_account_policy_data_value(name, 'failedLoginCount')
return salt.utils.mac_utils.parse_return(ret) | python | def get_login_failed_count(name):
'''
Get the the number of failed login attempts
:param str name: The username of the account
:return: The number of failed login attempts
:rtype: int
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_login_failed_count admin
'''
ret = _get_account_policy_data_value(name, 'failedLoginCount')
return salt.utils.mac_utils.parse_return(ret) | [
"def",
"get_login_failed_count",
"(",
"name",
")",
":",
"ret",
"=",
"_get_account_policy_data_value",
"(",
"name",
",",
"'failedLoginCount'",
")",
"return",
"salt",
".",
"utils",
".",
"mac_utils",
".",
"parse_return",
"(",
"ret",
")"
] | Get the the number of failed login attempts
:param str name: The username of the account
:return: The number of failed login attempts
:rtype: int
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_login_failed_count admin | [
"Get",
"the",
"the",
"number",
"of",
"failed",
"login",
"attempts"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_shadow.py#L238-L257 | train |
saltstack/salt | salt/modules/mac_shadow.py | set_maxdays | def set_maxdays(name, days):
'''
Set the maximum age of the password in days
:param str name: The username of the account
:param int days: The maximum age of the account in days
:return: True if successful, False if not
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.set_maxdays admin 90
'''
minutes = days * 24 * 60
_set_account_policy(
name, 'maxMinutesUntilChangePassword={0}'.format(minutes))
return get_maxdays(name) == days | python | def set_maxdays(name, days):
'''
Set the maximum age of the password in days
:param str name: The username of the account
:param int days: The maximum age of the account in days
:return: True if successful, False if not
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.set_maxdays admin 90
'''
minutes = days * 24 * 60
_set_account_policy(
name, 'maxMinutesUntilChangePassword={0}'.format(minutes))
return get_maxdays(name) == days | [
"def",
"set_maxdays",
"(",
"name",
",",
"days",
")",
":",
"minutes",
"=",
"days",
"*",
"24",
"*",
"60",
"_set_account_policy",
"(",
"name",
",",
"'maxMinutesUntilChangePassword={0}'",
".",
"format",
"(",
"minutes",
")",
")",
"return",
"get_maxdays",
"(",
"na... | Set the maximum age of the password in days
:param str name: The username of the account
:param int days: The maximum age of the account in days
:return: True if successful, False if not
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.set_maxdays admin 90 | [
"Set",
"the",
"maximum",
"age",
"of",
"the",
"password",
"in",
"days"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_shadow.py#L287-L311 | train |
saltstack/salt | salt/modules/mac_shadow.py | get_maxdays | def get_maxdays(name):
'''
Get the maximum age of the password
:param str name: The username of the account
:return: The maximum age of the password in days
:rtype: int
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_maxdays admin 90
'''
policies = _get_account_policy(name)
if 'maxMinutesUntilChangePassword' in policies:
max_minutes = policies['maxMinutesUntilChangePassword']
return int(max_minutes) / 24 / 60
return 0 | python | def get_maxdays(name):
'''
Get the maximum age of the password
:param str name: The username of the account
:return: The maximum age of the password in days
:rtype: int
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_maxdays admin 90
'''
policies = _get_account_policy(name)
if 'maxMinutesUntilChangePassword' in policies:
max_minutes = policies['maxMinutesUntilChangePassword']
return int(max_minutes) / 24 / 60
return 0 | [
"def",
"get_maxdays",
"(",
"name",
")",
":",
"policies",
"=",
"_get_account_policy",
"(",
"name",
")",
"if",
"'maxMinutesUntilChangePassword'",
"in",
"policies",
":",
"max_minutes",
"=",
"policies",
"[",
"'maxMinutesUntilChangePassword'",
"]",
"return",
"int",
"(",
... | Get the maximum age of the password
:param str name: The username of the account
:return: The maximum age of the password in days
:rtype: int
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_maxdays admin 90 | [
"Get",
"the",
"maximum",
"age",
"of",
"the",
"password"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_shadow.py#L314-L337 | train |
saltstack/salt | salt/modules/mac_shadow.py | set_change | def set_change(name, date):
'''
Sets the date on which the password expires. The user will be required to
change their password. Format is mm/dd/yyyy
:param str name: The name of the user account
:param date date: The date the password will expire. Must be in mm/dd/yyyy
format.
:return: True if successful, otherwise False
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.set_change username 09/21/2016
'''
_set_account_policy(
name, 'usingExpirationDate=1 expirationDateGMT={0}'.format(date))
return get_change(name) == date | python | def set_change(name, date):
'''
Sets the date on which the password expires. The user will be required to
change their password. Format is mm/dd/yyyy
:param str name: The name of the user account
:param date date: The date the password will expire. Must be in mm/dd/yyyy
format.
:return: True if successful, otherwise False
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.set_change username 09/21/2016
'''
_set_account_policy(
name, 'usingExpirationDate=1 expirationDateGMT={0}'.format(date))
return get_change(name) == date | [
"def",
"set_change",
"(",
"name",
",",
"date",
")",
":",
"_set_account_policy",
"(",
"name",
",",
"'usingExpirationDate=1 expirationDateGMT={0}'",
".",
"format",
"(",
"date",
")",
")",
"return",
"get_change",
"(",
"name",
")",
"==",
"date"
] | Sets the date on which the password expires. The user will be required to
change their password. Format is mm/dd/yyyy
:param str name: The name of the user account
:param date date: The date the password will expire. Must be in mm/dd/yyyy
format.
:return: True if successful, otherwise False
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.set_change username 09/21/2016 | [
"Sets",
"the",
"date",
"on",
"which",
"the",
"password",
"expires",
".",
"The",
"user",
"will",
"be",
"required",
"to",
"change",
"their",
"password",
".",
"Format",
"is",
"mm",
"/",
"dd",
"/",
"yyyy"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_shadow.py#L402-L426 | train |
saltstack/salt | salt/modules/mac_shadow.py | set_expire | def set_expire(name, date):
'''
Sets the date on which the account expires. The user will not be able to
login after this date. Date format is mm/dd/yyyy
:param str name: The name of the user account
:param datetime date: The date the account will expire. Format must be
mm/dd/yyyy.
:return: True if successful, False if not
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.set_expire username 07/23/2015
'''
_set_account_policy(
name, 'usingHardExpirationDate=1 hardExpireDateGMT={0}'.format(date))
return get_expire(name) == date | python | def set_expire(name, date):
'''
Sets the date on which the account expires. The user will not be able to
login after this date. Date format is mm/dd/yyyy
:param str name: The name of the user account
:param datetime date: The date the account will expire. Format must be
mm/dd/yyyy.
:return: True if successful, False if not
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.set_expire username 07/23/2015
'''
_set_account_policy(
name, 'usingHardExpirationDate=1 hardExpireDateGMT={0}'.format(date))
return get_expire(name) == date | [
"def",
"set_expire",
"(",
"name",
",",
"date",
")",
":",
"_set_account_policy",
"(",
"name",
",",
"'usingHardExpirationDate=1 hardExpireDateGMT={0}'",
".",
"format",
"(",
"date",
")",
")",
"return",
"get_expire",
"(",
"name",
")",
"==",
"date"
] | Sets the date on which the account expires. The user will not be able to
login after this date. Date format is mm/dd/yyyy
:param str name: The name of the user account
:param datetime date: The date the account will expire. Format must be
mm/dd/yyyy.
:return: True if successful, False if not
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.set_expire username 07/23/2015 | [
"Sets",
"the",
"date",
"on",
"which",
"the",
"account",
"expires",
".",
"The",
"user",
"will",
"not",
"be",
"able",
"to",
"login",
"after",
"this",
"date",
".",
"Date",
"format",
"is",
"mm",
"/",
"dd",
"/",
"yyyy"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_shadow.py#L454-L478 | train |
saltstack/salt | salt/modules/mac_shadow.py | del_password | def del_password(name):
'''
Deletes the account password
:param str name: The user name of the account
:return: True if successful, otherwise False
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.del_password username
'''
# This removes the password
cmd = "dscl . -passwd /Users/{0} ''".format(name)
try:
salt.utils.mac_utils.execute_return_success(cmd)
except CommandExecutionError as exc:
if 'eDSUnknownNodeName' in exc.strerror:
raise CommandExecutionError('User not found: {0}'.format(name))
raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))
# This is so it looks right in shadow.info
cmd = "dscl . -create /Users/{0} Password '*'".format(name)
salt.utils.mac_utils.execute_return_success(cmd)
return info(name)['passwd'] == '*' | python | def del_password(name):
'''
Deletes the account password
:param str name: The user name of the account
:return: True if successful, otherwise False
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.del_password username
'''
# This removes the password
cmd = "dscl . -passwd /Users/{0} ''".format(name)
try:
salt.utils.mac_utils.execute_return_success(cmd)
except CommandExecutionError as exc:
if 'eDSUnknownNodeName' in exc.strerror:
raise CommandExecutionError('User not found: {0}'.format(name))
raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))
# This is so it looks right in shadow.info
cmd = "dscl . -create /Users/{0} Password '*'".format(name)
salt.utils.mac_utils.execute_return_success(cmd)
return info(name)['passwd'] == '*' | [
"def",
"del_password",
"(",
"name",
")",
":",
"# This removes the password",
"cmd",
"=",
"\"dscl . -passwd /Users/{0} ''\"",
".",
"format",
"(",
"name",
")",
"try",
":",
"salt",
".",
"utils",
".",
"mac_utils",
".",
"execute_return_success",
"(",
"cmd",
")",
"exc... | Deletes the account password
:param str name: The user name of the account
:return: True if successful, otherwise False
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.del_password username | [
"Deletes",
"the",
"account",
"password"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_shadow.py#L506-L536 | train |
saltstack/salt | salt/modules/mac_shadow.py | set_password | def set_password(name, password):
'''
Set the password for a named user (insecure, the password will be in the
process list while the command is running)
:param str name: The name of the local user, which is assumed to be in the
local directory service
:param str password: The plaintext password to set
:return: True if successful, otherwise False
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' mac_shadow.set_password macuser macpassword
'''
cmd = "dscl . -passwd /Users/{0} '{1}'".format(name, password)
try:
salt.utils.mac_utils.execute_return_success(cmd)
except CommandExecutionError as exc:
if 'eDSUnknownNodeName' in exc.strerror:
raise CommandExecutionError('User not found: {0}'.format(name))
raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))
return True | python | def set_password(name, password):
'''
Set the password for a named user (insecure, the password will be in the
process list while the command is running)
:param str name: The name of the local user, which is assumed to be in the
local directory service
:param str password: The plaintext password to set
:return: True if successful, otherwise False
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' mac_shadow.set_password macuser macpassword
'''
cmd = "dscl . -passwd /Users/{0} '{1}'".format(name, password)
try:
salt.utils.mac_utils.execute_return_success(cmd)
except CommandExecutionError as exc:
if 'eDSUnknownNodeName' in exc.strerror:
raise CommandExecutionError('User not found: {0}'.format(name))
raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))
return True | [
"def",
"set_password",
"(",
"name",
",",
"password",
")",
":",
"cmd",
"=",
"\"dscl . -passwd /Users/{0} '{1}'\"",
".",
"format",
"(",
"name",
",",
"password",
")",
"try",
":",
"salt",
".",
"utils",
".",
"mac_utils",
".",
"execute_return_success",
"(",
"cmd",
... | Set the password for a named user (insecure, the password will be in the
process list while the command is running)
:param str name: The name of the local user, which is assumed to be in the
local directory service
:param str password: The plaintext password to set
:return: True if successful, otherwise False
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' mac_shadow.set_password macuser macpassword | [
"Set",
"the",
"password",
"for",
"a",
"named",
"user",
"(",
"insecure",
"the",
"password",
"will",
"be",
"in",
"the",
"process",
"list",
"while",
"the",
"command",
"is",
"running",
")"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_shadow.py#L539-L568 | train |
saltstack/salt | salt/states/rabbitmq_policy.py | present | def present(name,
pattern,
definition,
priority=0,
vhost='/',
runas=None,
apply_to=None):
'''
Ensure the RabbitMQ policy exists.
Reference: http://www.rabbitmq.com/ha.html
name
Policy name
pattern
A regex of queues to apply the policy to
definition
A json dict describing the policy
priority
Priority (defaults to 0)
vhost
Virtual host to apply to (defaults to '/')
runas
Name of the user to run the command as
apply_to
Apply policy to 'queues', 'exchanges' or 'all' (default to 'all')
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
result = {}
policies = __salt__['rabbitmq.list_policies'](vhost=vhost, runas=runas)
policy = policies.get(vhost, {}).get(name)
updates = []
if policy:
if policy.get('pattern') != pattern:
updates.append('Pattern')
current_definition = policy.get('definition')
current_definition = json.loads(current_definition) if current_definition else ''
new_definition = json.loads(definition) if definition else ''
if current_definition != new_definition:
updates.append('Definition')
if apply_to and (policy.get('apply-to') != apply_to):
updates.append('Applyto')
if int(policy.get('priority')) != priority:
updates.append('Priority')
if policy and not updates:
ret['comment'] = 'Policy {0} {1} is already present'.format(vhost, name)
return ret
if not policy:
ret['changes'].update({'old': {}, 'new': name})
if __opts__['test']:
ret['comment'] = 'Policy {0} {1} is set to be created'.format(vhost, name)
else:
log.debug('Policy doesn\'t exist - Creating')
result = __salt__['rabbitmq.set_policy'](vhost,
name,
pattern,
definition,
priority=priority,
runas=runas,
apply_to=apply_to)
elif updates:
ret['changes'].update({'old': policy, 'new': updates})
if __opts__['test']:
ret['comment'] = 'Policy {0} {1} is set to be updated'.format(vhost, name)
else:
log.debug('Policy exists but needs updating')
result = __salt__['rabbitmq.set_policy'](vhost,
name,
pattern,
definition,
priority=priority,
runas=runas,
apply_to=apply_to)
if 'Error' in result:
ret['result'] = False
ret['comment'] = result['Error']
elif ret['changes'] == {}:
ret['comment'] = '\'{0}\' is already in the desired state.'.format(name)
elif __opts__['test']:
ret['result'] = None
elif 'Set' in result:
ret['comment'] = result['Set']
return ret | python | def present(name,
pattern,
definition,
priority=0,
vhost='/',
runas=None,
apply_to=None):
'''
Ensure the RabbitMQ policy exists.
Reference: http://www.rabbitmq.com/ha.html
name
Policy name
pattern
A regex of queues to apply the policy to
definition
A json dict describing the policy
priority
Priority (defaults to 0)
vhost
Virtual host to apply to (defaults to '/')
runas
Name of the user to run the command as
apply_to
Apply policy to 'queues', 'exchanges' or 'all' (default to 'all')
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
result = {}
policies = __salt__['rabbitmq.list_policies'](vhost=vhost, runas=runas)
policy = policies.get(vhost, {}).get(name)
updates = []
if policy:
if policy.get('pattern') != pattern:
updates.append('Pattern')
current_definition = policy.get('definition')
current_definition = json.loads(current_definition) if current_definition else ''
new_definition = json.loads(definition) if definition else ''
if current_definition != new_definition:
updates.append('Definition')
if apply_to and (policy.get('apply-to') != apply_to):
updates.append('Applyto')
if int(policy.get('priority')) != priority:
updates.append('Priority')
if policy and not updates:
ret['comment'] = 'Policy {0} {1} is already present'.format(vhost, name)
return ret
if not policy:
ret['changes'].update({'old': {}, 'new': name})
if __opts__['test']:
ret['comment'] = 'Policy {0} {1} is set to be created'.format(vhost, name)
else:
log.debug('Policy doesn\'t exist - Creating')
result = __salt__['rabbitmq.set_policy'](vhost,
name,
pattern,
definition,
priority=priority,
runas=runas,
apply_to=apply_to)
elif updates:
ret['changes'].update({'old': policy, 'new': updates})
if __opts__['test']:
ret['comment'] = 'Policy {0} {1} is set to be updated'.format(vhost, name)
else:
log.debug('Policy exists but needs updating')
result = __salt__['rabbitmq.set_policy'](vhost,
name,
pattern,
definition,
priority=priority,
runas=runas,
apply_to=apply_to)
if 'Error' in result:
ret['result'] = False
ret['comment'] = result['Error']
elif ret['changes'] == {}:
ret['comment'] = '\'{0}\' is already in the desired state.'.format(name)
elif __opts__['test']:
ret['result'] = None
elif 'Set' in result:
ret['comment'] = result['Set']
return ret | [
"def",
"present",
"(",
"name",
",",
"pattern",
",",
"definition",
",",
"priority",
"=",
"0",
",",
"vhost",
"=",
"'/'",
",",
"runas",
"=",
"None",
",",
"apply_to",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
... | Ensure the RabbitMQ policy exists.
Reference: http://www.rabbitmq.com/ha.html
name
Policy name
pattern
A regex of queues to apply the policy to
definition
A json dict describing the policy
priority
Priority (defaults to 0)
vhost
Virtual host to apply to (defaults to '/')
runas
Name of the user to run the command as
apply_to
Apply policy to 'queues', 'exchanges' or 'all' (default to 'all') | [
"Ensure",
"the",
"RabbitMQ",
"policy",
"exists",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/rabbitmq_policy.py#L37-L124 | train |
saltstack/salt | salt/states/rabbitmq_policy.py | absent | def absent(name,
vhost='/',
runas=None):
'''
Ensure the named policy is absent
Reference: http://www.rabbitmq.com/ha.html
name
The name of the policy to remove
runas
Name of the user to run the command as
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
policy_exists = __salt__['rabbitmq.policy_exists'](
vhost, name, runas=runas)
if not policy_exists:
ret['comment'] = 'Policy \'{0} {1}\' is not present.'.format(vhost, name)
return ret
if not __opts__['test']:
result = __salt__['rabbitmq.delete_policy'](vhost, name, runas=runas)
if 'Error' in result:
ret['result'] = False
ret['comment'] = result['Error']
return ret
elif 'Deleted' in result:
ret['comment'] = 'Deleted'
# If we've reached this far before returning, we have changes.
ret['changes'] = {'new': '', 'old': name}
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Policy \'{0} {1}\' will be removed.'.format(vhost, name)
return ret | python | def absent(name,
vhost='/',
runas=None):
'''
Ensure the named policy is absent
Reference: http://www.rabbitmq.com/ha.html
name
The name of the policy to remove
runas
Name of the user to run the command as
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
policy_exists = __salt__['rabbitmq.policy_exists'](
vhost, name, runas=runas)
if not policy_exists:
ret['comment'] = 'Policy \'{0} {1}\' is not present.'.format(vhost, name)
return ret
if not __opts__['test']:
result = __salt__['rabbitmq.delete_policy'](vhost, name, runas=runas)
if 'Error' in result:
ret['result'] = False
ret['comment'] = result['Error']
return ret
elif 'Deleted' in result:
ret['comment'] = 'Deleted'
# If we've reached this far before returning, we have changes.
ret['changes'] = {'new': '', 'old': name}
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Policy \'{0} {1}\' will be removed.'.format(vhost, name)
return ret | [
"def",
"absent",
"(",
"name",
",",
"vhost",
"=",
"'/'",
",",
"runas",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",
"''",
",",
"'changes'",
":",
"{",
"}",
"}",
"policy_exists",
... | Ensure the named policy is absent
Reference: http://www.rabbitmq.com/ha.html
name
The name of the policy to remove
runas
Name of the user to run the command as | [
"Ensure",
"the",
"named",
"policy",
"is",
"absent"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/rabbitmq_policy.py#L127-L165 | train |
saltstack/salt | salt/cloud/clouds/openstack.py | get_configured_provider | def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__, __active_provider_name__ or __virtualname__,
('auth', 'region_name'), log_message=False,
) or config.is_provider_configured(
__opts__, __active_provider_name__ or __virtualname__,
('cloud', 'region_name')
) | python | def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__, __active_provider_name__ or __virtualname__,
('auth', 'region_name'), log_message=False,
) or config.is_provider_configured(
__opts__, __active_provider_name__ or __virtualname__,
('cloud', 'region_name')
) | [
"def",
"get_configured_provider",
"(",
")",
":",
"return",
"config",
".",
"is_provider_configured",
"(",
"__opts__",
",",
"__active_provider_name__",
"or",
"__virtualname__",
",",
"(",
"'auth'",
",",
"'region_name'",
")",
",",
"log_message",
"=",
"False",
",",
")"... | Return the first configured instance. | [
"Return",
"the",
"first",
"configured",
"instance",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/openstack.py#L259-L269 | train |
saltstack/salt | salt/cloud/clouds/openstack.py | preferred_ip | def preferred_ip(vm_, ips):
'''
Return the preferred Internet protocol. Either 'ipv4' (default) or 'ipv6'.
'''
proto = config.get_cloud_config_value(
'protocol', vm_, __opts__, default='ipv4', search_global=False
)
family = socket.AF_INET
if proto == 'ipv6':
family = socket.AF_INET6
for ip in ips:
try:
socket.inet_pton(family, ip)
return ip
except Exception:
continue
return False | python | def preferred_ip(vm_, ips):
'''
Return the preferred Internet protocol. Either 'ipv4' (default) or 'ipv6'.
'''
proto = config.get_cloud_config_value(
'protocol', vm_, __opts__, default='ipv4', search_global=False
)
family = socket.AF_INET
if proto == 'ipv6':
family = socket.AF_INET6
for ip in ips:
try:
socket.inet_pton(family, ip)
return ip
except Exception:
continue
return False | [
"def",
"preferred_ip",
"(",
"vm_",
",",
"ips",
")",
":",
"proto",
"=",
"config",
".",
"get_cloud_config_value",
"(",
"'protocol'",
",",
"vm_",
",",
"__opts__",
",",
"default",
"=",
"'ipv4'",
",",
"search_global",
"=",
"False",
")",
"family",
"=",
"socket",... | Return the preferred Internet protocol. Either 'ipv4' (default) or 'ipv6'. | [
"Return",
"the",
"preferred",
"Internet",
"protocol",
".",
"Either",
"ipv4",
"(",
"default",
")",
"or",
"ipv6",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/openstack.py#L286-L303 | train |
saltstack/salt | salt/cloud/clouds/openstack.py | get_conn | def get_conn():
'''
Return a conn object for the passed VM data
'''
if __active_provider_name__ in __context__:
return __context__[__active_provider_name__]
vm_ = get_configured_provider()
profile = vm_.pop('profile', None)
if profile is not None:
vm_ = __utils__['dictupdate.update'](os_client_config.vendors.get_profile(profile), vm_)
conn = shade.openstackcloud.OpenStackCloud(cloud_config=None, **vm_)
if __active_provider_name__ is not None:
__context__[__active_provider_name__] = conn
return conn | python | def get_conn():
'''
Return a conn object for the passed VM data
'''
if __active_provider_name__ in __context__:
return __context__[__active_provider_name__]
vm_ = get_configured_provider()
profile = vm_.pop('profile', None)
if profile is not None:
vm_ = __utils__['dictupdate.update'](os_client_config.vendors.get_profile(profile), vm_)
conn = shade.openstackcloud.OpenStackCloud(cloud_config=None, **vm_)
if __active_provider_name__ is not None:
__context__[__active_provider_name__] = conn
return conn | [
"def",
"get_conn",
"(",
")",
":",
"if",
"__active_provider_name__",
"in",
"__context__",
":",
"return",
"__context__",
"[",
"__active_provider_name__",
"]",
"vm_",
"=",
"get_configured_provider",
"(",
")",
"profile",
"=",
"vm_",
".",
"pop",
"(",
"'profile'",
","... | 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/openstack.py#L314-L327 | train |
saltstack/salt | salt/cloud/clouds/openstack.py | list_nodes | def list_nodes(conn=None, call=None):
'''
Return a list of VMs
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
for node, info in list_nodes_full(conn=conn).items():
for key in ('id', 'name', 'size', 'state', 'private_ips', 'public_ips', 'floating_ips', 'fixed_ips', 'image'):
ret.setdefault(node, {}).setdefault(key, info.get(key))
return ret | python | def list_nodes(conn=None, call=None):
'''
Return a list of VMs
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
for node, info in list_nodes_full(conn=conn).items():
for key in ('id', 'name', 'size', 'state', 'private_ips', 'public_ips', 'floating_ips', 'fixed_ips', 'image'):
ret.setdefault(node, {}).setdefault(key, info.get(key))
return ret | [
"def",
"list_nodes",
"(",
"conn",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"==",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The list_nodes function must be called with -f or --function.'",
")",
"ret",
"=",
"{",
"}",
"for",
"nod... | Return a list of VMs
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes myopenstack | [
"Return",
"a",
"list",
"of",
"VMs"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/openstack.py#L330-L350 | train |
saltstack/salt | salt/cloud/clouds/openstack.py | list_nodes_min | def list_nodes_min(conn=None, call=None):
'''
Return a list of VMs with minimal information
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes_min myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_min function must be called with -f or --function.'
)
if conn is None:
conn = get_conn()
ret = {}
for node in conn.list_servers(bare=True):
ret[node.name] = {'id': node.id, 'state': node.status}
return ret | python | def list_nodes_min(conn=None, call=None):
'''
Return a list of VMs with minimal information
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes_min myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_min function must be called with -f or --function.'
)
if conn is None:
conn = get_conn()
ret = {}
for node in conn.list_servers(bare=True):
ret[node.name] = {'id': node.id, 'state': node.status}
return ret | [
"def",
"list_nodes_min",
"(",
"conn",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"==",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The list_nodes_min function must be called with -f or --function.'",
")",
"if",
"conn",
"is",
"None",
... | Return a list of VMs with minimal information
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes_min myopenstack | [
"Return",
"a",
"list",
"of",
"VMs",
"with",
"minimal",
"information"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/openstack.py#L353-L373 | train |
saltstack/salt | salt/cloud/clouds/openstack.py | list_nodes_full | def list_nodes_full(conn=None, call=None):
'''
Return a list of VMs with all the information about them
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes_full myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if conn is None:
conn = get_conn()
ret = {}
for node in conn.list_servers(detailed=True):
ret[node.name] = dict(node)
ret[node.name]['id'] = node.id
ret[node.name]['name'] = node.name
ret[node.name]['size'] = node.flavor.name
ret[node.name]['state'] = node.status
ret[node.name]['private_ips'] = _get_ips(node, 'private')
ret[node.name]['public_ips'] = _get_ips(node, 'public')
ret[node.name]['floating_ips'] = _get_ips(node, 'floating')
ret[node.name]['fixed_ips'] = _get_ips(node, 'fixed')
ret[node.name]['image'] = node.image.name
return ret | python | def list_nodes_full(conn=None, call=None):
'''
Return a list of VMs with all the information about them
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes_full myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if conn is None:
conn = get_conn()
ret = {}
for node in conn.list_servers(detailed=True):
ret[node.name] = dict(node)
ret[node.name]['id'] = node.id
ret[node.name]['name'] = node.name
ret[node.name]['size'] = node.flavor.name
ret[node.name]['state'] = node.status
ret[node.name]['private_ips'] = _get_ips(node, 'private')
ret[node.name]['public_ips'] = _get_ips(node, 'public')
ret[node.name]['floating_ips'] = _get_ips(node, 'floating')
ret[node.name]['fixed_ips'] = _get_ips(node, 'fixed')
ret[node.name]['image'] = node.image.name
return ret | [
"def",
"list_nodes_full",
"(",
"conn",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"==",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The list_nodes_full function must be called with -f or --function.'",
")",
"if",
"conn",
"is",
"None",... | Return a list of VMs with all the information about them
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes_full myopenstack | [
"Return",
"a",
"list",
"of",
"VMs",
"with",
"all",
"the",
"information",
"about",
"them"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/openstack.py#L389-L418 | train |
saltstack/salt | salt/cloud/clouds/openstack.py | list_nodes_select | def list_nodes_select(conn=None, call=None):
'''
Return a list of VMs with the fields from `query.selection`
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes_full myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_select function must be called with -f or --function.'
)
return __utils__['cloud.list_nodes_select'](
list_nodes(conn, 'function'), __opts__['query.selection'], call,
) | python | def list_nodes_select(conn=None, call=None):
'''
Return a list of VMs with the fields from `query.selection`
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes_full myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_select function must be called with -f or --function.'
)
return __utils__['cloud.list_nodes_select'](
list_nodes(conn, 'function'), __opts__['query.selection'], call,
) | [
"def",
"list_nodes_select",
"(",
"conn",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"==",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The list_nodes_select function must be called with -f or --function.'",
")",
"return",
"__utils__",
"[... | Return a list of VMs with the fields from `query.selection`
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes_full myopenstack | [
"Return",
"a",
"list",
"of",
"VMs",
"with",
"the",
"fields",
"from",
"query",
".",
"selection"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/openstack.py#L421-L438 | train |
saltstack/salt | salt/cloud/clouds/openstack.py | show_instance | def show_instance(name, conn=None, call=None):
'''
Get VM on this OpenStack account
name
name of the instance
CLI Example
.. code-block:: bash
salt-cloud -a show_instance myserver
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
if conn is None:
conn = get_conn()
node = conn.get_server(name, bare=True)
ret = dict(node)
ret['id'] = node.id
ret['name'] = node.name
ret['size'] = conn.get_flavor(node.flavor.id).name
ret['state'] = node.status
ret['private_ips'] = _get_ips(node, 'private')
ret['public_ips'] = _get_ips(node, 'public')
ret['floating_ips'] = _get_ips(node, 'floating')
ret['fixed_ips'] = _get_ips(node, 'fixed')
if isinstance(node.image, six.string_types):
ret['image'] = node.image
else:
ret['image'] = conn.get_image(node.image.id).name
return ret | python | def show_instance(name, conn=None, call=None):
'''
Get VM on this OpenStack account
name
name of the instance
CLI Example
.. code-block:: bash
salt-cloud -a show_instance myserver
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
if conn is None:
conn = get_conn()
node = conn.get_server(name, bare=True)
ret = dict(node)
ret['id'] = node.id
ret['name'] = node.name
ret['size'] = conn.get_flavor(node.flavor.id).name
ret['state'] = node.status
ret['private_ips'] = _get_ips(node, 'private')
ret['public_ips'] = _get_ips(node, 'public')
ret['floating_ips'] = _get_ips(node, 'floating')
ret['fixed_ips'] = _get_ips(node, 'fixed')
if isinstance(node.image, six.string_types):
ret['image'] = node.image
else:
ret['image'] = conn.get_image(node.image.id).name
return ret | [
"def",
"show_instance",
"(",
"name",
",",
"conn",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The show_instance action must be called with -a or --action.'",
")",
"if",
"conn",
"is",
... | Get VM on this OpenStack account
name
name of the instance
CLI Example
.. code-block:: bash
salt-cloud -a show_instance myserver | [
"Get",
"VM",
"on",
"this",
"OpenStack",
"account"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/openstack.py#L441-L477 | train |
saltstack/salt | salt/cloud/clouds/openstack.py | avail_images | def avail_images(conn=None, call=None):
'''
List available images for OpenStack
CLI Example
.. code-block:: bash
salt-cloud -f avail_images myopenstack
salt-cloud --list-images myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if conn is None:
conn = get_conn()
return conn.list_images() | python | def avail_images(conn=None, call=None):
'''
List available images for OpenStack
CLI Example
.. code-block:: bash
salt-cloud -f avail_images myopenstack
salt-cloud --list-images myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if conn is None:
conn = get_conn()
return conn.list_images() | [
"def",
"avail_images",
"(",
"conn",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"==",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The avail_images function must be called with '",
"'-f or --function, or with the --list-images option'",
")",
... | List available images for OpenStack
CLI Example
.. code-block:: bash
salt-cloud -f avail_images myopenstack
salt-cloud --list-images myopenstack | [
"List",
"available",
"images",
"for",
"OpenStack"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/openstack.py#L480-L499 | train |
saltstack/salt | salt/cloud/clouds/openstack.py | avail_sizes | def avail_sizes(conn=None, call=None):
'''
List available sizes for OpenStack
CLI Example
.. code-block:: bash
salt-cloud -f avail_sizes myopenstack
salt-cloud --list-sizes myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
if conn is None:
conn = get_conn()
return conn.list_flavors() | python | def avail_sizes(conn=None, call=None):
'''
List available sizes for OpenStack
CLI Example
.. code-block:: bash
salt-cloud -f avail_sizes myopenstack
salt-cloud --list-sizes myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
if conn is None:
conn = get_conn()
return conn.list_flavors() | [
"def",
"avail_sizes",
"(",
"conn",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"==",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The avail_sizes function must be called with '",
"'-f or --function, or with the --list-sizes option'",
")",
"... | List available sizes for OpenStack
CLI Example
.. code-block:: bash
salt-cloud -f avail_sizes myopenstack
salt-cloud --list-sizes myopenstack | [
"List",
"available",
"sizes",
"for",
"OpenStack"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/openstack.py#L502-L521 | train |
saltstack/salt | salt/cloud/clouds/openstack.py | list_networks | def list_networks(conn=None, call=None):
'''
List networks for OpenStack
CLI Example
.. code-block:: bash
salt-cloud -f list_networks myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_networks function must be called with '
'-f or --function'
)
if conn is None:
conn = get_conn()
return conn.list_networks() | python | def list_networks(conn=None, call=None):
'''
List networks for OpenStack
CLI Example
.. code-block:: bash
salt-cloud -f list_networks myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_networks function must be called with '
'-f or --function'
)
if conn is None:
conn = get_conn()
return conn.list_networks() | [
"def",
"list_networks",
"(",
"conn",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"==",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The list_networks function must be called with '",
"'-f or --function'",
")",
"if",
"conn",
"is",
"Non... | List networks for OpenStack
CLI Example
.. code-block:: bash
salt-cloud -f list_networks myopenstack | [
"List",
"networks",
"for",
"OpenStack"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/openstack.py#L524-L542 | train |
saltstack/salt | salt/cloud/clouds/openstack.py | list_subnets | def list_subnets(conn=None, call=None, kwargs=None):
'''
List subnets in a virtual network
network
network to list subnets of
.. code-block:: bash
salt-cloud -f list_subnets myopenstack network=salt-net
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_subnets function must be called with '
'-f or --function.'
)
if conn is None:
conn = get_conn()
if kwargs is None or (isinstance(kwargs, dict) and 'network' not in kwargs):
raise SaltCloudSystemExit(
'A `network` must be specified'
)
return conn.list_subnets(filters={'network': kwargs['network']}) | python | def list_subnets(conn=None, call=None, kwargs=None):
'''
List subnets in a virtual network
network
network to list subnets of
.. code-block:: bash
salt-cloud -f list_subnets myopenstack network=salt-net
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_subnets function must be called with '
'-f or --function.'
)
if conn is None:
conn = get_conn()
if kwargs is None or (isinstance(kwargs, dict) and 'network' not in kwargs):
raise SaltCloudSystemExit(
'A `network` must be specified'
)
return conn.list_subnets(filters={'network': kwargs['network']}) | [
"def",
"list_subnets",
"(",
"conn",
"=",
"None",
",",
"call",
"=",
"None",
",",
"kwargs",
"=",
"None",
")",
":",
"if",
"call",
"==",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The list_subnets function must be called with '",
"'-f or --function.'",
")... | List subnets in a virtual network
network
network to list subnets of
.. code-block:: bash
salt-cloud -f list_subnets myopenstack network=salt-net | [
"List",
"subnets",
"in",
"a",
"virtual",
"network"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/openstack.py#L545-L568 | train |
saltstack/salt | salt/cloud/clouds/openstack.py | _clean_create_kwargs | def _clean_create_kwargs(**kwargs):
'''
Sanatize kwargs to be sent to create_server
'''
VALID_OPTS = {
'name': six.string_types,
'image': six.string_types,
'flavor': six.string_types,
'auto_ip': bool,
'ips': list,
'ip_pool': six.string_types,
'root_volume': six.string_types,
'boot_volume': six.string_types,
'terminate_volume': bool,
'volumes': list,
'meta': dict,
'files': dict,
'reservation_id': six.string_types,
'security_groups': list,
'key_name': six.string_types,
'availability_zone': six.string_types,
'block_device_mapping': dict,
'block_device_mapping_v2': dict,
'nics': list,
'scheduler_hints': dict,
'config_drive': bool,
'disk_config': six.string_types, # AUTO or MANUAL
'admin_pass': six.string_types,
'wait': bool,
'timeout': int,
'reuse_ips': bool,
'network': dict,
'boot_from_volume': bool,
'volume_size': int,
'nat_destination': six.string_types,
'group': six.string_types,
'userdata': six.string_types,
}
extra = kwargs.pop('extra', {})
for key, value in six.iteritems(kwargs.copy()):
if key in VALID_OPTS:
if isinstance(value, VALID_OPTS[key]):
continue
log.error('Error %s: %s is not of type %s', key, value, VALID_OPTS[key])
kwargs.pop(key)
return __utils__['dictupdate.update'](kwargs, extra) | python | def _clean_create_kwargs(**kwargs):
'''
Sanatize kwargs to be sent to create_server
'''
VALID_OPTS = {
'name': six.string_types,
'image': six.string_types,
'flavor': six.string_types,
'auto_ip': bool,
'ips': list,
'ip_pool': six.string_types,
'root_volume': six.string_types,
'boot_volume': six.string_types,
'terminate_volume': bool,
'volumes': list,
'meta': dict,
'files': dict,
'reservation_id': six.string_types,
'security_groups': list,
'key_name': six.string_types,
'availability_zone': six.string_types,
'block_device_mapping': dict,
'block_device_mapping_v2': dict,
'nics': list,
'scheduler_hints': dict,
'config_drive': bool,
'disk_config': six.string_types, # AUTO or MANUAL
'admin_pass': six.string_types,
'wait': bool,
'timeout': int,
'reuse_ips': bool,
'network': dict,
'boot_from_volume': bool,
'volume_size': int,
'nat_destination': six.string_types,
'group': six.string_types,
'userdata': six.string_types,
}
extra = kwargs.pop('extra', {})
for key, value in six.iteritems(kwargs.copy()):
if key in VALID_OPTS:
if isinstance(value, VALID_OPTS[key]):
continue
log.error('Error %s: %s is not of type %s', key, value, VALID_OPTS[key])
kwargs.pop(key)
return __utils__['dictupdate.update'](kwargs, extra) | [
"def",
"_clean_create_kwargs",
"(",
"*",
"*",
"kwargs",
")",
":",
"VALID_OPTS",
"=",
"{",
"'name'",
":",
"six",
".",
"string_types",
",",
"'image'",
":",
"six",
".",
"string_types",
",",
"'flavor'",
":",
"six",
".",
"string_types",
",",
"'auto_ip'",
":",
... | Sanatize kwargs to be sent to create_server | [
"Sanatize",
"kwargs",
"to",
"be",
"sent",
"to",
"create_server"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/openstack.py#L571-L616 | train |
saltstack/salt | salt/cloud/clouds/openstack.py | request_instance | def request_instance(vm_, conn=None, call=None):
'''
Request an instance to be built
'''
if call == 'function':
# Technically this function may be called other ways too, but it
# definitely cannot be called with --function.
raise SaltCloudSystemExit(
'The request_instance action must be called with -a or --action.'
)
kwargs = copy.deepcopy(vm_)
log.info('Creating Cloud VM %s', vm_['name'])
__utils__['cloud.check_name'](vm_['name'], 'a-zA-Z0-9._-')
conn = get_conn()
userdata = config.get_cloud_config_value(
'userdata', vm_, __opts__, search_global=False, default=None
)
if userdata is not None and os.path.isfile(userdata):
try:
with __utils__['files.fopen'](userdata, 'r') as fp_:
kwargs['userdata'] = __utils__['cloud.userdata_template'](
__opts__, vm_, fp_.read()
)
except Exception as exc:
log.exception(
'Failed to read userdata from %s: %s', userdata, exc)
if 'size' in kwargs:
kwargs['flavor'] = kwargs.pop('size')
kwargs['key_name'] = config.get_cloud_config_value(
'ssh_key_name', vm_, __opts__, search_global=False, default=None
)
kwargs['wait'] = True
try:
conn.create_server(**_clean_create_kwargs(**kwargs))
except shade.exc.OpenStackCloudException as exc:
log.error('Error creating server %s: %s', vm_['name'], exc)
destroy(vm_['name'], conn=conn, call='action')
raise SaltCloudSystemExit(six.text_type(exc))
return show_instance(vm_['name'], conn=conn, call='action') | python | def request_instance(vm_, conn=None, call=None):
'''
Request an instance to be built
'''
if call == 'function':
# Technically this function may be called other ways too, but it
# definitely cannot be called with --function.
raise SaltCloudSystemExit(
'The request_instance action must be called with -a or --action.'
)
kwargs = copy.deepcopy(vm_)
log.info('Creating Cloud VM %s', vm_['name'])
__utils__['cloud.check_name'](vm_['name'], 'a-zA-Z0-9._-')
conn = get_conn()
userdata = config.get_cloud_config_value(
'userdata', vm_, __opts__, search_global=False, default=None
)
if userdata is not None and os.path.isfile(userdata):
try:
with __utils__['files.fopen'](userdata, 'r') as fp_:
kwargs['userdata'] = __utils__['cloud.userdata_template'](
__opts__, vm_, fp_.read()
)
except Exception as exc:
log.exception(
'Failed to read userdata from %s: %s', userdata, exc)
if 'size' in kwargs:
kwargs['flavor'] = kwargs.pop('size')
kwargs['key_name'] = config.get_cloud_config_value(
'ssh_key_name', vm_, __opts__, search_global=False, default=None
)
kwargs['wait'] = True
try:
conn.create_server(**_clean_create_kwargs(**kwargs))
except shade.exc.OpenStackCloudException as exc:
log.error('Error creating server %s: %s', vm_['name'], exc)
destroy(vm_['name'], conn=conn, call='action')
raise SaltCloudSystemExit(six.text_type(exc))
return show_instance(vm_['name'], conn=conn, call='action') | [
"def",
"request_instance",
"(",
"vm_",
",",
"conn",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"==",
"'function'",
":",
"# Technically this function may be called other ways too, but it",
"# definitely cannot be called with --function.",
"raise",
"Salt... | Request an instance to be built | [
"Request",
"an",
"instance",
"to",
"be",
"built"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/openstack.py#L619-L658 | train |
saltstack/salt | salt/cloud/clouds/openstack.py | create | def create(vm_):
'''
Create a single VM from a data dict
'''
deploy = config.get_cloud_config_value('deploy', vm_, __opts__)
key_filename = config.get_cloud_config_value(
'ssh_key_file', vm_, __opts__, search_global=False, default=None
)
if key_filename is not None and not os.path.isfile(key_filename):
raise SaltCloudConfigError(
'The defined ssh_key_file \'{0}\' does not exist'.format(
key_filename
)
)
vm_['key_filename'] = key_filename
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
conn = get_conn()
if 'instance_id' in vm_:
# This was probably created via another process, and doesn't have
# things like salt keys created yet, so let's create them now.
if 'pub_key' not in vm_ and 'priv_key' not in vm_:
log.debug('Generating minion keys for \'%s\'', vm_['name'])
vm_['priv_key'], vm_['pub_key'] = __utils__['cloud.gen_keys'](
config.get_cloud_config_value(
'keysize',
vm_,
__opts__
)
)
else:
# Put together all of the information required to request the instance,
# and then fire off the request for it
request_instance(conn=conn, call='action', vm_=vm_)
data = show_instance(vm_.get('instance_id', vm_['name']), conn=conn, call='action')
log.debug('VM is now running')
def __query_node(vm_):
data = show_instance(vm_['name'], conn=conn, call='action')
if 'wait_for_metadata' in vm_:
for key, value in six.iteritems(vm_.get('wait_for_metadata', {})):
log.debug('Waiting for metadata: %s=%s', key, value)
if data['metadata'].get(key, None) != value:
log.debug('Metadata is not ready: %s=%s', key, data['metadata'].get(key))
return False
return preferred_ip(vm_, data[ssh_interface(vm_)])
try:
ip_address = __utils__['cloud.wait_for_fun'](
__query_node,
vm_=vm_
)
except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
try:
# It might be already up, let's destroy it!
destroy(vm_['name'])
except SaltCloudSystemExit:
pass
finally:
raise SaltCloudSystemExit(six.text_type(exc))
log.debug('Using IP address %s', ip_address)
salt_interface = __utils__['cloud.get_salt_interface'](vm_, __opts__)
salt_ip_address = preferred_ip(vm_, data[salt_interface])
log.debug('Salt interface set to: %s', salt_ip_address)
if not ip_address:
raise SaltCloudSystemExit('A valid IP address was not found')
vm_['ssh_host'] = ip_address
vm_['salt_host'] = salt_ip_address
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
ret.update(data)
log.info('Created Cloud VM \'%s\'', vm_['name'])
log.debug(
'\'%s\' VM creation details:\n%s',
vm_['name'], pprint.pformat(data)
)
event_data = {
'name': vm_['name'],
'profile': vm_['profile'],
'provider': vm_['driver'],
'instance_id': data['id'],
'floating_ips': data['floating_ips'],
'fixed_ips': data['fixed_ips'],
'private_ips': data['private_ips'],
'public_ips': data['public_ips'],
}
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', event_data, list(event_data)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
__utils__['cloud.cachedir_index_add'](vm_['name'], vm_['profile'], 'nova', vm_['driver'])
return ret | python | def create(vm_):
'''
Create a single VM from a data dict
'''
deploy = config.get_cloud_config_value('deploy', vm_, __opts__)
key_filename = config.get_cloud_config_value(
'ssh_key_file', vm_, __opts__, search_global=False, default=None
)
if key_filename is not None and not os.path.isfile(key_filename):
raise SaltCloudConfigError(
'The defined ssh_key_file \'{0}\' does not exist'.format(
key_filename
)
)
vm_['key_filename'] = key_filename
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
conn = get_conn()
if 'instance_id' in vm_:
# This was probably created via another process, and doesn't have
# things like salt keys created yet, so let's create them now.
if 'pub_key' not in vm_ and 'priv_key' not in vm_:
log.debug('Generating minion keys for \'%s\'', vm_['name'])
vm_['priv_key'], vm_['pub_key'] = __utils__['cloud.gen_keys'](
config.get_cloud_config_value(
'keysize',
vm_,
__opts__
)
)
else:
# Put together all of the information required to request the instance,
# and then fire off the request for it
request_instance(conn=conn, call='action', vm_=vm_)
data = show_instance(vm_.get('instance_id', vm_['name']), conn=conn, call='action')
log.debug('VM is now running')
def __query_node(vm_):
data = show_instance(vm_['name'], conn=conn, call='action')
if 'wait_for_metadata' in vm_:
for key, value in six.iteritems(vm_.get('wait_for_metadata', {})):
log.debug('Waiting for metadata: %s=%s', key, value)
if data['metadata'].get(key, None) != value:
log.debug('Metadata is not ready: %s=%s', key, data['metadata'].get(key))
return False
return preferred_ip(vm_, data[ssh_interface(vm_)])
try:
ip_address = __utils__['cloud.wait_for_fun'](
__query_node,
vm_=vm_
)
except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
try:
# It might be already up, let's destroy it!
destroy(vm_['name'])
except SaltCloudSystemExit:
pass
finally:
raise SaltCloudSystemExit(six.text_type(exc))
log.debug('Using IP address %s', ip_address)
salt_interface = __utils__['cloud.get_salt_interface'](vm_, __opts__)
salt_ip_address = preferred_ip(vm_, data[salt_interface])
log.debug('Salt interface set to: %s', salt_ip_address)
if not ip_address:
raise SaltCloudSystemExit('A valid IP address was not found')
vm_['ssh_host'] = ip_address
vm_['salt_host'] = salt_ip_address
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
ret.update(data)
log.info('Created Cloud VM \'%s\'', vm_['name'])
log.debug(
'\'%s\' VM creation details:\n%s',
vm_['name'], pprint.pformat(data)
)
event_data = {
'name': vm_['name'],
'profile': vm_['profile'],
'provider': vm_['driver'],
'instance_id': data['id'],
'floating_ips': data['floating_ips'],
'fixed_ips': data['fixed_ips'],
'private_ips': data['private_ips'],
'public_ips': data['public_ips'],
}
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', event_data, list(event_data)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
__utils__['cloud.cachedir_index_add'](vm_['name'], vm_['profile'], 'nova', vm_['driver'])
return ret | [
"def",
"create",
"(",
"vm_",
")",
":",
"deploy",
"=",
"config",
".",
"get_cloud_config_value",
"(",
"'deploy'",
",",
"vm_",
",",
"__opts__",
")",
"key_filename",
"=",
"config",
".",
"get_cloud_config_value",
"(",
"'ssh_key_file'",
",",
"vm_",
",",
"__opts__",
... | Create a single VM from a data dict | [
"Create",
"a",
"single",
"VM",
"from",
"a",
"data",
"dict"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/openstack.py#L661-L770 | train |
saltstack/salt | salt/cloud/clouds/openstack.py | destroy | def destroy(name, conn=None, call=None):
'''
Delete a single VM
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
__utils__['cloud.fire_event'](
'event',
'destroying instance',
'salt/cloud/{0}/destroying'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
if not conn:
conn = get_conn()
node = show_instance(name, conn=conn, call='action')
log.info('Destroying VM: %s', name)
ret = conn.delete_server(name)
if ret:
log.info('Destroyed VM: %s', name)
# Fire destroy action
__utils__['cloud.fire_event'](
'event',
'destroyed instance',
'salt/cloud/{0}/destroyed'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
if __opts__.get('delete_sshkeys', False) is True:
__utils__['cloud.remove_sshkey'](getattr(node, __opts__.get('ssh_interface', 'public_ips'))[0])
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
__utils__['cloud.cachedir_index_del'](name)
return True
log.error('Failed to Destroy VM: %s', name)
return False | python | def destroy(name, conn=None, call=None):
'''
Delete a single VM
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
__utils__['cloud.fire_event'](
'event',
'destroying instance',
'salt/cloud/{0}/destroying'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
if not conn:
conn = get_conn()
node = show_instance(name, conn=conn, call='action')
log.info('Destroying VM: %s', name)
ret = conn.delete_server(name)
if ret:
log.info('Destroyed VM: %s', name)
# Fire destroy action
__utils__['cloud.fire_event'](
'event',
'destroyed instance',
'salt/cloud/{0}/destroyed'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
if __opts__.get('delete_sshkeys', False) is True:
__utils__['cloud.remove_sshkey'](getattr(node, __opts__.get('ssh_interface', 'public_ips'))[0])
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
__utils__['cloud.cachedir_index_del'](name)
return True
log.error('Failed to Destroy VM: %s', name)
return False | [
"def",
"destroy",
"(",
"name",
",",
"conn",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"==",
"'function'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The destroy action must be called with -d, --destroy, '",
"'-a or --action.'",
")",
"__utils__"... | Delete a single VM | [
"Delete",
"a",
"single",
"VM"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/openstack.py#L773-L816 | train |
saltstack/salt | salt/cloud/clouds/openstack.py | call | def call(conn=None, call=None, kwargs=None):
'''
Call function from shade.
func
function to call from shade.openstackcloud library
CLI Example
.. code-block:: bash
salt-cloud -f call myopenstack func=list_images
t sujksalt-cloud -f call myopenstack func=create_network name=mysubnet
'''
if call == 'action':
raise SaltCloudSystemExit(
'The call function must be called with '
'-f or --function.'
)
if 'func' not in kwargs:
raise SaltCloudSystemExit(
'No `func` argument passed'
)
if conn is None:
conn = get_conn()
func = kwargs.pop('func')
for key, value in kwargs.items():
try:
kwargs[key] = __utils__['json.loads'](value)
except ValueError:
continue
try:
return getattr(conn, func)(**kwargs)
except shade.exc.OpenStackCloudException as exc:
log.error('Error running %s: %s', func, exc)
raise SaltCloudSystemExit(six.text_type(exc)) | python | def call(conn=None, call=None, kwargs=None):
'''
Call function from shade.
func
function to call from shade.openstackcloud library
CLI Example
.. code-block:: bash
salt-cloud -f call myopenstack func=list_images
t sujksalt-cloud -f call myopenstack func=create_network name=mysubnet
'''
if call == 'action':
raise SaltCloudSystemExit(
'The call function must be called with '
'-f or --function.'
)
if 'func' not in kwargs:
raise SaltCloudSystemExit(
'No `func` argument passed'
)
if conn is None:
conn = get_conn()
func = kwargs.pop('func')
for key, value in kwargs.items():
try:
kwargs[key] = __utils__['json.loads'](value)
except ValueError:
continue
try:
return getattr(conn, func)(**kwargs)
except shade.exc.OpenStackCloudException as exc:
log.error('Error running %s: %s', func, exc)
raise SaltCloudSystemExit(six.text_type(exc)) | [
"def",
"call",
"(",
"conn",
"=",
"None",
",",
"call",
"=",
"None",
",",
"kwargs",
"=",
"None",
")",
":",
"if",
"call",
"==",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The call function must be called with '",
"'-f or --function.'",
")",
"if",
"'f... | Call function from shade.
func
function to call from shade.openstackcloud library
CLI Example
.. code-block:: bash
salt-cloud -f call myopenstack func=list_images
t sujksalt-cloud -f call myopenstack func=create_network name=mysubnet | [
"Call",
"function",
"from",
"shade",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/openstack.py#L819-L858 | train |
saltstack/salt | salt/modules/slsutil.py | merge | def merge(obj_a, obj_b, strategy='smart', renderer='yaml', merge_lists=False):
'''
Merge a data structure into another by choosing a merge strategy
Strategies:
* aggregate
* list
* overwrite
* recurse
* smart
CLI Example:
.. code-block:: shell
salt '*' slsutil.merge '{foo: Foo}' '{bar: Bar}'
'''
return salt.utils.dictupdate.merge(obj_a, obj_b, strategy, renderer,
merge_lists) | python | def merge(obj_a, obj_b, strategy='smart', renderer='yaml', merge_lists=False):
'''
Merge a data structure into another by choosing a merge strategy
Strategies:
* aggregate
* list
* overwrite
* recurse
* smart
CLI Example:
.. code-block:: shell
salt '*' slsutil.merge '{foo: Foo}' '{bar: Bar}'
'''
return salt.utils.dictupdate.merge(obj_a, obj_b, strategy, renderer,
merge_lists) | [
"def",
"merge",
"(",
"obj_a",
",",
"obj_b",
",",
"strategy",
"=",
"'smart'",
",",
"renderer",
"=",
"'yaml'",
",",
"merge_lists",
"=",
"False",
")",
":",
"return",
"salt",
".",
"utils",
".",
"dictupdate",
".",
"merge",
"(",
"obj_a",
",",
"obj_b",
",",
... | Merge a data structure into another by choosing a merge strategy
Strategies:
* aggregate
* list
* overwrite
* recurse
* smart
CLI Example:
.. code-block:: shell
salt '*' slsutil.merge '{foo: Foo}' '{bar: Bar}' | [
"Merge",
"a",
"data",
"structure",
"into",
"another",
"by",
"choosing",
"a",
"merge",
"strategy"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/slsutil.py#L37-L56 | train |
saltstack/salt | salt/modules/slsutil.py | merge_all | def merge_all(lst, strategy='smart', renderer='yaml', merge_lists=False):
'''
.. versionadded:: 2019.2.0
Merge a list of objects into each other in order
:type lst: Iterable
:param lst: List of objects to be merged.
:type strategy: String
:param strategy: Merge strategy. See utils.dictupdate.
:type renderer: String
:param renderer:
Renderer type. Used to determine strategy when strategy is 'smart'.
:type merge_lists: Bool
:param merge_lists: Defines whether to merge embedded object lists.
CLI Example:
.. code-block:: shell
$ salt-call --output=txt slsutil.merge_all '[{foo: Foo}, {foo: Bar}]'
local: {u'foo': u'Bar'}
'''
ret = {}
for obj in lst:
ret = salt.utils.dictupdate.merge(
ret, obj, strategy, renderer, merge_lists
)
return ret | python | def merge_all(lst, strategy='smart', renderer='yaml', merge_lists=False):
'''
.. versionadded:: 2019.2.0
Merge a list of objects into each other in order
:type lst: Iterable
:param lst: List of objects to be merged.
:type strategy: String
:param strategy: Merge strategy. See utils.dictupdate.
:type renderer: String
:param renderer:
Renderer type. Used to determine strategy when strategy is 'smart'.
:type merge_lists: Bool
:param merge_lists: Defines whether to merge embedded object lists.
CLI Example:
.. code-block:: shell
$ salt-call --output=txt slsutil.merge_all '[{foo: Foo}, {foo: Bar}]'
local: {u'foo': u'Bar'}
'''
ret = {}
for obj in lst:
ret = salt.utils.dictupdate.merge(
ret, obj, strategy, renderer, merge_lists
)
return ret | [
"def",
"merge_all",
"(",
"lst",
",",
"strategy",
"=",
"'smart'",
",",
"renderer",
"=",
"'yaml'",
",",
"merge_lists",
"=",
"False",
")",
":",
"ret",
"=",
"{",
"}",
"for",
"obj",
"in",
"lst",
":",
"ret",
"=",
"salt",
".",
"utils",
".",
"dictupdate",
... | .. versionadded:: 2019.2.0
Merge a list of objects into each other in order
:type lst: Iterable
:param lst: List of objects to be merged.
:type strategy: String
:param strategy: Merge strategy. See utils.dictupdate.
:type renderer: String
:param renderer:
Renderer type. Used to determine strategy when strategy is 'smart'.
:type merge_lists: Bool
:param merge_lists: Defines whether to merge embedded object lists.
CLI Example:
.. code-block:: shell
$ salt-call --output=txt slsutil.merge_all '[{foo: Foo}, {foo: Bar}]'
local: {u'foo': u'Bar'} | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/slsutil.py#L59-L92 | train |
saltstack/salt | salt/modules/slsutil.py | renderer | def renderer(path=None, string=None, default_renderer='jinja|yaml', **kwargs):
'''
Parse a string or file through Salt's renderer system
.. versionchanged:: 2018.3.0
Add support for Salt fileserver URIs.
This is an open-ended function and can be used for a variety of tasks. It
makes use of Salt's "renderer pipes" system to run a string or file through
a pipe of any of the loaded renderer modules.
:param path: The path to a file on Salt's fileserver (any URIs supported by
:py:func:`cp.get_url <salt.modules.cp.get_url>`) or on the local file
system.
:param string: An inline string to be used as the file to send through the
renderer system. Note, not all renderer modules can work with strings;
the 'py' renderer requires a file, for example.
:param default_renderer: The renderer pipe to send the file through; this
is overridden by a "she-bang" at the top of the file.
:param kwargs: Keyword args to pass to Salt's compile_template() function.
Keep in mind the goal of each renderer when choosing a render-pipe; for
example, the Jinja renderer processes a text file and produces a string,
however the YAML renderer processes a text file and produces a data
structure.
One possible use is to allow writing "map files", as are commonly seen in
Salt formulas, but without tying the renderer of the map file to the
renderer used in the other sls files. In other words, a map file could use
the Python renderer and still be included and used by an sls file that uses
the default 'jinja|yaml' renderer.
For example, the two following map files produce identical results but one
is written using the normal 'jinja|yaml' and the other is using 'py':
.. code-block:: jinja
#!jinja|yaml
{% set apache = salt.grains.filter_by({
...normal jinja map file here...
}, merge=salt.pillar.get('apache:lookup')) %}
{{ apache | yaml() }}
.. code-block:: python
#!py
def run():
apache = __salt__.grains.filter_by({
...normal map here but as a python dict...
}, merge=__salt__.pillar.get('apache:lookup'))
return apache
Regardless of which of the above map files is used, it can be accessed from
any other sls file by calling this function. The following is a usage
example in Jinja:
.. code-block:: jinja
{% set apache = salt.slsutil.renderer('map.sls') %}
CLI Example:
.. code-block:: bash
salt '*' slsutil.renderer salt://path/to/file
salt '*' slsutil.renderer /path/to/file
salt '*' slsutil.renderer /path/to/file.jinja 'jinja'
salt '*' slsutil.renderer /path/to/file.sls 'jinja|yaml'
salt '*' slsutil.renderer string='Inline template! {{ saltenv }}'
salt '*' slsutil.renderer string='Hello, {{ name }}.' name='world'
'''
if not path and not string:
raise salt.exceptions.SaltInvocationError(
'Must pass either path or string')
renderers = salt.loader.render(__opts__, __salt__)
if path:
path_or_string = __salt__['cp.get_url'](path, saltenv=kwargs.get('saltenv', 'base'))
elif string:
path_or_string = ':string:'
kwargs['input_data'] = string
ret = salt.template.compile_template(
path_or_string,
renderers,
default_renderer,
__opts__['renderer_blacklist'],
__opts__['renderer_whitelist'],
**kwargs
)
return ret.read() if __utils__['stringio.is_readable'](ret) else ret | python | def renderer(path=None, string=None, default_renderer='jinja|yaml', **kwargs):
'''
Parse a string or file through Salt's renderer system
.. versionchanged:: 2018.3.0
Add support for Salt fileserver URIs.
This is an open-ended function and can be used for a variety of tasks. It
makes use of Salt's "renderer pipes" system to run a string or file through
a pipe of any of the loaded renderer modules.
:param path: The path to a file on Salt's fileserver (any URIs supported by
:py:func:`cp.get_url <salt.modules.cp.get_url>`) or on the local file
system.
:param string: An inline string to be used as the file to send through the
renderer system. Note, not all renderer modules can work with strings;
the 'py' renderer requires a file, for example.
:param default_renderer: The renderer pipe to send the file through; this
is overridden by a "she-bang" at the top of the file.
:param kwargs: Keyword args to pass to Salt's compile_template() function.
Keep in mind the goal of each renderer when choosing a render-pipe; for
example, the Jinja renderer processes a text file and produces a string,
however the YAML renderer processes a text file and produces a data
structure.
One possible use is to allow writing "map files", as are commonly seen in
Salt formulas, but without tying the renderer of the map file to the
renderer used in the other sls files. In other words, a map file could use
the Python renderer and still be included and used by an sls file that uses
the default 'jinja|yaml' renderer.
For example, the two following map files produce identical results but one
is written using the normal 'jinja|yaml' and the other is using 'py':
.. code-block:: jinja
#!jinja|yaml
{% set apache = salt.grains.filter_by({
...normal jinja map file here...
}, merge=salt.pillar.get('apache:lookup')) %}
{{ apache | yaml() }}
.. code-block:: python
#!py
def run():
apache = __salt__.grains.filter_by({
...normal map here but as a python dict...
}, merge=__salt__.pillar.get('apache:lookup'))
return apache
Regardless of which of the above map files is used, it can be accessed from
any other sls file by calling this function. The following is a usage
example in Jinja:
.. code-block:: jinja
{% set apache = salt.slsutil.renderer('map.sls') %}
CLI Example:
.. code-block:: bash
salt '*' slsutil.renderer salt://path/to/file
salt '*' slsutil.renderer /path/to/file
salt '*' slsutil.renderer /path/to/file.jinja 'jinja'
salt '*' slsutil.renderer /path/to/file.sls 'jinja|yaml'
salt '*' slsutil.renderer string='Inline template! {{ saltenv }}'
salt '*' slsutil.renderer string='Hello, {{ name }}.' name='world'
'''
if not path and not string:
raise salt.exceptions.SaltInvocationError(
'Must pass either path or string')
renderers = salt.loader.render(__opts__, __salt__)
if path:
path_or_string = __salt__['cp.get_url'](path, saltenv=kwargs.get('saltenv', 'base'))
elif string:
path_or_string = ':string:'
kwargs['input_data'] = string
ret = salt.template.compile_template(
path_or_string,
renderers,
default_renderer,
__opts__['renderer_blacklist'],
__opts__['renderer_whitelist'],
**kwargs
)
return ret.read() if __utils__['stringio.is_readable'](ret) else ret | [
"def",
"renderer",
"(",
"path",
"=",
"None",
",",
"string",
"=",
"None",
",",
"default_renderer",
"=",
"'jinja|yaml'",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"path",
"and",
"not",
"string",
":",
"raise",
"salt",
".",
"exceptions",
".",
"SaltIn... | Parse a string or file through Salt's renderer system
.. versionchanged:: 2018.3.0
Add support for Salt fileserver URIs.
This is an open-ended function and can be used for a variety of tasks. It
makes use of Salt's "renderer pipes" system to run a string or file through
a pipe of any of the loaded renderer modules.
:param path: The path to a file on Salt's fileserver (any URIs supported by
:py:func:`cp.get_url <salt.modules.cp.get_url>`) or on the local file
system.
:param string: An inline string to be used as the file to send through the
renderer system. Note, not all renderer modules can work with strings;
the 'py' renderer requires a file, for example.
:param default_renderer: The renderer pipe to send the file through; this
is overridden by a "she-bang" at the top of the file.
:param kwargs: Keyword args to pass to Salt's compile_template() function.
Keep in mind the goal of each renderer when choosing a render-pipe; for
example, the Jinja renderer processes a text file and produces a string,
however the YAML renderer processes a text file and produces a data
structure.
One possible use is to allow writing "map files", as are commonly seen in
Salt formulas, but without tying the renderer of the map file to the
renderer used in the other sls files. In other words, a map file could use
the Python renderer and still be included and used by an sls file that uses
the default 'jinja|yaml' renderer.
For example, the two following map files produce identical results but one
is written using the normal 'jinja|yaml' and the other is using 'py':
.. code-block:: jinja
#!jinja|yaml
{% set apache = salt.grains.filter_by({
...normal jinja map file here...
}, merge=salt.pillar.get('apache:lookup')) %}
{{ apache | yaml() }}
.. code-block:: python
#!py
def run():
apache = __salt__.grains.filter_by({
...normal map here but as a python dict...
}, merge=__salt__.pillar.get('apache:lookup'))
return apache
Regardless of which of the above map files is used, it can be accessed from
any other sls file by calling this function. The following is a usage
example in Jinja:
.. code-block:: jinja
{% set apache = salt.slsutil.renderer('map.sls') %}
CLI Example:
.. code-block:: bash
salt '*' slsutil.renderer salt://path/to/file
salt '*' slsutil.renderer /path/to/file
salt '*' slsutil.renderer /path/to/file.jinja 'jinja'
salt '*' slsutil.renderer /path/to/file.sls 'jinja|yaml'
salt '*' slsutil.renderer string='Inline template! {{ saltenv }}'
salt '*' slsutil.renderer string='Hello, {{ name }}.' name='world' | [
"Parse",
"a",
"string",
"or",
"file",
"through",
"Salt",
"s",
"renderer",
"system"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/slsutil.py#L95-L186 | train |
saltstack/salt | salt/modules/slsutil.py | serialize | def serialize(serializer, obj, **mod_kwargs):
'''
Serialize a Python object using a :py:mod:`serializer module
<salt.serializers>`
CLI Example:
.. code-block:: bash
salt '*' --no-parse=obj slsutil.serialize 'json' obj="{'foo': 'Foo!'}
Jinja Example:
.. code-block:: jinja
{% set json_string = salt.slsutil.serialize('json',
{'foo': 'Foo!'}) %}
'''
kwargs = salt.utils.args.clean_kwargs(**mod_kwargs)
return _get_serialize_fn(serializer, 'serialize')(obj, **kwargs) | python | def serialize(serializer, obj, **mod_kwargs):
'''
Serialize a Python object using a :py:mod:`serializer module
<salt.serializers>`
CLI Example:
.. code-block:: bash
salt '*' --no-parse=obj slsutil.serialize 'json' obj="{'foo': 'Foo!'}
Jinja Example:
.. code-block:: jinja
{% set json_string = salt.slsutil.serialize('json',
{'foo': 'Foo!'}) %}
'''
kwargs = salt.utils.args.clean_kwargs(**mod_kwargs)
return _get_serialize_fn(serializer, 'serialize')(obj, **kwargs) | [
"def",
"serialize",
"(",
"serializer",
",",
"obj",
",",
"*",
"*",
"mod_kwargs",
")",
":",
"kwargs",
"=",
"salt",
".",
"utils",
".",
"args",
".",
"clean_kwargs",
"(",
"*",
"*",
"mod_kwargs",
")",
"return",
"_get_serialize_fn",
"(",
"serializer",
",",
"'se... | Serialize a Python object using a :py:mod:`serializer module
<salt.serializers>`
CLI Example:
.. code-block:: bash
salt '*' --no-parse=obj slsutil.serialize 'json' obj="{'foo': 'Foo!'}
Jinja Example:
.. code-block:: jinja
{% set json_string = salt.slsutil.serialize('json',
{'foo': 'Foo!'}) %} | [
"Serialize",
"a",
"Python",
"object",
"using",
"a",
":",
"py",
":",
"mod",
":",
"serializer",
"module",
"<salt",
".",
"serializers",
">"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/slsutil.py#L206-L225 | train |
saltstack/salt | salt/modules/slsutil.py | deserialize | def deserialize(serializer, stream_or_string, **mod_kwargs):
'''
Deserialize a Python object using a :py:mod:`serializer module
<salt.serializers>`
CLI Example:
.. code-block:: bash
salt '*' slsutil.deserialize 'json' '{"foo": "Foo!"}'
salt '*' --no-parse=stream_or_string slsutil.deserialize 'json' \\
stream_or_string='{"foo": "Foo!"}'
Jinja Example:
.. code-block:: jinja
{% set python_object = salt.slsutil.deserialize('json',
'{"foo": "Foo!"}') %}
'''
kwargs = salt.utils.args.clean_kwargs(**mod_kwargs)
return _get_serialize_fn(serializer, 'deserialize')(stream_or_string,
**kwargs) | python | def deserialize(serializer, stream_or_string, **mod_kwargs):
'''
Deserialize a Python object using a :py:mod:`serializer module
<salt.serializers>`
CLI Example:
.. code-block:: bash
salt '*' slsutil.deserialize 'json' '{"foo": "Foo!"}'
salt '*' --no-parse=stream_or_string slsutil.deserialize 'json' \\
stream_or_string='{"foo": "Foo!"}'
Jinja Example:
.. code-block:: jinja
{% set python_object = salt.slsutil.deserialize('json',
'{"foo": "Foo!"}') %}
'''
kwargs = salt.utils.args.clean_kwargs(**mod_kwargs)
return _get_serialize_fn(serializer, 'deserialize')(stream_or_string,
**kwargs) | [
"def",
"deserialize",
"(",
"serializer",
",",
"stream_or_string",
",",
"*",
"*",
"mod_kwargs",
")",
":",
"kwargs",
"=",
"salt",
".",
"utils",
".",
"args",
".",
"clean_kwargs",
"(",
"*",
"*",
"mod_kwargs",
")",
"return",
"_get_serialize_fn",
"(",
"serializer"... | Deserialize a Python object using a :py:mod:`serializer module
<salt.serializers>`
CLI Example:
.. code-block:: bash
salt '*' slsutil.deserialize 'json' '{"foo": "Foo!"}'
salt '*' --no-parse=stream_or_string slsutil.deserialize 'json' \\
stream_or_string='{"foo": "Foo!"}'
Jinja Example:
.. code-block:: jinja
{% set python_object = salt.slsutil.deserialize('json',
'{"foo": "Foo!"}') %} | [
"Deserialize",
"a",
"Python",
"object",
"using",
"a",
":",
"py",
":",
"mod",
":",
"serializer",
"module",
"<salt",
".",
"serializers",
">"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/slsutil.py#L228-L250 | train |
saltstack/salt | salt/modules/slsutil.py | banner | def banner(width=72, commentchar='#', borderchar='#', blockstart=None, blockend=None,
title=None, text=None, newline=False):
'''
Create a standardized comment block to include in a templated file.
A common technique in configuration management is to include a comment
block in managed files, warning users not to modify the file. This
function simplifies and standardizes those comment blocks.
:param width: The width, in characters, of the banner. Default is 72.
:param commentchar: The character to be used in the starting position of
each line. This value should be set to a valid line comment character
for the syntax of the file in which the banner is being inserted.
Multiple character sequences, like '//' are supported.
If the file's syntax does not support line comments (such as XML),
use the ``blockstart`` and ``blockend`` options.
:param borderchar: The character to use in the top and bottom border of
the comment box. Must be a single character.
:param blockstart: The character sequence to use at the beginning of a
block comment. Should be used in conjunction with ``blockend``
:param blockend: The character sequence to use at the end of a
block comment. Should be used in conjunction with ``blockstart``
:param title: The first field of the comment block. This field appears
centered at the top of the box.
:param text: The second filed of the comment block. This field appears
left-justifed at the bottom of the box.
:param newline: Boolean value to indicate whether the comment block should
end with a newline. Default is ``False``.
This banner can be injected into any templated file, for example:
.. code-block:: jinja
{{ salt['slsutil.banner'](width=120, commentchar='//') }}
The default banner:
.. code-block:: none
########################################################################
# #
# THIS FILE IS MANAGED BY SALT - DO NOT EDIT #
# #
# The contents of this file are managed by Salt. Any changes to this #
# file may be overwritten automatically and without warning. #
########################################################################
'''
if title is None:
title = 'THIS FILE IS MANAGED BY SALT - DO NOT EDIT'
if text is None:
text = ('The contents of this file are managed by Salt. '
'Any changes to this file may be overwritten '
'automatically and without warning')
# Set up some typesetting variables
lgutter = commentchar.strip() + ' '
rgutter = ' ' + commentchar.strip()
textwidth = width - len(lgutter) - len(rgutter)
border_line = commentchar + borderchar[:1] * (width - len(commentchar) * 2) + commentchar
spacer_line = commentchar + ' ' * (width - len(commentchar) * 2) + commentchar
wrapper = textwrap.TextWrapper(width=(width - len(lgutter) - len(rgutter)))
block = list()
# Create the banner
if blockstart is not None:
block.append(blockstart)
block.append(border_line)
block.append(spacer_line)
for line in wrapper.wrap(title):
block.append(lgutter + line.center(textwidth) + rgutter)
block.append(spacer_line)
for line in wrapper.wrap(text):
block.append(lgutter + line + ' ' * (textwidth - len(line)) + rgutter)
block.append(border_line)
if blockend is not None:
block.append(blockend)
# Convert list to multi-line string
result = os.linesep.join(block)
# Add a newline character to the end of the banner
if newline:
return result + os.linesep
return result | python | def banner(width=72, commentchar='#', borderchar='#', blockstart=None, blockend=None,
title=None, text=None, newline=False):
'''
Create a standardized comment block to include in a templated file.
A common technique in configuration management is to include a comment
block in managed files, warning users not to modify the file. This
function simplifies and standardizes those comment blocks.
:param width: The width, in characters, of the banner. Default is 72.
:param commentchar: The character to be used in the starting position of
each line. This value should be set to a valid line comment character
for the syntax of the file in which the banner is being inserted.
Multiple character sequences, like '//' are supported.
If the file's syntax does not support line comments (such as XML),
use the ``blockstart`` and ``blockend`` options.
:param borderchar: The character to use in the top and bottom border of
the comment box. Must be a single character.
:param blockstart: The character sequence to use at the beginning of a
block comment. Should be used in conjunction with ``blockend``
:param blockend: The character sequence to use at the end of a
block comment. Should be used in conjunction with ``blockstart``
:param title: The first field of the comment block. This field appears
centered at the top of the box.
:param text: The second filed of the comment block. This field appears
left-justifed at the bottom of the box.
:param newline: Boolean value to indicate whether the comment block should
end with a newline. Default is ``False``.
This banner can be injected into any templated file, for example:
.. code-block:: jinja
{{ salt['slsutil.banner'](width=120, commentchar='//') }}
The default banner:
.. code-block:: none
########################################################################
# #
# THIS FILE IS MANAGED BY SALT - DO NOT EDIT #
# #
# The contents of this file are managed by Salt. Any changes to this #
# file may be overwritten automatically and without warning. #
########################################################################
'''
if title is None:
title = 'THIS FILE IS MANAGED BY SALT - DO NOT EDIT'
if text is None:
text = ('The contents of this file are managed by Salt. '
'Any changes to this file may be overwritten '
'automatically and without warning')
# Set up some typesetting variables
lgutter = commentchar.strip() + ' '
rgutter = ' ' + commentchar.strip()
textwidth = width - len(lgutter) - len(rgutter)
border_line = commentchar + borderchar[:1] * (width - len(commentchar) * 2) + commentchar
spacer_line = commentchar + ' ' * (width - len(commentchar) * 2) + commentchar
wrapper = textwrap.TextWrapper(width=(width - len(lgutter) - len(rgutter)))
block = list()
# Create the banner
if blockstart is not None:
block.append(blockstart)
block.append(border_line)
block.append(spacer_line)
for line in wrapper.wrap(title):
block.append(lgutter + line.center(textwidth) + rgutter)
block.append(spacer_line)
for line in wrapper.wrap(text):
block.append(lgutter + line + ' ' * (textwidth - len(line)) + rgutter)
block.append(border_line)
if blockend is not None:
block.append(blockend)
# Convert list to multi-line string
result = os.linesep.join(block)
# Add a newline character to the end of the banner
if newline:
return result + os.linesep
return result | [
"def",
"banner",
"(",
"width",
"=",
"72",
",",
"commentchar",
"=",
"'#'",
",",
"borderchar",
"=",
"'#'",
",",
"blockstart",
"=",
"None",
",",
"blockend",
"=",
"None",
",",
"title",
"=",
"None",
",",
"text",
"=",
"None",
",",
"newline",
"=",
"False",
... | Create a standardized comment block to include in a templated file.
A common technique in configuration management is to include a comment
block in managed files, warning users not to modify the file. This
function simplifies and standardizes those comment blocks.
:param width: The width, in characters, of the banner. Default is 72.
:param commentchar: The character to be used in the starting position of
each line. This value should be set to a valid line comment character
for the syntax of the file in which the banner is being inserted.
Multiple character sequences, like '//' are supported.
If the file's syntax does not support line comments (such as XML),
use the ``blockstart`` and ``blockend`` options.
:param borderchar: The character to use in the top and bottom border of
the comment box. Must be a single character.
:param blockstart: The character sequence to use at the beginning of a
block comment. Should be used in conjunction with ``blockend``
:param blockend: The character sequence to use at the end of a
block comment. Should be used in conjunction with ``blockstart``
:param title: The first field of the comment block. This field appears
centered at the top of the box.
:param text: The second filed of the comment block. This field appears
left-justifed at the bottom of the box.
:param newline: Boolean value to indicate whether the comment block should
end with a newline. Default is ``False``.
This banner can be injected into any templated file, for example:
.. code-block:: jinja
{{ salt['slsutil.banner'](width=120, commentchar='//') }}
The default banner:
.. code-block:: none
########################################################################
# #
# THIS FILE IS MANAGED BY SALT - DO NOT EDIT #
# #
# The contents of this file are managed by Salt. Any changes to this #
# file may be overwritten automatically and without warning. #
######################################################################## | [
"Create",
"a",
"standardized",
"comment",
"block",
"to",
"include",
"in",
"a",
"templated",
"file",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/slsutil.py#L253-L339 | train |
saltstack/salt | salt/utils/msazure.py | get_storage_conn | def get_storage_conn(storage_account=None, storage_key=None, opts=None):
'''
.. versionadded:: 2015.8.0
Return a storage_conn object for the storage account
'''
if opts is None:
opts = {}
if not storage_account:
storage_account = opts.get('storage_account', None)
if not storage_key:
storage_key = opts.get('storage_key', None)
return azure.storage.BlobService(storage_account, storage_key) | python | def get_storage_conn(storage_account=None, storage_key=None, opts=None):
'''
.. versionadded:: 2015.8.0
Return a storage_conn object for the storage account
'''
if opts is None:
opts = {}
if not storage_account:
storage_account = opts.get('storage_account', None)
if not storage_key:
storage_key = opts.get('storage_key', None)
return azure.storage.BlobService(storage_account, storage_key) | [
"def",
"get_storage_conn",
"(",
"storage_account",
"=",
"None",
",",
"storage_key",
"=",
"None",
",",
"opts",
"=",
"None",
")",
":",
"if",
"opts",
"is",
"None",
":",
"opts",
"=",
"{",
"}",
"if",
"not",
"storage_account",
":",
"storage_account",
"=",
"opt... | .. versionadded:: 2015.8.0
Return a storage_conn object for the storage account | [
"..",
"versionadded",
"::",
"2015",
".",
"8",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/msazure.py#L26-L40 | train |
saltstack/salt | salt/utils/msazure.py | list_blobs | def list_blobs(storage_conn=None, **kwargs):
'''
.. versionadded:: 2015.8.0
List blobs associated with the container
'''
if not storage_conn:
storage_conn = get_storage_conn(opts=kwargs)
if 'container' not in kwargs:
raise SaltSystemExit(
code=42,
msg='An storage container name must be specified as "container"'
)
data = storage_conn.list_blobs(
container_name=kwargs['container'],
prefix=kwargs.get('prefix', None),
marker=kwargs.get('marker', None),
maxresults=kwargs.get('maxresults', None),
include=kwargs.get('include', None),
delimiter=kwargs.get('delimiter', None),
)
ret = {}
for item in data.blobs:
ret[item.name] = object_to_dict(item)
return ret | python | def list_blobs(storage_conn=None, **kwargs):
'''
.. versionadded:: 2015.8.0
List blobs associated with the container
'''
if not storage_conn:
storage_conn = get_storage_conn(opts=kwargs)
if 'container' not in kwargs:
raise SaltSystemExit(
code=42,
msg='An storage container name must be specified as "container"'
)
data = storage_conn.list_blobs(
container_name=kwargs['container'],
prefix=kwargs.get('prefix', None),
marker=kwargs.get('marker', None),
maxresults=kwargs.get('maxresults', None),
include=kwargs.get('include', None),
delimiter=kwargs.get('delimiter', None),
)
ret = {}
for item in data.blobs:
ret[item.name] = object_to_dict(item)
return ret | [
"def",
"list_blobs",
"(",
"storage_conn",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"storage_conn",
":",
"storage_conn",
"=",
"get_storage_conn",
"(",
"opts",
"=",
"kwargs",
")",
"if",
"'container'",
"not",
"in",
"kwargs",
":",
"raise",
... | .. versionadded:: 2015.8.0
List blobs associated with the container | [
"..",
"versionadded",
"::",
"2015",
".",
"8",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/msazure.py#L43-L70 | train |
saltstack/salt | salt/utils/msazure.py | put_blob | def put_blob(storage_conn=None, **kwargs):
'''
.. versionadded:: 2015.8.0
Upload a blob
'''
if not storage_conn:
storage_conn = get_storage_conn(opts=kwargs)
if 'container' not in kwargs:
raise SaltSystemExit(code=42, msg='The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltSystemExit(code=42, msg='The blob name must be specified as "name"')
if 'blob_path' not in kwargs and 'blob_content' not in kwargs:
raise SaltSystemExit(
code=42,
msg='Either a path to a file needs to be passed in as "blob_path" '
'or the contents of a blob as "blob_content."'
)
blob_kwargs = {
'container_name': kwargs['container'],
'blob_name': kwargs['name'],
'cache_control': kwargs.get('cache_control', None),
'content_language': kwargs.get('content_language', None),
'content_md5': kwargs.get('content_md5', None),
'x_ms_blob_content_type': kwargs.get('blob_content_type', None),
'x_ms_blob_content_encoding': kwargs.get('blob_content_encoding', None),
'x_ms_blob_content_language': kwargs.get('blob_content_language', None),
'x_ms_blob_content_md5': kwargs.get('blob_content_md5', None),
'x_ms_blob_cache_control': kwargs.get('blob_cache_control', None),
'x_ms_meta_name_values': kwargs.get('meta_name_values', None),
'x_ms_lease_id': kwargs.get('lease_id', None),
}
if 'blob_path' in kwargs:
data = storage_conn.put_block_blob_from_path(
file_path=kwargs['blob_path'],
**blob_kwargs
)
elif 'blob_content' in kwargs:
data = storage_conn.put_block_blob_from_bytes(
blob=kwargs['blob_content'],
**blob_kwargs
)
return data | python | def put_blob(storage_conn=None, **kwargs):
'''
.. versionadded:: 2015.8.0
Upload a blob
'''
if not storage_conn:
storage_conn = get_storage_conn(opts=kwargs)
if 'container' not in kwargs:
raise SaltSystemExit(code=42, msg='The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltSystemExit(code=42, msg='The blob name must be specified as "name"')
if 'blob_path' not in kwargs and 'blob_content' not in kwargs:
raise SaltSystemExit(
code=42,
msg='Either a path to a file needs to be passed in as "blob_path" '
'or the contents of a blob as "blob_content."'
)
blob_kwargs = {
'container_name': kwargs['container'],
'blob_name': kwargs['name'],
'cache_control': kwargs.get('cache_control', None),
'content_language': kwargs.get('content_language', None),
'content_md5': kwargs.get('content_md5', None),
'x_ms_blob_content_type': kwargs.get('blob_content_type', None),
'x_ms_blob_content_encoding': kwargs.get('blob_content_encoding', None),
'x_ms_blob_content_language': kwargs.get('blob_content_language', None),
'x_ms_blob_content_md5': kwargs.get('blob_content_md5', None),
'x_ms_blob_cache_control': kwargs.get('blob_cache_control', None),
'x_ms_meta_name_values': kwargs.get('meta_name_values', None),
'x_ms_lease_id': kwargs.get('lease_id', None),
}
if 'blob_path' in kwargs:
data = storage_conn.put_block_blob_from_path(
file_path=kwargs['blob_path'],
**blob_kwargs
)
elif 'blob_content' in kwargs:
data = storage_conn.put_block_blob_from_bytes(
blob=kwargs['blob_content'],
**blob_kwargs
)
return data | [
"def",
"put_blob",
"(",
"storage_conn",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"storage_conn",
":",
"storage_conn",
"=",
"get_storage_conn",
"(",
"opts",
"=",
"kwargs",
")",
"if",
"'container'",
"not",
"in",
"kwargs",
":",
"raise",
... | .. versionadded:: 2015.8.0
Upload a blob | [
"..",
"versionadded",
"::",
"2015",
".",
"8",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/msazure.py#L73-L120 | train |
saltstack/salt | salt/utils/msazure.py | get_blob | def get_blob(storage_conn=None, **kwargs):
'''
.. versionadded:: 2015.8.0
Download a blob
'''
if not storage_conn:
storage_conn = get_storage_conn(opts=kwargs)
if 'container' not in kwargs:
raise SaltSystemExit(code=42, msg='The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltSystemExit(code=42, msg='The blob name must be specified as "name"')
if 'local_path' not in kwargs and 'return_content' not in kwargs:
raise SaltSystemExit(
code=42,
msg='Either a local path needs to be passed in as "local_path", '
'or "return_content" to return the blob contents directly'
)
blob_kwargs = {
'container_name': kwargs['container'],
'blob_name': kwargs['name'],
'snapshot': kwargs.get('snapshot', None),
'x_ms_lease_id': kwargs.get('lease_id', None),
'progress_callback': kwargs.get('progress_callback', None),
'max_connections': kwargs.get('max_connections', 1),
'max_retries': kwargs.get('max_retries', 5),
'retry_wait': kwargs.get('retry_wait', 1),
}
if 'local_path' in kwargs:
data = storage_conn.get_blob_to_path(
file_path=kwargs['local_path'],
open_mode=kwargs.get('open_mode', 'wb'),
**blob_kwargs
)
elif 'return_content' in kwargs:
data = storage_conn.get_blob_to_bytes(
**blob_kwargs
)
return data | python | def get_blob(storage_conn=None, **kwargs):
'''
.. versionadded:: 2015.8.0
Download a blob
'''
if not storage_conn:
storage_conn = get_storage_conn(opts=kwargs)
if 'container' not in kwargs:
raise SaltSystemExit(code=42, msg='The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltSystemExit(code=42, msg='The blob name must be specified as "name"')
if 'local_path' not in kwargs and 'return_content' not in kwargs:
raise SaltSystemExit(
code=42,
msg='Either a local path needs to be passed in as "local_path", '
'or "return_content" to return the blob contents directly'
)
blob_kwargs = {
'container_name': kwargs['container'],
'blob_name': kwargs['name'],
'snapshot': kwargs.get('snapshot', None),
'x_ms_lease_id': kwargs.get('lease_id', None),
'progress_callback': kwargs.get('progress_callback', None),
'max_connections': kwargs.get('max_connections', 1),
'max_retries': kwargs.get('max_retries', 5),
'retry_wait': kwargs.get('retry_wait', 1),
}
if 'local_path' in kwargs:
data = storage_conn.get_blob_to_path(
file_path=kwargs['local_path'],
open_mode=kwargs.get('open_mode', 'wb'),
**blob_kwargs
)
elif 'return_content' in kwargs:
data = storage_conn.get_blob_to_bytes(
**blob_kwargs
)
return data | [
"def",
"get_blob",
"(",
"storage_conn",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"storage_conn",
":",
"storage_conn",
"=",
"get_storage_conn",
"(",
"opts",
"=",
"kwargs",
")",
"if",
"'container'",
"not",
"in",
"kwargs",
":",
"raise",
... | .. versionadded:: 2015.8.0
Download a blob | [
"..",
"versionadded",
"::",
"2015",
".",
"8",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/msazure.py#L123-L167 | train |
saltstack/salt | salt/utils/msazure.py | object_to_dict | def object_to_dict(obj):
'''
.. versionadded:: 2015.8.0
Convert an object to a dictionary
'''
if isinstance(obj, list) or isinstance(obj, tuple):
ret = []
for item in obj:
ret.append(object_to_dict(item))
elif hasattr(obj, '__dict__'):
ret = {}
for item in obj.__dict__:
if item.startswith('_'):
continue
ret[item] = object_to_dict(obj.__dict__[item])
else:
ret = obj
return ret | python | def object_to_dict(obj):
'''
.. versionadded:: 2015.8.0
Convert an object to a dictionary
'''
if isinstance(obj, list) or isinstance(obj, tuple):
ret = []
for item in obj:
ret.append(object_to_dict(item))
elif hasattr(obj, '__dict__'):
ret = {}
for item in obj.__dict__:
if item.startswith('_'):
continue
ret[item] = object_to_dict(obj.__dict__[item])
else:
ret = obj
return ret | [
"def",
"object_to_dict",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"list",
")",
"or",
"isinstance",
"(",
"obj",
",",
"tuple",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"item",
"in",
"obj",
":",
"ret",
".",
"append",
"(",
"object_to_di... | .. versionadded:: 2015.8.0
Convert an object to a dictionary | [
"..",
"versionadded",
"::",
"2015",
".",
"8",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/msazure.py#L170-L188 | train |
saltstack/salt | salt/cloud/cli.py | SaltCloud.run | def run(self):
'''
Execute the salt-cloud command line
'''
# Parse shell arguments
self.parse_args()
salt_master_user = self.config.get('user')
if salt_master_user is None:
salt_master_user = salt.utils.user.get_user()
if not check_user(salt_master_user):
self.error(
'If salt-cloud is running on a master machine, salt-cloud '
'needs to run as the same user as the salt-master, \'{0}\'. '
'If salt-cloud is not running on a salt-master, the '
'appropriate write permissions must be granted to \'{1}\'. '
'Please run salt-cloud as root, \'{0}\', or change '
'permissions for \'{1}\'.'.format(
salt_master_user,
syspaths.CONFIG_DIR
)
)
try:
if self.config['verify_env']:
verify_env(
[os.path.dirname(self.config['conf_file'])],
salt_master_user,
root_dir=self.config['root_dir'],
)
logfile = self.config['log_file']
if logfile is not None and not logfile.startswith('tcp://') \
and not logfile.startswith('udp://') \
and not logfile.startswith('file://'):
# Logfile is not using Syslog, verify
verify_files([logfile], salt_master_user)
except (IOError, OSError) as err:
log.error('Error while verifying the environment: %s', err)
sys.exit(err.errno)
# Setup log file logging
self.setup_logfile_logger()
verify_log(self.config)
if self.options.update_bootstrap:
ret = salt.utils.cloud.update_bootstrap(self.config)
salt.output.display_output(ret,
self.options.output,
opts=self.config)
self.exit(salt.defaults.exitcodes.EX_OK)
log.info('salt-cloud starting')
try:
mapper = salt.cloud.Map(self.config)
except SaltCloudSystemExit as exc:
self.handle_exception(exc.args, exc)
except SaltCloudException as exc:
msg = 'There was an error generating the mapper.'
self.handle_exception(msg, exc)
names = self.config.get('names', None)
if names is not None:
filtered_rendered_map = {}
for map_profile in mapper.rendered_map:
filtered_map_profile = {}
for name in mapper.rendered_map[map_profile]:
if name in names:
filtered_map_profile[name] = mapper.rendered_map[map_profile][name]
if filtered_map_profile:
filtered_rendered_map[map_profile] = filtered_map_profile
mapper.rendered_map = filtered_rendered_map
ret = {}
if self.selected_query_option is not None:
if self.selected_query_option == 'list_providers':
try:
ret = mapper.provider_list()
except (SaltCloudException, Exception) as exc:
msg = 'There was an error listing providers: {0}'
self.handle_exception(msg, exc)
elif self.selected_query_option == 'list_profiles':
provider = self.options.list_profiles
try:
ret = mapper.profile_list(provider)
except(SaltCloudException, Exception) as exc:
msg = 'There was an error listing profiles: {0}'
self.handle_exception(msg, exc)
elif self.config.get('map', None):
log.info('Applying map from \'%s\'.', self.config['map'])
try:
ret = mapper.interpolated_map(
query=self.selected_query_option
)
except (SaltCloudException, Exception) as exc:
msg = 'There was an error with a custom map: {0}'
self.handle_exception(msg, exc)
else:
try:
ret = mapper.map_providers_parallel(
query=self.selected_query_option
)
except (SaltCloudException, Exception) as exc:
msg = 'There was an error with a map: {0}'
self.handle_exception(msg, exc)
elif self.options.list_locations is not None:
try:
ret = mapper.location_list(
self.options.list_locations
)
except (SaltCloudException, Exception) as exc:
msg = 'There was an error listing locations: {0}'
self.handle_exception(msg, exc)
elif self.options.list_images is not None:
try:
ret = mapper.image_list(
self.options.list_images
)
except (SaltCloudException, Exception) as exc:
msg = 'There was an error listing images: {0}'
self.handle_exception(msg, exc)
elif self.options.list_sizes is not None:
try:
ret = mapper.size_list(
self.options.list_sizes
)
except (SaltCloudException, Exception) as exc:
msg = 'There was an error listing sizes: {0}'
self.handle_exception(msg, exc)
elif self.options.destroy and (self.config.get('names', None) or
self.config.get('map', None)):
map_file = self.config.get('map', None)
names = self.config.get('names', ())
if map_file is not None:
if names != ():
msg = 'Supplying a mapfile, \'{0}\', in addition to instance names {1} ' \
'with the \'--destroy\' or \'-d\' function is not supported. ' \
'Please choose to delete either the entire map file or individual ' \
'instances.'.format(map_file, names)
self.handle_exception(msg, SaltCloudSystemExit)
log.info('Applying map from \'%s\'.', map_file)
matching = mapper.delete_map(query='list_nodes')
else:
matching = mapper.get_running_by_names(
names,
profile=self.options.profile
)
if not matching:
print('No machines were found to be destroyed')
self.exit(salt.defaults.exitcodes.EX_OK)
msg = 'The following virtual machines are set to be destroyed:\n'
names = set()
for alias, drivers in six.iteritems(matching):
msg += ' {0}:\n'.format(alias)
for driver, vms in six.iteritems(drivers):
msg += ' {0}:\n'.format(driver)
for name in vms:
msg += ' {0}\n'.format(name)
names.add(name)
try:
if self.print_confirm(msg):
ret = mapper.destroy(names, cached=True)
except (SaltCloudException, Exception) as exc:
msg = 'There was an error destroying machines: {0}'
self.handle_exception(msg, exc)
elif self.options.action and (self.config.get('names', None) or
self.config.get('map', None)):
if self.config.get('map', None):
log.info('Applying map from \'%s\'.', self.config['map'])
try:
names = mapper.get_vmnames_by_action(self.options.action)
except SaltCloudException as exc:
msg = 'There was an error actioning virtual machines.'
self.handle_exception(msg, exc)
else:
names = self.config.get('names', None)
kwargs = {}
machines = []
msg = (
'The following virtual machines are set to be actioned with '
'"{0}":\n'.format(
self.options.action
)
)
for name in names:
if '=' in name:
# This is obviously not a machine name, treat it as a kwarg
key, value = name.split('=', 1)
kwargs[key] = value
else:
msg += ' {0}\n'.format(name)
machines.append(name)
names = machines
try:
if self.print_confirm(msg):
ret = mapper.do_action(names, kwargs)
except (SaltCloudException, Exception) as exc:
msg = 'There was an error actioning machines: {0}'
self.handle_exception(msg, exc)
elif self.options.function:
kwargs = {}
args = self.args[:]
for arg in args[:]:
if '=' in arg:
key, value = arg.split('=', 1)
kwargs[key] = value
args.remove(arg)
if args:
self.error(
'Any arguments passed to --function need to be passed '
'as kwargs. Ex: image=ami-54cf5c3d. Remaining '
'arguments: {0}'.format(args)
)
try:
ret = mapper.do_function(
self.function_provider, self.function_name, kwargs
)
except (SaltCloudException, Exception) as exc:
msg = 'There was an error running the function: {0}'
self.handle_exception(msg, exc)
elif self.options.profile and self.config.get('names', False):
try:
ret = mapper.run_profile(
self.options.profile,
self.config.get('names')
)
except (SaltCloudException, Exception) as exc:
msg = 'There was a profile error: {0}'
self.handle_exception(msg, exc)
elif self.options.set_password:
username = self.credential_username
provider_name = "salt.cloud.provider.{0}".format(self.credential_provider)
# TODO: check if provider is configured
# set the password
salt.utils.cloud.store_password_in_keyring(provider_name, username)
elif self.config.get('map', None) and \
self.selected_query_option is None:
if not mapper.rendered_map:
sys.stderr.write('No nodes defined in this map')
self.exit(salt.defaults.exitcodes.EX_GENERIC)
try:
ret = {}
run_map = True
log.info('Applying map from \'%s\'.', self.config['map'])
dmap = mapper.map_data()
msg = ''
if 'errors' in dmap:
# display profile errors
msg += 'Found the following errors:\n'
for profile_name, error in six.iteritems(dmap['errors']):
msg += ' {0}: {1}\n'.format(profile_name, error)
sys.stderr.write(msg)
sys.stderr.flush()
msg = ''
if 'existing' in dmap:
msg += ('The following virtual machines already exist:\n')
for name in dmap['existing']:
msg += ' {0}\n'.format(name)
if dmap['create']:
msg += ('The following virtual machines are set to be '
'created:\n')
for name in dmap['create']:
msg += ' {0}\n'.format(name)
if 'destroy' in dmap:
msg += ('The following virtual machines are set to be '
'destroyed:\n')
for name in dmap['destroy']:
msg += ' {0}\n'.format(name)
if not dmap['create'] and not dmap.get('destroy', None):
if not dmap.get('existing', None):
# nothing to create or destroy & nothing exists
print(msg)
self.exit(1)
else:
# nothing to create or destroy, print existing
run_map = False
if run_map:
if self.print_confirm(msg):
ret = mapper.run_map(dmap)
if self.config.get('parallel', False) is False:
log.info('Complete')
if dmap.get('existing', None):
for name in dmap['existing']:
if 'ec2' in dmap['existing'][name]['provider']:
msg = 'Instance already exists, or is terminated and has the same name.'
else:
msg = 'Already running.'
ret[name] = {'Message': msg}
except (SaltCloudException, Exception) as exc:
msg = 'There was a query error: {0}'
self.handle_exception(msg, exc)
elif self.options.bootstrap:
host = self.options.bootstrap
if self.args and '=' not in self.args[0]:
minion_id = self.args.pop(0)
else:
minion_id = host
vm_ = {
'driver': '',
'ssh_host': host,
'name': minion_id,
}
args = self.args[:]
for arg in args[:]:
if '=' in arg:
key, value = arg.split('=', 1)
vm_[key] = value
args.remove(arg)
if args:
self.error(
'Any arguments passed to --bootstrap need to be passed as '
'kwargs. Ex: ssh_username=larry. Remaining arguments: {0}'.format(args)
)
try:
ret = salt.utils.cloud.bootstrap(vm_, self.config)
except (SaltCloudException, Exception) as exc:
msg = 'There was an error bootstrapping the minion: {0}'
self.handle_exception(msg, exc)
else:
self.error('Nothing was done. Using the proper arguments?')
salt.output.display_output(ret,
self.options.output,
opts=self.config)
self.exit(salt.defaults.exitcodes.EX_OK) | python | def run(self):
'''
Execute the salt-cloud command line
'''
# Parse shell arguments
self.parse_args()
salt_master_user = self.config.get('user')
if salt_master_user is None:
salt_master_user = salt.utils.user.get_user()
if not check_user(salt_master_user):
self.error(
'If salt-cloud is running on a master machine, salt-cloud '
'needs to run as the same user as the salt-master, \'{0}\'. '
'If salt-cloud is not running on a salt-master, the '
'appropriate write permissions must be granted to \'{1}\'. '
'Please run salt-cloud as root, \'{0}\', or change '
'permissions for \'{1}\'.'.format(
salt_master_user,
syspaths.CONFIG_DIR
)
)
try:
if self.config['verify_env']:
verify_env(
[os.path.dirname(self.config['conf_file'])],
salt_master_user,
root_dir=self.config['root_dir'],
)
logfile = self.config['log_file']
if logfile is not None and not logfile.startswith('tcp://') \
and not logfile.startswith('udp://') \
and not logfile.startswith('file://'):
# Logfile is not using Syslog, verify
verify_files([logfile], salt_master_user)
except (IOError, OSError) as err:
log.error('Error while verifying the environment: %s', err)
sys.exit(err.errno)
# Setup log file logging
self.setup_logfile_logger()
verify_log(self.config)
if self.options.update_bootstrap:
ret = salt.utils.cloud.update_bootstrap(self.config)
salt.output.display_output(ret,
self.options.output,
opts=self.config)
self.exit(salt.defaults.exitcodes.EX_OK)
log.info('salt-cloud starting')
try:
mapper = salt.cloud.Map(self.config)
except SaltCloudSystemExit as exc:
self.handle_exception(exc.args, exc)
except SaltCloudException as exc:
msg = 'There was an error generating the mapper.'
self.handle_exception(msg, exc)
names = self.config.get('names', None)
if names is not None:
filtered_rendered_map = {}
for map_profile in mapper.rendered_map:
filtered_map_profile = {}
for name in mapper.rendered_map[map_profile]:
if name in names:
filtered_map_profile[name] = mapper.rendered_map[map_profile][name]
if filtered_map_profile:
filtered_rendered_map[map_profile] = filtered_map_profile
mapper.rendered_map = filtered_rendered_map
ret = {}
if self.selected_query_option is not None:
if self.selected_query_option == 'list_providers':
try:
ret = mapper.provider_list()
except (SaltCloudException, Exception) as exc:
msg = 'There was an error listing providers: {0}'
self.handle_exception(msg, exc)
elif self.selected_query_option == 'list_profiles':
provider = self.options.list_profiles
try:
ret = mapper.profile_list(provider)
except(SaltCloudException, Exception) as exc:
msg = 'There was an error listing profiles: {0}'
self.handle_exception(msg, exc)
elif self.config.get('map', None):
log.info('Applying map from \'%s\'.', self.config['map'])
try:
ret = mapper.interpolated_map(
query=self.selected_query_option
)
except (SaltCloudException, Exception) as exc:
msg = 'There was an error with a custom map: {0}'
self.handle_exception(msg, exc)
else:
try:
ret = mapper.map_providers_parallel(
query=self.selected_query_option
)
except (SaltCloudException, Exception) as exc:
msg = 'There was an error with a map: {0}'
self.handle_exception(msg, exc)
elif self.options.list_locations is not None:
try:
ret = mapper.location_list(
self.options.list_locations
)
except (SaltCloudException, Exception) as exc:
msg = 'There was an error listing locations: {0}'
self.handle_exception(msg, exc)
elif self.options.list_images is not None:
try:
ret = mapper.image_list(
self.options.list_images
)
except (SaltCloudException, Exception) as exc:
msg = 'There was an error listing images: {0}'
self.handle_exception(msg, exc)
elif self.options.list_sizes is not None:
try:
ret = mapper.size_list(
self.options.list_sizes
)
except (SaltCloudException, Exception) as exc:
msg = 'There was an error listing sizes: {0}'
self.handle_exception(msg, exc)
elif self.options.destroy and (self.config.get('names', None) or
self.config.get('map', None)):
map_file = self.config.get('map', None)
names = self.config.get('names', ())
if map_file is not None:
if names != ():
msg = 'Supplying a mapfile, \'{0}\', in addition to instance names {1} ' \
'with the \'--destroy\' or \'-d\' function is not supported. ' \
'Please choose to delete either the entire map file or individual ' \
'instances.'.format(map_file, names)
self.handle_exception(msg, SaltCloudSystemExit)
log.info('Applying map from \'%s\'.', map_file)
matching = mapper.delete_map(query='list_nodes')
else:
matching = mapper.get_running_by_names(
names,
profile=self.options.profile
)
if not matching:
print('No machines were found to be destroyed')
self.exit(salt.defaults.exitcodes.EX_OK)
msg = 'The following virtual machines are set to be destroyed:\n'
names = set()
for alias, drivers in six.iteritems(matching):
msg += ' {0}:\n'.format(alias)
for driver, vms in six.iteritems(drivers):
msg += ' {0}:\n'.format(driver)
for name in vms:
msg += ' {0}\n'.format(name)
names.add(name)
try:
if self.print_confirm(msg):
ret = mapper.destroy(names, cached=True)
except (SaltCloudException, Exception) as exc:
msg = 'There was an error destroying machines: {0}'
self.handle_exception(msg, exc)
elif self.options.action and (self.config.get('names', None) or
self.config.get('map', None)):
if self.config.get('map', None):
log.info('Applying map from \'%s\'.', self.config['map'])
try:
names = mapper.get_vmnames_by_action(self.options.action)
except SaltCloudException as exc:
msg = 'There was an error actioning virtual machines.'
self.handle_exception(msg, exc)
else:
names = self.config.get('names', None)
kwargs = {}
machines = []
msg = (
'The following virtual machines are set to be actioned with '
'"{0}":\n'.format(
self.options.action
)
)
for name in names:
if '=' in name:
# This is obviously not a machine name, treat it as a kwarg
key, value = name.split('=', 1)
kwargs[key] = value
else:
msg += ' {0}\n'.format(name)
machines.append(name)
names = machines
try:
if self.print_confirm(msg):
ret = mapper.do_action(names, kwargs)
except (SaltCloudException, Exception) as exc:
msg = 'There was an error actioning machines: {0}'
self.handle_exception(msg, exc)
elif self.options.function:
kwargs = {}
args = self.args[:]
for arg in args[:]:
if '=' in arg:
key, value = arg.split('=', 1)
kwargs[key] = value
args.remove(arg)
if args:
self.error(
'Any arguments passed to --function need to be passed '
'as kwargs. Ex: image=ami-54cf5c3d. Remaining '
'arguments: {0}'.format(args)
)
try:
ret = mapper.do_function(
self.function_provider, self.function_name, kwargs
)
except (SaltCloudException, Exception) as exc:
msg = 'There was an error running the function: {0}'
self.handle_exception(msg, exc)
elif self.options.profile and self.config.get('names', False):
try:
ret = mapper.run_profile(
self.options.profile,
self.config.get('names')
)
except (SaltCloudException, Exception) as exc:
msg = 'There was a profile error: {0}'
self.handle_exception(msg, exc)
elif self.options.set_password:
username = self.credential_username
provider_name = "salt.cloud.provider.{0}".format(self.credential_provider)
# TODO: check if provider is configured
# set the password
salt.utils.cloud.store_password_in_keyring(provider_name, username)
elif self.config.get('map', None) and \
self.selected_query_option is None:
if not mapper.rendered_map:
sys.stderr.write('No nodes defined in this map')
self.exit(salt.defaults.exitcodes.EX_GENERIC)
try:
ret = {}
run_map = True
log.info('Applying map from \'%s\'.', self.config['map'])
dmap = mapper.map_data()
msg = ''
if 'errors' in dmap:
# display profile errors
msg += 'Found the following errors:\n'
for profile_name, error in six.iteritems(dmap['errors']):
msg += ' {0}: {1}\n'.format(profile_name, error)
sys.stderr.write(msg)
sys.stderr.flush()
msg = ''
if 'existing' in dmap:
msg += ('The following virtual machines already exist:\n')
for name in dmap['existing']:
msg += ' {0}\n'.format(name)
if dmap['create']:
msg += ('The following virtual machines are set to be '
'created:\n')
for name in dmap['create']:
msg += ' {0}\n'.format(name)
if 'destroy' in dmap:
msg += ('The following virtual machines are set to be '
'destroyed:\n')
for name in dmap['destroy']:
msg += ' {0}\n'.format(name)
if not dmap['create'] and not dmap.get('destroy', None):
if not dmap.get('existing', None):
# nothing to create or destroy & nothing exists
print(msg)
self.exit(1)
else:
# nothing to create or destroy, print existing
run_map = False
if run_map:
if self.print_confirm(msg):
ret = mapper.run_map(dmap)
if self.config.get('parallel', False) is False:
log.info('Complete')
if dmap.get('existing', None):
for name in dmap['existing']:
if 'ec2' in dmap['existing'][name]['provider']:
msg = 'Instance already exists, or is terminated and has the same name.'
else:
msg = 'Already running.'
ret[name] = {'Message': msg}
except (SaltCloudException, Exception) as exc:
msg = 'There was a query error: {0}'
self.handle_exception(msg, exc)
elif self.options.bootstrap:
host = self.options.bootstrap
if self.args and '=' not in self.args[0]:
minion_id = self.args.pop(0)
else:
minion_id = host
vm_ = {
'driver': '',
'ssh_host': host,
'name': minion_id,
}
args = self.args[:]
for arg in args[:]:
if '=' in arg:
key, value = arg.split('=', 1)
vm_[key] = value
args.remove(arg)
if args:
self.error(
'Any arguments passed to --bootstrap need to be passed as '
'kwargs. Ex: ssh_username=larry. Remaining arguments: {0}'.format(args)
)
try:
ret = salt.utils.cloud.bootstrap(vm_, self.config)
except (SaltCloudException, Exception) as exc:
msg = 'There was an error bootstrapping the minion: {0}'
self.handle_exception(msg, exc)
else:
self.error('Nothing was done. Using the proper arguments?')
salt.output.display_output(ret,
self.options.output,
opts=self.config)
self.exit(salt.defaults.exitcodes.EX_OK) | [
"def",
"run",
"(",
"self",
")",
":",
"# Parse shell arguments",
"self",
".",
"parse_args",
"(",
")",
"salt_master_user",
"=",
"self",
".",
"config",
".",
"get",
"(",
"'user'",
")",
"if",
"salt_master_user",
"is",
"None",
":",
"salt_master_user",
"=",
"salt",... | Execute the salt-cloud command line | [
"Execute",
"the",
"salt",
"-",
"cloud",
"command",
"line"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/cli.py#L41-L397 | train |
saltstack/salt | salt/states/webutil.py | user_exists | def user_exists(name, password=None, htpasswd_file=None, options='',
force=False, runas=None, update=False):
'''
Make sure the user is inside the specified htpasswd file
name
User name
password
User password
htpasswd_file
Path to the htpasswd file
options
See :mod:`salt.modules.htpasswd.useradd`
force
Touch the file even if user already created
runas
The system user to run htpasswd command with
update
Update an existing user's password if it's different from what's in
the htpasswd file (unlike force, which updates regardless)
'''
ret = {'name': name,
'changes': {},
'comment': '',
'result': None}
exists = __salt__['file.grep'](
htpasswd_file, '^{0}:'.format(name))['retcode'] == 0
# If user exists, but we're supposed to update the password, find out if
# it's changed, but not if we're forced to update the file regardless.
password_changed = False
if exists and update and not force:
password_changed = not __salt__['webutil.verify'](
htpasswd_file, name, password, opts=options, runas=runas)
if not exists or password_changed or force:
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'User \'{0}\' is set to be added to htpasswd file'.format(name)
ret['changes'] = {name: True}
return ret
useradd_ret = __salt__['webutil.useradd'](htpasswd_file, name,
password, opts=options,
runas=runas)
if useradd_ret['retcode'] == 0:
ret['result'] = True
ret['comment'] = useradd_ret['stderr']
ret['changes'] = {name: True}
return ret
else:
ret['result'] = False
ret['comment'] = useradd_ret['stderr']
return ret
if __opts__['test'] and ret['changes']:
ret['result'] = None
else:
ret['result'] = True
ret['comment'] = 'User already known'
return ret | python | def user_exists(name, password=None, htpasswd_file=None, options='',
force=False, runas=None, update=False):
'''
Make sure the user is inside the specified htpasswd file
name
User name
password
User password
htpasswd_file
Path to the htpasswd file
options
See :mod:`salt.modules.htpasswd.useradd`
force
Touch the file even if user already created
runas
The system user to run htpasswd command with
update
Update an existing user's password if it's different from what's in
the htpasswd file (unlike force, which updates regardless)
'''
ret = {'name': name,
'changes': {},
'comment': '',
'result': None}
exists = __salt__['file.grep'](
htpasswd_file, '^{0}:'.format(name))['retcode'] == 0
# If user exists, but we're supposed to update the password, find out if
# it's changed, but not if we're forced to update the file regardless.
password_changed = False
if exists and update and not force:
password_changed = not __salt__['webutil.verify'](
htpasswd_file, name, password, opts=options, runas=runas)
if not exists or password_changed or force:
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'User \'{0}\' is set to be added to htpasswd file'.format(name)
ret['changes'] = {name: True}
return ret
useradd_ret = __salt__['webutil.useradd'](htpasswd_file, name,
password, opts=options,
runas=runas)
if useradd_ret['retcode'] == 0:
ret['result'] = True
ret['comment'] = useradd_ret['stderr']
ret['changes'] = {name: True}
return ret
else:
ret['result'] = False
ret['comment'] = useradd_ret['stderr']
return ret
if __opts__['test'] and ret['changes']:
ret['result'] = None
else:
ret['result'] = True
ret['comment'] = 'User already known'
return ret | [
"def",
"user_exists",
"(",
"name",
",",
"password",
"=",
"None",
",",
"htpasswd_file",
"=",
"None",
",",
"options",
"=",
"''",
",",
"force",
"=",
"False",
",",
"runas",
"=",
"None",
",",
"update",
"=",
"False",
")",
":",
"ret",
"=",
"{",
"'name'",
... | Make sure the user is inside the specified htpasswd file
name
User name
password
User password
htpasswd_file
Path to the htpasswd file
options
See :mod:`salt.modules.htpasswd.useradd`
force
Touch the file even if user already created
runas
The system user to run htpasswd command with
update
Update an existing user's password if it's different from what's in
the htpasswd file (unlike force, which updates regardless) | [
"Make",
"sure",
"the",
"user",
"is",
"inside",
"the",
"specified",
"htpasswd",
"file"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/webutil.py#L36-L104 | train |
saltstack/salt | salt/states/webutil.py | user_absent | def user_absent(name, htpasswd_file=None, runas=None):
'''
Make sure the user is not in the specified htpasswd file
name
User name
htpasswd_file
Path to the htpasswd file
runas
The system user to run htpasswd command with
'''
ret = {'name': name,
'changes': {},
'comment': '',
'result': None}
exists = __salt__['file.grep'](
htpasswd_file, '^{0}:'.format(name))['retcode'] == 0
if not exists:
if __opts__['test']:
ret['result'] = None
else:
ret['result'] = True
ret['comment'] = 'User already not in file'
else:
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'User \'{0}\' is set to be removed from htpasswd file'.format(name)
ret['changes'] = {name: True}
else:
userdel_ret = __salt__['webutil.userdel'](
htpasswd_file, name, runas=runas, all_results=True)
ret['result'] = userdel_ret['retcode'] == 0
ret['comment'] = userdel_ret['stderr']
if ret['result']:
ret['changes'] = {name: True}
return ret | python | def user_absent(name, htpasswd_file=None, runas=None):
'''
Make sure the user is not in the specified htpasswd file
name
User name
htpasswd_file
Path to the htpasswd file
runas
The system user to run htpasswd command with
'''
ret = {'name': name,
'changes': {},
'comment': '',
'result': None}
exists = __salt__['file.grep'](
htpasswd_file, '^{0}:'.format(name))['retcode'] == 0
if not exists:
if __opts__['test']:
ret['result'] = None
else:
ret['result'] = True
ret['comment'] = 'User already not in file'
else:
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'User \'{0}\' is set to be removed from htpasswd file'.format(name)
ret['changes'] = {name: True}
else:
userdel_ret = __salt__['webutil.userdel'](
htpasswd_file, name, runas=runas, all_results=True)
ret['result'] = userdel_ret['retcode'] == 0
ret['comment'] = userdel_ret['stderr']
if ret['result']:
ret['changes'] = {name: True}
return ret | [
"def",
"user_absent",
"(",
"name",
",",
"htpasswd_file",
"=",
"None",
",",
"runas",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'comment'",
":",
"''",
",",
"'result'",
":",
"None",
"}",
"exi... | Make sure the user is not in the specified htpasswd file
name
User name
htpasswd_file
Path to the htpasswd file
runas
The system user to run htpasswd command with | [
"Make",
"sure",
"the",
"user",
"is",
"not",
"in",
"the",
"specified",
"htpasswd",
"file"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/webutil.py#L107-L150 | train |
saltstack/salt | salt/modules/celery.py | run_task | def run_task(task_name, args=None, kwargs=None, broker=None, backend=None, wait_for_result=False, timeout=None,
propagate=True, interval=0.5, no_ack=True, raise_timeout=True, config=None):
'''
Execute celery tasks. For celery specific parameters see celery documentation.
CLI Example:
.. code-block:: bash
salt '*' celery.run_task tasks.sleep args=[4] broker=redis://localhost \\
backend=redis://localhost wait_for_result=true
task_name
The task name, e.g. tasks.sleep
args
Task arguments as a list
kwargs
Task keyword arguments
broker
Broker for celeryapp, see celery documentation
backend
Result backend for celeryapp, see celery documentation
wait_for_result
Wait until task result is read from result backend and return result, Default: False
timeout
Timeout waiting for result from celery, see celery AsyncResult.get documentation
propagate
Propagate exceptions from celery task, see celery AsyncResult.get documentation, Default: True
interval
Interval to check for task result, see celery AsyncResult.get documentation, Default: 0.5
no_ack
see celery AsyncResult.get documentation. Default: True
raise_timeout
Raise timeout exception if waiting for task result times out. Default: False
config
Config dict for celery app, See celery documentation
'''
if not broker:
raise SaltInvocationError('broker parameter is required')
with Celery(broker=broker, backend=backend, set_as_current=False) as app:
if config:
app.conf.update(config)
with app.connection():
args = args or []
kwargs = kwargs or {}
async_result = app.send_task(task_name, args=args, kwargs=kwargs)
if wait_for_result:
try:
return async_result.get(timeout=timeout, propagate=propagate,
interval=interval, no_ack=no_ack)
except TimeoutError as ex:
log.error('Waiting for the result of a celery task execution timed out.')
if raise_timeout:
raise ex
return False | python | def run_task(task_name, args=None, kwargs=None, broker=None, backend=None, wait_for_result=False, timeout=None,
propagate=True, interval=0.5, no_ack=True, raise_timeout=True, config=None):
'''
Execute celery tasks. For celery specific parameters see celery documentation.
CLI Example:
.. code-block:: bash
salt '*' celery.run_task tasks.sleep args=[4] broker=redis://localhost \\
backend=redis://localhost wait_for_result=true
task_name
The task name, e.g. tasks.sleep
args
Task arguments as a list
kwargs
Task keyword arguments
broker
Broker for celeryapp, see celery documentation
backend
Result backend for celeryapp, see celery documentation
wait_for_result
Wait until task result is read from result backend and return result, Default: False
timeout
Timeout waiting for result from celery, see celery AsyncResult.get documentation
propagate
Propagate exceptions from celery task, see celery AsyncResult.get documentation, Default: True
interval
Interval to check for task result, see celery AsyncResult.get documentation, Default: 0.5
no_ack
see celery AsyncResult.get documentation. Default: True
raise_timeout
Raise timeout exception if waiting for task result times out. Default: False
config
Config dict for celery app, See celery documentation
'''
if not broker:
raise SaltInvocationError('broker parameter is required')
with Celery(broker=broker, backend=backend, set_as_current=False) as app:
if config:
app.conf.update(config)
with app.connection():
args = args or []
kwargs = kwargs or {}
async_result = app.send_task(task_name, args=args, kwargs=kwargs)
if wait_for_result:
try:
return async_result.get(timeout=timeout, propagate=propagate,
interval=interval, no_ack=no_ack)
except TimeoutError as ex:
log.error('Waiting for the result of a celery task execution timed out.')
if raise_timeout:
raise ex
return False | [
"def",
"run_task",
"(",
"task_name",
",",
"args",
"=",
"None",
",",
"kwargs",
"=",
"None",
",",
"broker",
"=",
"None",
",",
"backend",
"=",
"None",
",",
"wait_for_result",
"=",
"False",
",",
"timeout",
"=",
"None",
",",
"propagate",
"=",
"True",
",",
... | Execute celery tasks. For celery specific parameters see celery documentation.
CLI Example:
.. code-block:: bash
salt '*' celery.run_task tasks.sleep args=[4] broker=redis://localhost \\
backend=redis://localhost wait_for_result=true
task_name
The task name, e.g. tasks.sleep
args
Task arguments as a list
kwargs
Task keyword arguments
broker
Broker for celeryapp, see celery documentation
backend
Result backend for celeryapp, see celery documentation
wait_for_result
Wait until task result is read from result backend and return result, Default: False
timeout
Timeout waiting for result from celery, see celery AsyncResult.get documentation
propagate
Propagate exceptions from celery task, see celery AsyncResult.get documentation, Default: True
interval
Interval to check for task result, see celery AsyncResult.get documentation, Default: 0.5
no_ack
see celery AsyncResult.get documentation. Default: True
raise_timeout
Raise timeout exception if waiting for task result times out. Default: False
config
Config dict for celery app, See celery documentation | [
"Execute",
"celery",
"tasks",
".",
"For",
"celery",
"specific",
"parameters",
"see",
"celery",
"documentation",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/celery.py#L40-L110 | train |
saltstack/salt | salt/client/api.py | APIClient.run | def run(self, cmd):
'''
Execute the salt command given by cmd dict.
cmd is a dictionary of the following form:
{
'mode': 'modestring',
'fun' : 'modulefunctionstring',
'kwarg': functionkeywordargdictionary,
'tgt' : 'targetpatternstring',
'tgt_type' : 'targetpatterntype',
'ret' : 'returner namestring',
'timeout': 'functiontimeout',
'arg' : 'functionpositionalarg sequence',
'token': 'salttokenstring',
'username': 'usernamestring',
'password': 'passwordstring',
'eauth': 'eauthtypestring',
}
Implied by the fun is which client is used to run the command, that is, either
the master local minion client, the master runner client, or the master wheel client.
The cmd dict items are as follows:
mode: either 'sync' or 'asynchronous'. Defaults to 'asynchronous' if missing
fun: required. If the function is to be run on the master using either
a wheel or runner client then the fun: includes either
'wheel.' or 'runner.' as a prefix and has three parts separated by '.'.
Otherwise the fun: specifies a module to be run on a minion via the local
minion client.
Example:
fun of 'wheel.config.values' run with master wheel client
fun of 'runner.manage.status' run with master runner client
fun of 'test.ping' run with local minion client
fun of 'wheel.foobar' run with with local minion client not wheel
kwarg: A dictionary of keyword function parameters to be passed to the eventual
salt function specified by fun:
tgt: Pattern string specifying the targeted minions when the implied client is local
tgt_type: Optional target pattern type string when client is local minion.
Defaults to 'glob' if missing
ret: Optional name string of returner when local minion client.
arg: Optional positional argument string when local minion client
token: the salt token. Either token: is required or the set of username:,
password: , and eauth:
username: the salt username. Required if token is missing.
password: the user's password. Required if token is missing.
eauth: the authentication type such as 'pam' or 'ldap'. Required if token is missing
'''
cmd = dict(cmd) # make copy
client = 'minion' # default to local minion client
mode = cmd.get('mode', 'async')
# check for wheel or runner prefix to fun name to use wheel or runner client
funparts = cmd.get('fun', '').split('.')
if len(funparts) > 2 and funparts[0] in ['wheel', 'runner']: # master
client = funparts[0]
cmd['fun'] = '.'.join(funparts[1:]) # strip prefix
if not ('token' in cmd or
('eauth' in cmd and 'password' in cmd and 'username' in cmd)):
raise EauthAuthenticationError('No authentication credentials given')
executor = getattr(self, '{0}_{1}'.format(client, mode))
result = executor(**cmd)
return result | python | def run(self, cmd):
'''
Execute the salt command given by cmd dict.
cmd is a dictionary of the following form:
{
'mode': 'modestring',
'fun' : 'modulefunctionstring',
'kwarg': functionkeywordargdictionary,
'tgt' : 'targetpatternstring',
'tgt_type' : 'targetpatterntype',
'ret' : 'returner namestring',
'timeout': 'functiontimeout',
'arg' : 'functionpositionalarg sequence',
'token': 'salttokenstring',
'username': 'usernamestring',
'password': 'passwordstring',
'eauth': 'eauthtypestring',
}
Implied by the fun is which client is used to run the command, that is, either
the master local minion client, the master runner client, or the master wheel client.
The cmd dict items are as follows:
mode: either 'sync' or 'asynchronous'. Defaults to 'asynchronous' if missing
fun: required. If the function is to be run on the master using either
a wheel or runner client then the fun: includes either
'wheel.' or 'runner.' as a prefix and has three parts separated by '.'.
Otherwise the fun: specifies a module to be run on a minion via the local
minion client.
Example:
fun of 'wheel.config.values' run with master wheel client
fun of 'runner.manage.status' run with master runner client
fun of 'test.ping' run with local minion client
fun of 'wheel.foobar' run with with local minion client not wheel
kwarg: A dictionary of keyword function parameters to be passed to the eventual
salt function specified by fun:
tgt: Pattern string specifying the targeted minions when the implied client is local
tgt_type: Optional target pattern type string when client is local minion.
Defaults to 'glob' if missing
ret: Optional name string of returner when local minion client.
arg: Optional positional argument string when local minion client
token: the salt token. Either token: is required or the set of username:,
password: , and eauth:
username: the salt username. Required if token is missing.
password: the user's password. Required if token is missing.
eauth: the authentication type such as 'pam' or 'ldap'. Required if token is missing
'''
cmd = dict(cmd) # make copy
client = 'minion' # default to local minion client
mode = cmd.get('mode', 'async')
# check for wheel or runner prefix to fun name to use wheel or runner client
funparts = cmd.get('fun', '').split('.')
if len(funparts) > 2 and funparts[0] in ['wheel', 'runner']: # master
client = funparts[0]
cmd['fun'] = '.'.join(funparts[1:]) # strip prefix
if not ('token' in cmd or
('eauth' in cmd and 'password' in cmd and 'username' in cmd)):
raise EauthAuthenticationError('No authentication credentials given')
executor = getattr(self, '{0}_{1}'.format(client, mode))
result = executor(**cmd)
return result | [
"def",
"run",
"(",
"self",
",",
"cmd",
")",
":",
"cmd",
"=",
"dict",
"(",
"cmd",
")",
"# make copy",
"client",
"=",
"'minion'",
"# default to local minion client",
"mode",
"=",
"cmd",
".",
"get",
"(",
"'mode'",
",",
"'async'",
")",
"# check for wheel or runn... | Execute the salt command given by cmd dict.
cmd is a dictionary of the following form:
{
'mode': 'modestring',
'fun' : 'modulefunctionstring',
'kwarg': functionkeywordargdictionary,
'tgt' : 'targetpatternstring',
'tgt_type' : 'targetpatterntype',
'ret' : 'returner namestring',
'timeout': 'functiontimeout',
'arg' : 'functionpositionalarg sequence',
'token': 'salttokenstring',
'username': 'usernamestring',
'password': 'passwordstring',
'eauth': 'eauthtypestring',
}
Implied by the fun is which client is used to run the command, that is, either
the master local minion client, the master runner client, or the master wheel client.
The cmd dict items are as follows:
mode: either 'sync' or 'asynchronous'. Defaults to 'asynchronous' if missing
fun: required. If the function is to be run on the master using either
a wheel or runner client then the fun: includes either
'wheel.' or 'runner.' as a prefix and has three parts separated by '.'.
Otherwise the fun: specifies a module to be run on a minion via the local
minion client.
Example:
fun of 'wheel.config.values' run with master wheel client
fun of 'runner.manage.status' run with master runner client
fun of 'test.ping' run with local minion client
fun of 'wheel.foobar' run with with local minion client not wheel
kwarg: A dictionary of keyword function parameters to be passed to the eventual
salt function specified by fun:
tgt: Pattern string specifying the targeted minions when the implied client is local
tgt_type: Optional target pattern type string when client is local minion.
Defaults to 'glob' if missing
ret: Optional name string of returner when local minion client.
arg: Optional positional argument string when local minion client
token: the salt token. Either token: is required or the set of username:,
password: , and eauth:
username: the salt username. Required if token is missing.
password: the user's password. Required if token is missing.
eauth: the authentication type such as 'pam' or 'ldap'. Required if token is missing | [
"Execute",
"the",
"salt",
"command",
"given",
"by",
"cmd",
"dict",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/api.py#L70-L137 | train |
saltstack/salt | salt/client/api.py | APIClient.signature | def signature(self, cmd):
'''
Convenience function that returns dict of function signature(s) specified by cmd.
cmd is dict of the form:
{
'module' : 'modulestring',
'tgt' : 'targetpatternstring',
'tgt_type' : 'targetpatterntype',
'token': 'salttokenstring',
'username': 'usernamestring',
'password': 'passwordstring',
'eauth': 'eauthtypestring',
}
The cmd dict items are as follows:
module: required. This is either a module or module function name for
the specified client.
tgt: Optional pattern string specifying the targeted minions when client
is 'minion'
tgt_type: Optional target pattern type string when client is 'minion'.
Example: 'glob' defaults to 'glob' if missing
token: the salt token. Either token: is required or the set of username:,
password: , and eauth:
username: the salt username. Required if token is missing.
password: the user's password. Required if token is missing.
eauth: the authentication type such as 'pam' or 'ldap'. Required if token is missing
Adds client per the command.
'''
cmd['client'] = 'minion'
if len(cmd['module'].split('.')) > 2 and cmd['module'].split('.')[0] in ['runner', 'wheel']:
cmd['client'] = 'master'
return self._signature(cmd) | python | def signature(self, cmd):
'''
Convenience function that returns dict of function signature(s) specified by cmd.
cmd is dict of the form:
{
'module' : 'modulestring',
'tgt' : 'targetpatternstring',
'tgt_type' : 'targetpatterntype',
'token': 'salttokenstring',
'username': 'usernamestring',
'password': 'passwordstring',
'eauth': 'eauthtypestring',
}
The cmd dict items are as follows:
module: required. This is either a module or module function name for
the specified client.
tgt: Optional pattern string specifying the targeted minions when client
is 'minion'
tgt_type: Optional target pattern type string when client is 'minion'.
Example: 'glob' defaults to 'glob' if missing
token: the salt token. Either token: is required or the set of username:,
password: , and eauth:
username: the salt username. Required if token is missing.
password: the user's password. Required if token is missing.
eauth: the authentication type such as 'pam' or 'ldap'. Required if token is missing
Adds client per the command.
'''
cmd['client'] = 'minion'
if len(cmd['module'].split('.')) > 2 and cmd['module'].split('.')[0] in ['runner', 'wheel']:
cmd['client'] = 'master'
return self._signature(cmd) | [
"def",
"signature",
"(",
"self",
",",
"cmd",
")",
":",
"cmd",
"[",
"'client'",
"]",
"=",
"'minion'",
"if",
"len",
"(",
"cmd",
"[",
"'module'",
"]",
".",
"split",
"(",
"'.'",
")",
")",
">",
"2",
"and",
"cmd",
"[",
"'module'",
"]",
".",
"split",
... | Convenience function that returns dict of function signature(s) specified by cmd.
cmd is dict of the form:
{
'module' : 'modulestring',
'tgt' : 'targetpatternstring',
'tgt_type' : 'targetpatterntype',
'token': 'salttokenstring',
'username': 'usernamestring',
'password': 'passwordstring',
'eauth': 'eauthtypestring',
}
The cmd dict items are as follows:
module: required. This is either a module or module function name for
the specified client.
tgt: Optional pattern string specifying the targeted minions when client
is 'minion'
tgt_type: Optional target pattern type string when client is 'minion'.
Example: 'glob' defaults to 'glob' if missing
token: the salt token. Either token: is required or the set of username:,
password: , and eauth:
username: the salt username. Required if token is missing.
password: the user's password. Required if token is missing.
eauth: the authentication type such as 'pam' or 'ldap'. Required if token is missing
Adds client per the command. | [
"Convenience",
"function",
"that",
"returns",
"dict",
"of",
"function",
"signature",
"(",
"s",
")",
"specified",
"by",
"cmd",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/api.py#L177-L211 | train |
saltstack/salt | salt/client/api.py | APIClient._signature | def _signature(self, cmd):
'''
Expects everything that signature does and also a client type string.
client can either be master or minion.
'''
result = {}
client = cmd.get('client', 'minion')
if client == 'minion':
cmd['fun'] = 'sys.argspec'
cmd['kwarg'] = dict(module=cmd['module'])
result = self.run(cmd)
elif client == 'master':
parts = cmd['module'].split('.')
client = parts[0]
module = '.'.join(parts[1:]) # strip prefix
if client == 'wheel':
functions = self.wheelClient.functions
elif client == 'runner':
functions = self.runnerClient.functions
result = {'master': salt.utils.args.argspec_report(functions, module)}
return result | python | def _signature(self, cmd):
'''
Expects everything that signature does and also a client type string.
client can either be master or minion.
'''
result = {}
client = cmd.get('client', 'minion')
if client == 'minion':
cmd['fun'] = 'sys.argspec'
cmd['kwarg'] = dict(module=cmd['module'])
result = self.run(cmd)
elif client == 'master':
parts = cmd['module'].split('.')
client = parts[0]
module = '.'.join(parts[1:]) # strip prefix
if client == 'wheel':
functions = self.wheelClient.functions
elif client == 'runner':
functions = self.runnerClient.functions
result = {'master': salt.utils.args.argspec_report(functions, module)}
return result | [
"def",
"_signature",
"(",
"self",
",",
"cmd",
")",
":",
"result",
"=",
"{",
"}",
"client",
"=",
"cmd",
".",
"get",
"(",
"'client'",
",",
"'minion'",
")",
"if",
"client",
"==",
"'minion'",
":",
"cmd",
"[",
"'fun'",
"]",
"=",
"'sys.argspec'",
"cmd",
... | Expects everything that signature does and also a client type string.
client can either be master or minion. | [
"Expects",
"everything",
"that",
"signature",
"does",
"and",
"also",
"a",
"client",
"type",
"string",
".",
"client",
"can",
"either",
"be",
"master",
"or",
"minion",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/api.py#L213-L234 | train |
saltstack/salt | salt/client/api.py | APIClient.create_token | def create_token(self, creds):
'''
Create token with creds.
Token authorizes salt access if successful authentication
with the credentials in creds.
creds format is as follows:
{
'username': 'namestring',
'password': 'passwordstring',
'eauth': 'eauthtypestring',
}
examples of valid eauth type strings: 'pam' or 'ldap'
Returns dictionary of token information with the following format:
{
'token': 'tokenstring',
'start': starttimeinfractionalseconds,
'expire': expiretimeinfractionalseconds,
'name': 'usernamestring',
'user': 'usernamestring',
'username': 'usernamestring',
'eauth': 'eauthtypestring',
'perms: permslistofstrings,
}
The perms list provides those parts of salt for which the user is authorised
to execute.
example perms list:
[
"grains.*",
"status.*",
"sys.*",
"test.*"
]
'''
try:
tokenage = self.resolver.mk_token(creds)
except Exception as ex:
raise EauthAuthenticationError(
"Authentication failed with {0}.".format(repr(ex)))
if 'token' not in tokenage:
raise EauthAuthenticationError("Authentication failed with provided credentials.")
# Grab eauth config for the current backend for the current user
tokenage_eauth = self.opts['external_auth'][tokenage['eauth']]
if tokenage['name'] in tokenage_eauth:
tokenage['perms'] = tokenage_eauth[tokenage['name']]
else:
tokenage['perms'] = tokenage_eauth['*']
tokenage['user'] = tokenage['name']
tokenage['username'] = tokenage['name']
return tokenage | python | def create_token(self, creds):
'''
Create token with creds.
Token authorizes salt access if successful authentication
with the credentials in creds.
creds format is as follows:
{
'username': 'namestring',
'password': 'passwordstring',
'eauth': 'eauthtypestring',
}
examples of valid eauth type strings: 'pam' or 'ldap'
Returns dictionary of token information with the following format:
{
'token': 'tokenstring',
'start': starttimeinfractionalseconds,
'expire': expiretimeinfractionalseconds,
'name': 'usernamestring',
'user': 'usernamestring',
'username': 'usernamestring',
'eauth': 'eauthtypestring',
'perms: permslistofstrings,
}
The perms list provides those parts of salt for which the user is authorised
to execute.
example perms list:
[
"grains.*",
"status.*",
"sys.*",
"test.*"
]
'''
try:
tokenage = self.resolver.mk_token(creds)
except Exception as ex:
raise EauthAuthenticationError(
"Authentication failed with {0}.".format(repr(ex)))
if 'token' not in tokenage:
raise EauthAuthenticationError("Authentication failed with provided credentials.")
# Grab eauth config for the current backend for the current user
tokenage_eauth = self.opts['external_auth'][tokenage['eauth']]
if tokenage['name'] in tokenage_eauth:
tokenage['perms'] = tokenage_eauth[tokenage['name']]
else:
tokenage['perms'] = tokenage_eauth['*']
tokenage['user'] = tokenage['name']
tokenage['username'] = tokenage['name']
return tokenage | [
"def",
"create_token",
"(",
"self",
",",
"creds",
")",
":",
"try",
":",
"tokenage",
"=",
"self",
".",
"resolver",
".",
"mk_token",
"(",
"creds",
")",
"except",
"Exception",
"as",
"ex",
":",
"raise",
"EauthAuthenticationError",
"(",
"\"Authentication failed wit... | Create token with creds.
Token authorizes salt access if successful authentication
with the credentials in creds.
creds format is as follows:
{
'username': 'namestring',
'password': 'passwordstring',
'eauth': 'eauthtypestring',
}
examples of valid eauth type strings: 'pam' or 'ldap'
Returns dictionary of token information with the following format:
{
'token': 'tokenstring',
'start': starttimeinfractionalseconds,
'expire': expiretimeinfractionalseconds,
'name': 'usernamestring',
'user': 'usernamestring',
'username': 'usernamestring',
'eauth': 'eauthtypestring',
'perms: permslistofstrings,
}
The perms list provides those parts of salt for which the user is authorised
to execute.
example perms list:
[
"grains.*",
"status.*",
"sys.*",
"test.*"
] | [
"Create",
"token",
"with",
"creds",
".",
"Token",
"authorizes",
"salt",
"access",
"if",
"successful",
"authentication",
"with",
"the",
"credentials",
"in",
"creds",
".",
"creds",
"format",
"is",
"as",
"follows",
":"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/api.py#L236-L293 | train |
saltstack/salt | salt/client/api.py | APIClient.verify_token | def verify_token(self, token):
'''
If token is valid Then returns user name associated with token
Else False.
'''
try:
result = self.resolver.get_token(token)
except Exception as ex:
raise EauthAuthenticationError(
"Token validation failed with {0}.".format(repr(ex)))
return result | python | def verify_token(self, token):
'''
If token is valid Then returns user name associated with token
Else False.
'''
try:
result = self.resolver.get_token(token)
except Exception as ex:
raise EauthAuthenticationError(
"Token validation failed with {0}.".format(repr(ex)))
return result | [
"def",
"verify_token",
"(",
"self",
",",
"token",
")",
":",
"try",
":",
"result",
"=",
"self",
".",
"resolver",
".",
"get_token",
"(",
"token",
")",
"except",
"Exception",
"as",
"ex",
":",
"raise",
"EauthAuthenticationError",
"(",
"\"Token validation failed wi... | If token is valid Then returns user name associated with token
Else False. | [
"If",
"token",
"is",
"valid",
"Then",
"returns",
"user",
"name",
"associated",
"with",
"token",
"Else",
"False",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/api.py#L295-L306 | train |
saltstack/salt | salt/client/api.py | APIClient.get_event | def get_event(self, wait=0.25, tag='', full=False):
'''
Get a single salt event.
If no events are available, then block for up to ``wait`` seconds.
Return the event if it matches the tag (or ``tag`` is empty)
Otherwise return None
If wait is 0 then block forever or until next event becomes available.
'''
return self.event.get_event(wait=wait, tag=tag, full=full, auto_reconnect=True) | python | def get_event(self, wait=0.25, tag='', full=False):
'''
Get a single salt event.
If no events are available, then block for up to ``wait`` seconds.
Return the event if it matches the tag (or ``tag`` is empty)
Otherwise return None
If wait is 0 then block forever or until next event becomes available.
'''
return self.event.get_event(wait=wait, tag=tag, full=full, auto_reconnect=True) | [
"def",
"get_event",
"(",
"self",
",",
"wait",
"=",
"0.25",
",",
"tag",
"=",
"''",
",",
"full",
"=",
"False",
")",
":",
"return",
"self",
".",
"event",
".",
"get_event",
"(",
"wait",
"=",
"wait",
",",
"tag",
"=",
"tag",
",",
"full",
"=",
"full",
... | Get a single salt event.
If no events are available, then block for up to ``wait`` seconds.
Return the event if it matches the tag (or ``tag`` is empty)
Otherwise return None
If wait is 0 then block forever or until next event becomes available. | [
"Get",
"a",
"single",
"salt",
"event",
".",
"If",
"no",
"events",
"are",
"available",
"then",
"block",
"for",
"up",
"to",
"wait",
"seconds",
".",
"Return",
"the",
"event",
"if",
"it",
"matches",
"the",
"tag",
"(",
"or",
"tag",
"is",
"empty",
")",
"Ot... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/api.py#L308-L317 | train |
saltstack/salt | salt/client/api.py | APIClient.fire_event | def fire_event(self, data, tag):
'''
fires event with data and tag
This only works if api is running with same user permissions as master
Need to convert this to a master call with appropriate authentication
'''
return self.event.fire_event(data, salt.utils.event.tagify(tag, 'wui')) | python | def fire_event(self, data, tag):
'''
fires event with data and tag
This only works if api is running with same user permissions as master
Need to convert this to a master call with appropriate authentication
'''
return self.event.fire_event(data, salt.utils.event.tagify(tag, 'wui')) | [
"def",
"fire_event",
"(",
"self",
",",
"data",
",",
"tag",
")",
":",
"return",
"self",
".",
"event",
".",
"fire_event",
"(",
"data",
",",
"salt",
".",
"utils",
".",
"event",
".",
"tagify",
"(",
"tag",
",",
"'wui'",
")",
")"
] | fires event with data and tag
This only works if api is running with same user permissions as master
Need to convert this to a master call with appropriate authentication | [
"fires",
"event",
"with",
"data",
"and",
"tag",
"This",
"only",
"works",
"if",
"api",
"is",
"running",
"with",
"same",
"user",
"permissions",
"as",
"master",
"Need",
"to",
"convert",
"this",
"to",
"a",
"master",
"call",
"with",
"appropriate",
"authentication... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/api.py#L319-L326 | train |
saltstack/salt | salt/modules/win_timezone.py | get_zone | def get_zone():
'''
Get current timezone (i.e. America/Denver)
Returns:
str: Timezone in unix format
Raises:
CommandExecutionError: If timezone could not be gathered
CLI Example:
.. code-block:: bash
salt '*' timezone.get_zone
'''
cmd = ['tzutil', '/g']
res = __salt__['cmd.run_all'](cmd, python_shell=False)
if res['retcode'] or not res['stdout']:
raise CommandExecutionError('tzutil encountered an error getting '
'timezone',
info=res)
return mapper.get_unix(res['stdout'].lower(), 'Unknown') | python | def get_zone():
'''
Get current timezone (i.e. America/Denver)
Returns:
str: Timezone in unix format
Raises:
CommandExecutionError: If timezone could not be gathered
CLI Example:
.. code-block:: bash
salt '*' timezone.get_zone
'''
cmd = ['tzutil', '/g']
res = __salt__['cmd.run_all'](cmd, python_shell=False)
if res['retcode'] or not res['stdout']:
raise CommandExecutionError('tzutil encountered an error getting '
'timezone',
info=res)
return mapper.get_unix(res['stdout'].lower(), 'Unknown') | [
"def",
"get_zone",
"(",
")",
":",
"cmd",
"=",
"[",
"'tzutil'",
",",
"'/g'",
"]",
"res",
"=",
"__salt__",
"[",
"'cmd.run_all'",
"]",
"(",
"cmd",
",",
"python_shell",
"=",
"False",
")",
"if",
"res",
"[",
"'retcode'",
"]",
"or",
"not",
"res",
"[",
"'s... | Get current timezone (i.e. America/Denver)
Returns:
str: Timezone in unix format
Raises:
CommandExecutionError: If timezone could not be gathered
CLI Example:
.. code-block:: bash
salt '*' timezone.get_zone | [
"Get",
"current",
"timezone",
"(",
"i",
".",
"e",
".",
"America",
"/",
"Denver",
")"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_timezone.py#L201-L223 | train |
saltstack/salt | salt/modules/win_timezone.py | get_offset | def get_offset():
'''
Get current numeric timezone offset from UTC (i.e. -0700)
Returns:
str: Offset from UTC
CLI Example:
.. code-block:: bash
salt '*' timezone.get_offset
'''
# http://craigglennie.com/programming/python/2013/07/21/working-with-timezones-using-Python-and-pytz-localize-vs-normalize/
tz_object = pytz.timezone(get_zone())
utc_time = pytz.utc.localize(datetime.utcnow())
loc_time = utc_time.astimezone(tz_object)
norm_time = tz_object.normalize(loc_time)
return norm_time.strftime('%z') | python | def get_offset():
'''
Get current numeric timezone offset from UTC (i.e. -0700)
Returns:
str: Offset from UTC
CLI Example:
.. code-block:: bash
salt '*' timezone.get_offset
'''
# http://craigglennie.com/programming/python/2013/07/21/working-with-timezones-using-Python-and-pytz-localize-vs-normalize/
tz_object = pytz.timezone(get_zone())
utc_time = pytz.utc.localize(datetime.utcnow())
loc_time = utc_time.astimezone(tz_object)
norm_time = tz_object.normalize(loc_time)
return norm_time.strftime('%z') | [
"def",
"get_offset",
"(",
")",
":",
"# http://craigglennie.com/programming/python/2013/07/21/working-with-timezones-using-Python-and-pytz-localize-vs-normalize/",
"tz_object",
"=",
"pytz",
".",
"timezone",
"(",
"get_zone",
"(",
")",
")",
"utc_time",
"=",
"pytz",
".",
"utc",
... | Get current numeric timezone offset from UTC (i.e. -0700)
Returns:
str: Offset from UTC
CLI Example:
.. code-block:: bash
salt '*' timezone.get_offset | [
"Get",
"current",
"numeric",
"timezone",
"offset",
"from",
"UTC",
"(",
"i",
".",
"e",
".",
"-",
"0700",
")"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_timezone.py#L226-L244 | train |
saltstack/salt | salt/modules/win_timezone.py | get_zonecode | def get_zonecode():
'''
Get current timezone (i.e. PST, MDT, etc)
Returns:
str: An abbreviated timezone code
CLI Example:
.. code-block:: bash
salt '*' timezone.get_zonecode
'''
tz_object = pytz.timezone(get_zone())
loc_time = tz_object.localize(datetime.utcnow())
return loc_time.tzname() | python | def get_zonecode():
'''
Get current timezone (i.e. PST, MDT, etc)
Returns:
str: An abbreviated timezone code
CLI Example:
.. code-block:: bash
salt '*' timezone.get_zonecode
'''
tz_object = pytz.timezone(get_zone())
loc_time = tz_object.localize(datetime.utcnow())
return loc_time.tzname() | [
"def",
"get_zonecode",
"(",
")",
":",
"tz_object",
"=",
"pytz",
".",
"timezone",
"(",
"get_zone",
"(",
")",
")",
"loc_time",
"=",
"tz_object",
".",
"localize",
"(",
"datetime",
".",
"utcnow",
"(",
")",
")",
"return",
"loc_time",
".",
"tzname",
"(",
")"... | Get current timezone (i.e. PST, MDT, etc)
Returns:
str: An abbreviated timezone code
CLI Example:
.. code-block:: bash
salt '*' timezone.get_zonecode | [
"Get",
"current",
"timezone",
"(",
"i",
".",
"e",
".",
"PST",
"MDT",
"etc",
")"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_timezone.py#L247-L262 | train |
saltstack/salt | salt/modules/win_timezone.py | set_zone | def set_zone(timezone):
'''
Sets the timezone using the tzutil.
Args:
timezone (str): A valid timezone
Returns:
bool: ``True`` if successful, otherwise ``False``
Raises:
CommandExecutionError: If invalid timezone is passed
CLI Example:
.. code-block:: bash
salt '*' timezone.set_zone 'America/Denver'
'''
# if it's one of the key's just use it
if timezone.lower() in mapper.win_to_unix:
win_zone = timezone
elif timezone.lower() in mapper.unix_to_win:
# if it's one of the values, use the key
win_zone = mapper.get_win(timezone)
else:
# Raise error because it's neither key nor value
raise CommandExecutionError('Invalid timezone passed: {0}'.format(timezone))
# Set the value
cmd = ['tzutil', '/s', win_zone]
res = __salt__['cmd.run_all'](cmd, python_shell=False)
if res['retcode']:
raise CommandExecutionError('tzutil encountered an error setting '
'timezone: {0}'.format(timezone),
info=res)
return zone_compare(timezone) | python | def set_zone(timezone):
'''
Sets the timezone using the tzutil.
Args:
timezone (str): A valid timezone
Returns:
bool: ``True`` if successful, otherwise ``False``
Raises:
CommandExecutionError: If invalid timezone is passed
CLI Example:
.. code-block:: bash
salt '*' timezone.set_zone 'America/Denver'
'''
# if it's one of the key's just use it
if timezone.lower() in mapper.win_to_unix:
win_zone = timezone
elif timezone.lower() in mapper.unix_to_win:
# if it's one of the values, use the key
win_zone = mapper.get_win(timezone)
else:
# Raise error because it's neither key nor value
raise CommandExecutionError('Invalid timezone passed: {0}'.format(timezone))
# Set the value
cmd = ['tzutil', '/s', win_zone]
res = __salt__['cmd.run_all'](cmd, python_shell=False)
if res['retcode']:
raise CommandExecutionError('tzutil encountered an error setting '
'timezone: {0}'.format(timezone),
info=res)
return zone_compare(timezone) | [
"def",
"set_zone",
"(",
"timezone",
")",
":",
"# if it's one of the key's just use it",
"if",
"timezone",
".",
"lower",
"(",
")",
"in",
"mapper",
".",
"win_to_unix",
":",
"win_zone",
"=",
"timezone",
"elif",
"timezone",
".",
"lower",
"(",
")",
"in",
"mapper",
... | Sets the timezone using the tzutil.
Args:
timezone (str): A valid timezone
Returns:
bool: ``True`` if successful, otherwise ``False``
Raises:
CommandExecutionError: If invalid timezone is passed
CLI Example:
.. code-block:: bash
salt '*' timezone.set_zone 'America/Denver' | [
"Sets",
"the",
"timezone",
"using",
"the",
"tzutil",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_timezone.py#L265-L303 | train |
saltstack/salt | salt/modules/win_timezone.py | zone_compare | def zone_compare(timezone):
'''
Compares the given timezone with the machine timezone. Mostly useful for
running state checks.
Args:
timezone (str):
The timezone to compare. This can be in Windows or Unix format. Can
be any of the values returned by the ``timezone.list`` function
Returns:
bool: ``True`` if they match, otherwise ``False``
Example:
.. code-block:: bash
salt '*' timezone.zone_compare 'America/Denver'
'''
# if it's one of the key's just use it
if timezone.lower() in mapper.win_to_unix:
check_zone = timezone
elif timezone.lower() in mapper.unix_to_win:
# if it's one of the values, use the key
check_zone = mapper.get_win(timezone)
else:
# Raise error because it's neither key nor value
raise CommandExecutionError('Invalid timezone passed: {0}'
''.format(timezone))
return get_zone() == mapper.get_unix(check_zone, 'Unknown') | python | def zone_compare(timezone):
'''
Compares the given timezone with the machine timezone. Mostly useful for
running state checks.
Args:
timezone (str):
The timezone to compare. This can be in Windows or Unix format. Can
be any of the values returned by the ``timezone.list`` function
Returns:
bool: ``True`` if they match, otherwise ``False``
Example:
.. code-block:: bash
salt '*' timezone.zone_compare 'America/Denver'
'''
# if it's one of the key's just use it
if timezone.lower() in mapper.win_to_unix:
check_zone = timezone
elif timezone.lower() in mapper.unix_to_win:
# if it's one of the values, use the key
check_zone = mapper.get_win(timezone)
else:
# Raise error because it's neither key nor value
raise CommandExecutionError('Invalid timezone passed: {0}'
''.format(timezone))
return get_zone() == mapper.get_unix(check_zone, 'Unknown') | [
"def",
"zone_compare",
"(",
"timezone",
")",
":",
"# if it's one of the key's just use it",
"if",
"timezone",
".",
"lower",
"(",
")",
"in",
"mapper",
".",
"win_to_unix",
":",
"check_zone",
"=",
"timezone",
"elif",
"timezone",
".",
"lower",
"(",
")",
"in",
"map... | Compares the given timezone with the machine timezone. Mostly useful for
running state checks.
Args:
timezone (str):
The timezone to compare. This can be in Windows or Unix format. Can
be any of the values returned by the ``timezone.list`` function
Returns:
bool: ``True`` if they match, otherwise ``False``
Example:
.. code-block:: bash
salt '*' timezone.zone_compare 'America/Denver' | [
"Compares",
"the",
"given",
"timezone",
"with",
"the",
"machine",
"timezone",
".",
"Mostly",
"useful",
"for",
"running",
"state",
"checks",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_timezone.py#L306-L338 | train |
saltstack/salt | salt/states/win_license.py | activate | def activate(name):
'''
Install and activate the given product key
name
The 5x5 product key given to you by Microsoft
'''
ret = {'name': name,
'result': True,
'comment': '',
'changes': {}}
product_key = name
license_info = __salt__['license.info']()
licensed = False
key_match = False
if license_info is not None:
licensed = license_info['licensed']
key_match = license_info['partial_key'] in product_key
if not key_match:
out = __salt__['license.install'](product_key)
licensed = False
if 'successfully' not in out:
ret['result'] = False
ret['comment'] += 'Unable to install the given product key is it valid?'
return ret
if not licensed:
out = __salt__['license.activate']()
if 'successfully' not in out:
ret['result'] = False
ret['comment'] += 'Unable to activate the given product key.'
return ret
ret['comment'] += 'Windows is now activated.'
else:
ret['comment'] += 'Windows is already activated.'
return ret | python | def activate(name):
'''
Install and activate the given product key
name
The 5x5 product key given to you by Microsoft
'''
ret = {'name': name,
'result': True,
'comment': '',
'changes': {}}
product_key = name
license_info = __salt__['license.info']()
licensed = False
key_match = False
if license_info is not None:
licensed = license_info['licensed']
key_match = license_info['partial_key'] in product_key
if not key_match:
out = __salt__['license.install'](product_key)
licensed = False
if 'successfully' not in out:
ret['result'] = False
ret['comment'] += 'Unable to install the given product key is it valid?'
return ret
if not licensed:
out = __salt__['license.activate']()
if 'successfully' not in out:
ret['result'] = False
ret['comment'] += 'Unable to activate the given product key.'
return ret
ret['comment'] += 'Windows is now activated.'
else:
ret['comment'] += 'Windows is already activated.'
return ret | [
"def",
"activate",
"(",
"name",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",
"''",
",",
"'changes'",
":",
"{",
"}",
"}",
"product_key",
"=",
"name",
"license_info",
"=",
"__salt__",
"[",
"'lic... | Install and activate the given product key
name
The 5x5 product key given to you by Microsoft | [
"Install",
"and",
"activate",
"the",
"given",
"product",
"key"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/win_license.py#L33-L71 | train |
saltstack/salt | salt/states/quota.py | mode | def mode(name, mode, quotatype):
'''
Set the quota for the system
name
The filesystem to set the quota mode on
mode
Whether the quota system is on or off
quotatype
Must be ``user`` or ``group``
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
fun = 'off'
if mode is True:
fun = 'on'
if __salt__['quota.get_mode'](name)[name][quotatype] == fun:
ret['result'] = True
ret['comment'] = 'Quota for {0} already set to {1}'.format(name, fun)
return ret
if __opts__['test']:
ret['comment'] = 'Quota for {0} needs to be set to {1}'.format(name,
fun)
return ret
if __salt__['quota.{0}'.format(fun)](name):
ret['changes'] = {'quota': name}
ret['result'] = True
ret['comment'] = 'Set quota for {0} to {1}'.format(name, fun)
return ret
else:
ret['result'] = False
ret['comment'] = 'Failed to set quota for {0} to {1}'.format(name, fun)
return ret | python | def mode(name, mode, quotatype):
'''
Set the quota for the system
name
The filesystem to set the quota mode on
mode
Whether the quota system is on or off
quotatype
Must be ``user`` or ``group``
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
fun = 'off'
if mode is True:
fun = 'on'
if __salt__['quota.get_mode'](name)[name][quotatype] == fun:
ret['result'] = True
ret['comment'] = 'Quota for {0} already set to {1}'.format(name, fun)
return ret
if __opts__['test']:
ret['comment'] = 'Quota for {0} needs to be set to {1}'.format(name,
fun)
return ret
if __salt__['quota.{0}'.format(fun)](name):
ret['changes'] = {'quota': name}
ret['result'] = True
ret['comment'] = 'Set quota for {0} to {1}'.format(name, fun)
return ret
else:
ret['result'] = False
ret['comment'] = 'Failed to set quota for {0} to {1}'.format(name, fun)
return ret | [
"def",
"mode",
"(",
"name",
",",
"mode",
",",
"quotatype",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"None",
",",
"'comment'",
":",
"''",
"}",
"fun",
"=",
"'off'",
"if",
"mode",
"is",... | Set the quota for the system
name
The filesystem to set the quota mode on
mode
Whether the quota system is on or off
quotatype
Must be ``user`` or ``group`` | [
"Set",
"the",
"quota",
"for",
"the",
"system"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/quota.py#L26-L62 | train |
saltstack/salt | salt/modules/quota.py | report | def report(mount):
'''
Report on quotas for a specific volume
CLI Example:
.. code-block:: bash
salt '*' quota.report /media/data
'''
ret = {mount: {}}
ret[mount]['User Quotas'] = _parse_quota(mount, '-u')
ret[mount]['Group Quotas'] = _parse_quota(mount, '-g')
return ret | python | def report(mount):
'''
Report on quotas for a specific volume
CLI Example:
.. code-block:: bash
salt '*' quota.report /media/data
'''
ret = {mount: {}}
ret[mount]['User Quotas'] = _parse_quota(mount, '-u')
ret[mount]['Group Quotas'] = _parse_quota(mount, '-g')
return ret | [
"def",
"report",
"(",
"mount",
")",
":",
"ret",
"=",
"{",
"mount",
":",
"{",
"}",
"}",
"ret",
"[",
"mount",
"]",
"[",
"'User Quotas'",
"]",
"=",
"_parse_quota",
"(",
"mount",
",",
"'-u'",
")",
"ret",
"[",
"mount",
"]",
"[",
"'Group Quotas'",
"]",
... | Report on quotas for a specific volume
CLI Example:
.. code-block:: bash
salt '*' quota.report /media/data | [
"Report",
"on",
"quotas",
"for",
"a",
"specific",
"volume"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/quota.py#L38-L51 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.