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/freebsdservice.py | get_disabled | def get_disabled(jail=None):
'''
Return what services are available but not enabled to start at boot
.. versionchanged:: 2016.3.4
Support for jail (representing jid or jail name) keyword argument in kwargs
CLI Example:
.. code-block:: bash
salt '*' service.get_disabled
'''
en_ = get_enabled(jail)
all_ = get_all(jail)
return sorted(set(all_) - set(en_)) | python | def get_disabled(jail=None):
'''
Return what services are available but not enabled to start at boot
.. versionchanged:: 2016.3.4
Support for jail (representing jid or jail name) keyword argument in kwargs
CLI Example:
.. code-block:: bash
salt '*' service.get_disabled
'''
en_ = get_enabled(jail)
all_ = get_all(jail)
return sorted(set(all_) - set(en_)) | [
"def",
"get_disabled",
"(",
"jail",
"=",
"None",
")",
":",
"en_",
"=",
"get_enabled",
"(",
"jail",
")",
"all_",
"=",
"get_all",
"(",
"jail",
")",
"return",
"sorted",
"(",
"set",
"(",
"all_",
")",
"-",
"set",
"(",
"en_",
")",
")"
] | Return what services are available but not enabled to start at boot
.. versionchanged:: 2016.3.4
Support for jail (representing jid or jail name) keyword argument in kwargs
CLI Example:
.. code-block:: bash
salt '*' service.get_disabled | [
"Return",
"what",
"services",
"are",
"available",
"but",
"not",
"enabled",
"to",
"start",
"at",
"boot"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/freebsdservice.py#L157-L173 | train |
saltstack/salt | salt/modules/freebsdservice.py | _switch | def _switch(name, # pylint: disable=C0103
on, # pylint: disable=C0103
**kwargs):
'''
Switch on/off service start at boot.
.. versionchanged:: 2016.3.4
Support for jail (representing jid or jail name) and chroot keyword argument
in kwargs. chroot should be used when jail's /etc is mounted read-only and
should point to a root directory where jail's /etc is mounted read-write.
'''
jail = kwargs.get('jail', '')
chroot = kwargs.get('chroot', '').rstrip('/')
if not available(name, jail):
return False
rcvar = _get_rcvar(name, jail)
if not rcvar:
log.error('rcvar for service %s not found', name)
return False
if jail and not chroot:
# prepend the jail's path in config paths when referring to a jail, when
# chroot is not provided. chroot should be provided when the jail's /etc
# is mounted read-only
chroot = _get_jail_path(jail)
config = kwargs.get('config',
__salt__['config.option']('service.config',
default='{0}/etc/rc.conf'.format(chroot)
)
)
if not config:
rcdir = '{0}/etc/rc.conf.d'.format(chroot)
if not os.path.exists(rcdir) or not os.path.isdir(rcdir):
log.error('%s not exists', rcdir)
return False
config = os.path.join(rcdir, rcvar.replace('_enable', ''))
nlines = []
edited = False
if on:
val = 'YES'
else:
val = 'NO'
if os.path.exists(config):
with salt.utils.files.fopen(config, 'r') as ifile:
for line in ifile:
line = salt.utils.stringutils.to_unicode(line)
if not line.startswith('{0}='.format(rcvar)):
nlines.append(line)
continue
rest = line[len(line.split()[0]):] # keep comments etc
nlines.append('{0}="{1}"{2}'.format(rcvar, val, rest))
edited = True
if not edited:
# Ensure that the file ends in a \n
if len(nlines) > 1 and nlines[-1][-1] != '\n':
nlines[-1] = '{0}\n'.format(nlines[-1])
nlines.append('{0}="{1}"\n'.format(rcvar, val))
with salt.utils.files.fopen(config, 'w') as ofile:
nlines = [salt.utils.stringutils.to_str(_l) for _l in nlines]
ofile.writelines(nlines)
return True | python | def _switch(name, # pylint: disable=C0103
on, # pylint: disable=C0103
**kwargs):
'''
Switch on/off service start at boot.
.. versionchanged:: 2016.3.4
Support for jail (representing jid or jail name) and chroot keyword argument
in kwargs. chroot should be used when jail's /etc is mounted read-only and
should point to a root directory where jail's /etc is mounted read-write.
'''
jail = kwargs.get('jail', '')
chroot = kwargs.get('chroot', '').rstrip('/')
if not available(name, jail):
return False
rcvar = _get_rcvar(name, jail)
if not rcvar:
log.error('rcvar for service %s not found', name)
return False
if jail and not chroot:
# prepend the jail's path in config paths when referring to a jail, when
# chroot is not provided. chroot should be provided when the jail's /etc
# is mounted read-only
chroot = _get_jail_path(jail)
config = kwargs.get('config',
__salt__['config.option']('service.config',
default='{0}/etc/rc.conf'.format(chroot)
)
)
if not config:
rcdir = '{0}/etc/rc.conf.d'.format(chroot)
if not os.path.exists(rcdir) or not os.path.isdir(rcdir):
log.error('%s not exists', rcdir)
return False
config = os.path.join(rcdir, rcvar.replace('_enable', ''))
nlines = []
edited = False
if on:
val = 'YES'
else:
val = 'NO'
if os.path.exists(config):
with salt.utils.files.fopen(config, 'r') as ifile:
for line in ifile:
line = salt.utils.stringutils.to_unicode(line)
if not line.startswith('{0}='.format(rcvar)):
nlines.append(line)
continue
rest = line[len(line.split()[0]):] # keep comments etc
nlines.append('{0}="{1}"{2}'.format(rcvar, val, rest))
edited = True
if not edited:
# Ensure that the file ends in a \n
if len(nlines) > 1 and nlines[-1][-1] != '\n':
nlines[-1] = '{0}\n'.format(nlines[-1])
nlines.append('{0}="{1}"\n'.format(rcvar, val))
with salt.utils.files.fopen(config, 'w') as ofile:
nlines = [salt.utils.stringutils.to_str(_l) for _l in nlines]
ofile.writelines(nlines)
return True | [
"def",
"_switch",
"(",
"name",
",",
"# pylint: disable=C0103",
"on",
",",
"# pylint: disable=C0103",
"*",
"*",
"kwargs",
")",
":",
"jail",
"=",
"kwargs",
".",
"get",
"(",
"'jail'",
",",
"''",
")",
"chroot",
"=",
"kwargs",
".",
"get",
"(",
"'chroot'",
","... | Switch on/off service start at boot.
.. versionchanged:: 2016.3.4
Support for jail (representing jid or jail name) and chroot keyword argument
in kwargs. chroot should be used when jail's /etc is mounted read-only and
should point to a root directory where jail's /etc is mounted read-write. | [
"Switch",
"on",
"/",
"off",
"service",
"start",
"at",
"boot",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/freebsdservice.py#L176-L245 | train |
saltstack/salt | salt/modules/freebsdservice.py | enabled | def enabled(name, **kwargs):
'''
Return True if the named service is enabled, false otherwise
name
Service name
.. versionchanged:: 2016.3.4
Support for jail (representing jid or jail name) keyword argument in kwargs
CLI Example:
.. code-block:: bash
salt '*' service.enabled <service name>
'''
jail = kwargs.get('jail', '')
if not available(name, jail):
log.error('Service %s not found', name)
return False
cmd = '{0} {1} rcvar'.format(_cmd(jail), name)
for line in __salt__['cmd.run_stdout'](cmd, python_shell=False).splitlines():
if '_enable="' not in line:
continue
_, state, _ = line.split('"', 2)
return state.lower() in ('yes', 'true', 'on', '1')
# probably will never reached
return False | python | def enabled(name, **kwargs):
'''
Return True if the named service is enabled, false otherwise
name
Service name
.. versionchanged:: 2016.3.4
Support for jail (representing jid or jail name) keyword argument in kwargs
CLI Example:
.. code-block:: bash
salt '*' service.enabled <service name>
'''
jail = kwargs.get('jail', '')
if not available(name, jail):
log.error('Service %s not found', name)
return False
cmd = '{0} {1} rcvar'.format(_cmd(jail), name)
for line in __salt__['cmd.run_stdout'](cmd, python_shell=False).splitlines():
if '_enable="' not in line:
continue
_, state, _ = line.split('"', 2)
return state.lower() in ('yes', 'true', 'on', '1')
# probably will never reached
return False | [
"def",
"enabled",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"jail",
"=",
"kwargs",
".",
"get",
"(",
"'jail'",
",",
"''",
")",
"if",
"not",
"available",
"(",
"name",
",",
"jail",
")",
":",
"log",
".",
"error",
"(",
"'Service %s not found'",
",... | Return True if the named service is enabled, false otherwise
name
Service name
.. versionchanged:: 2016.3.4
Support for jail (representing jid or jail name) keyword argument in kwargs
CLI Example:
.. code-block:: bash
salt '*' service.enabled <service name> | [
"Return",
"True",
"if",
"the",
"named",
"service",
"is",
"enabled",
"false",
"otherwise"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/freebsdservice.py#L302-L333 | train |
saltstack/salt | salt/modules/freebsdservice.py | get_all | def get_all(jail=None):
'''
Return a list of all available services
.. versionchanged:: 2016.3.4
jail: optional jid or jail name
CLI Example:
.. code-block:: bash
salt '*' service.get_all
'''
ret = []
service = _cmd(jail)
for srv in __salt__['cmd.run']('{0} -l'.format(service)).splitlines():
if not srv.isupper():
ret.append(srv)
return sorted(ret) | python | def get_all(jail=None):
'''
Return a list of all available services
.. versionchanged:: 2016.3.4
jail: optional jid or jail name
CLI Example:
.. code-block:: bash
salt '*' service.get_all
'''
ret = []
service = _cmd(jail)
for srv in __salt__['cmd.run']('{0} -l'.format(service)).splitlines():
if not srv.isupper():
ret.append(srv)
return sorted(ret) | [
"def",
"get_all",
"(",
"jail",
"=",
"None",
")",
":",
"ret",
"=",
"[",
"]",
"service",
"=",
"_cmd",
"(",
"jail",
")",
"for",
"srv",
"in",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"'{0} -l'",
".",
"format",
"(",
"service",
")",
")",
".",
"splitlines"... | Return a list of all available services
.. versionchanged:: 2016.3.4
jail: optional jid or jail name
CLI Example:
.. code-block:: bash
salt '*' service.get_all | [
"Return",
"a",
"list",
"of",
"all",
"available",
"services"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/freebsdservice.py#L385-L404 | train |
saltstack/salt | salt/modules/freebsdservice.py | start | def start(name, jail=None):
'''
Start the specified service
.. versionchanged:: 2016.3.4
jail: optional jid or jail name
CLI Example:
.. code-block:: bash
salt '*' service.start <service name>
'''
cmd = '{0} {1} onestart'.format(_cmd(jail), name)
return not __salt__['cmd.retcode'](cmd, python_shell=False) | python | def start(name, jail=None):
'''
Start the specified service
.. versionchanged:: 2016.3.4
jail: optional jid or jail name
CLI Example:
.. code-block:: bash
salt '*' service.start <service name>
'''
cmd = '{0} {1} onestart'.format(_cmd(jail), name)
return not __salt__['cmd.retcode'](cmd, python_shell=False) | [
"def",
"start",
"(",
"name",
",",
"jail",
"=",
"None",
")",
":",
"cmd",
"=",
"'{0} {1} onestart'",
".",
"format",
"(",
"_cmd",
"(",
"jail",
")",
",",
"name",
")",
"return",
"not",
"__salt__",
"[",
"'cmd.retcode'",
"]",
"(",
"cmd",
",",
"python_shell",
... | Start the specified service
.. versionchanged:: 2016.3.4
jail: optional jid or jail name
CLI Example:
.. code-block:: bash
salt '*' service.start <service name> | [
"Start",
"the",
"specified",
"service"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/freebsdservice.py#L407-L422 | train |
saltstack/salt | salt/states/pyenv.py | _python_installed | def _python_installed(ret, python, user=None):
'''
Check to see if given python is installed.
'''
default = __salt__['pyenv.default'](runas=user)
for version in __salt__['pyenv.versions'](user):
if version == python:
ret['result'] = True
ret['comment'] = 'Requested python exists.'
ret['default'] = default == python
break
return ret | python | def _python_installed(ret, python, user=None):
'''
Check to see if given python is installed.
'''
default = __salt__['pyenv.default'](runas=user)
for version in __salt__['pyenv.versions'](user):
if version == python:
ret['result'] = True
ret['comment'] = 'Requested python exists.'
ret['default'] = default == python
break
return ret | [
"def",
"_python_installed",
"(",
"ret",
",",
"python",
",",
"user",
"=",
"None",
")",
":",
"default",
"=",
"__salt__",
"[",
"'pyenv.default'",
"]",
"(",
"runas",
"=",
"user",
")",
"for",
"version",
"in",
"__salt__",
"[",
"'pyenv.versions'",
"]",
"(",
"us... | Check to see if given python is installed. | [
"Check",
"to",
"see",
"if",
"given",
"python",
"is",
"installed",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/pyenv.py#L67-L79 | train |
saltstack/salt | salt/states/pyenv.py | _check_and_install_python | def _check_and_install_python(ret, python, default=False, user=None):
'''
Verify that python is installed, install if unavailable
'''
ret = _python_installed(ret, python, user=user)
if not ret['result']:
if __salt__['pyenv.install_python'](python, runas=user):
ret['result'] = True
ret['changes'][python] = 'Installed'
ret['comment'] = 'Successfully installed python'
ret['default'] = default
else:
ret['result'] = False
ret['comment'] = 'Could not install python.'
return ret
if default:
__salt__['pyenv.default'](python, runas=user)
return ret | python | def _check_and_install_python(ret, python, default=False, user=None):
'''
Verify that python is installed, install if unavailable
'''
ret = _python_installed(ret, python, user=user)
if not ret['result']:
if __salt__['pyenv.install_python'](python, runas=user):
ret['result'] = True
ret['changes'][python] = 'Installed'
ret['comment'] = 'Successfully installed python'
ret['default'] = default
else:
ret['result'] = False
ret['comment'] = 'Could not install python.'
return ret
if default:
__salt__['pyenv.default'](python, runas=user)
return ret | [
"def",
"_check_and_install_python",
"(",
"ret",
",",
"python",
",",
"default",
"=",
"False",
",",
"user",
"=",
"None",
")",
":",
"ret",
"=",
"_python_installed",
"(",
"ret",
",",
"python",
",",
"user",
"=",
"user",
")",
"if",
"not",
"ret",
"[",
"'resul... | Verify that python is installed, install if unavailable | [
"Verify",
"that",
"python",
"is",
"installed",
"install",
"if",
"unavailable"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/pyenv.py#L82-L101 | train |
saltstack/salt | salt/states/pyenv.py | installed | def installed(name, default=False, user=None):
'''
Verify that the specified python is installed with pyenv. pyenv is
installed if necessary.
name
The version of python to install
default : False
Whether to make this python the default.
user: None
The user to run pyenv as.
.. versionadded:: 0.17.0
.. versionadded:: 0.16.0
'''
ret = {'name': name, 'result': None, 'comment': '', 'changes': {}}
if name.startswith('python-'):
name = re.sub(r'^python-', '', name)
if __opts__['test']:
ret['comment'] = 'python {0} is set to be installed'.format(name)
return ret
ret = _check_pyenv(ret, user)
if ret['result'] is False:
if not __salt__['pyenv.install'](user):
ret['comment'] = 'pyenv failed to install'
return ret
else:
return _check_and_install_python(ret, name, default, user=user)
else:
return _check_and_install_python(ret, name, default, user=user) | python | def installed(name, default=False, user=None):
'''
Verify that the specified python is installed with pyenv. pyenv is
installed if necessary.
name
The version of python to install
default : False
Whether to make this python the default.
user: None
The user to run pyenv as.
.. versionadded:: 0.17.0
.. versionadded:: 0.16.0
'''
ret = {'name': name, 'result': None, 'comment': '', 'changes': {}}
if name.startswith('python-'):
name = re.sub(r'^python-', '', name)
if __opts__['test']:
ret['comment'] = 'python {0} is set to be installed'.format(name)
return ret
ret = _check_pyenv(ret, user)
if ret['result'] is False:
if not __salt__['pyenv.install'](user):
ret['comment'] = 'pyenv failed to install'
return ret
else:
return _check_and_install_python(ret, name, default, user=user)
else:
return _check_and_install_python(ret, name, default, user=user) | [
"def",
"installed",
"(",
"name",
",",
"default",
"=",
"False",
",",
"user",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"None",
",",
"'comment'",
":",
"''",
",",
"'changes'",
":",
"{",
"}",
"}",
"if",
"nam... | Verify that the specified python is installed with pyenv. pyenv is
installed if necessary.
name
The version of python to install
default : False
Whether to make this python the default.
user: None
The user to run pyenv as.
.. versionadded:: 0.17.0
.. versionadded:: 0.16.0 | [
"Verify",
"that",
"the",
"specified",
"python",
"is",
"installed",
"with",
"pyenv",
".",
"pyenv",
"is",
"installed",
"if",
"necessary",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/pyenv.py#L104-L139 | train |
saltstack/salt | salt/states/pyenv.py | _check_and_uninstall_python | def _check_and_uninstall_python(ret, python, user=None):
'''
Verify that python is uninstalled
'''
ret = _python_installed(ret, python, user=user)
if ret['result']:
if ret['default']:
__salt__['pyenv.default']('system', runas=user)
if __salt__['pyenv.uninstall_python'](python, runas=user):
ret['result'] = True
ret['changes'][python] = 'Uninstalled'
ret['comment'] = 'Successfully removed python'
return ret
else:
ret['result'] = False
ret['comment'] = 'Failed to uninstall python'
return ret
else:
ret['result'] = True
ret['comment'] = 'python {0} is already absent'.format(python)
return ret | python | def _check_and_uninstall_python(ret, python, user=None):
'''
Verify that python is uninstalled
'''
ret = _python_installed(ret, python, user=user)
if ret['result']:
if ret['default']:
__salt__['pyenv.default']('system', runas=user)
if __salt__['pyenv.uninstall_python'](python, runas=user):
ret['result'] = True
ret['changes'][python] = 'Uninstalled'
ret['comment'] = 'Successfully removed python'
return ret
else:
ret['result'] = False
ret['comment'] = 'Failed to uninstall python'
return ret
else:
ret['result'] = True
ret['comment'] = 'python {0} is already absent'.format(python)
return ret | [
"def",
"_check_and_uninstall_python",
"(",
"ret",
",",
"python",
",",
"user",
"=",
"None",
")",
":",
"ret",
"=",
"_python_installed",
"(",
"ret",
",",
"python",
",",
"user",
"=",
"user",
")",
"if",
"ret",
"[",
"'result'",
"]",
":",
"if",
"ret",
"[",
... | Verify that python is uninstalled | [
"Verify",
"that",
"python",
"is",
"uninstalled"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/pyenv.py#L142-L164 | train |
saltstack/salt | salt/states/pyenv.py | absent | def absent(name, user=None):
'''
Verify that the specified python is not installed with pyenv. pyenv
is installed if necessary.
name
The version of python to uninstall
user: None
The user to run pyenv as.
.. versionadded:: 0.17.0
.. versionadded:: 0.16.0
'''
ret = {'name': name, 'result': None, 'comment': '', 'changes': {}}
if name.startswith('python-'):
name = re.sub(r'^python-', '', name)
if __opts__['test']:
ret['comment'] = 'python {0} is set to be uninstalled'.format(name)
return ret
ret = _check_pyenv(ret, user)
if ret['result'] is False:
ret['result'] = True
ret['comment'] = 'pyenv not installed, {0} not either'.format(name)
return ret
else:
return _check_and_uninstall_python(ret, name, user=user) | python | def absent(name, user=None):
'''
Verify that the specified python is not installed with pyenv. pyenv
is installed if necessary.
name
The version of python to uninstall
user: None
The user to run pyenv as.
.. versionadded:: 0.17.0
.. versionadded:: 0.16.0
'''
ret = {'name': name, 'result': None, 'comment': '', 'changes': {}}
if name.startswith('python-'):
name = re.sub(r'^python-', '', name)
if __opts__['test']:
ret['comment'] = 'python {0} is set to be uninstalled'.format(name)
return ret
ret = _check_pyenv(ret, user)
if ret['result'] is False:
ret['result'] = True
ret['comment'] = 'pyenv not installed, {0} not either'.format(name)
return ret
else:
return _check_and_uninstall_python(ret, name, user=user) | [
"def",
"absent",
"(",
"name",
",",
"user",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"None",
",",
"'comment'",
":",
"''",
",",
"'changes'",
":",
"{",
"}",
"}",
"if",
"name",
".",
"startswith",
"(",
"'pyt... | Verify that the specified python is not installed with pyenv. pyenv
is installed if necessary.
name
The version of python to uninstall
user: None
The user to run pyenv as.
.. versionadded:: 0.17.0
.. versionadded:: 0.16.0 | [
"Verify",
"that",
"the",
"specified",
"python",
"is",
"not",
"installed",
"with",
"pyenv",
".",
"pyenv",
"is",
"installed",
"if",
"necessary",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/pyenv.py#L167-L197 | train |
saltstack/salt | salt/states/pyenv.py | install_pyenv | def install_pyenv(name, user=None):
'''
Install pyenv if not installed. Allows you to require pyenv be installed
prior to installing the plugins. Useful if you want to install pyenv
plugins via the git or file modules and need them installed before
installing any rubies.
Use the pyenv.root configuration option to set the path for pyenv if you
want a system wide install that is not in a user home dir.
user: None
The user to run pyenv as.
'''
ret = {'name': name, 'result': None, 'comment': '', 'changes': {}}
if __opts__['test']:
ret['comment'] = 'pyenv is set to be installed'
return ret
return _check_and_install_python(ret, user) | python | def install_pyenv(name, user=None):
'''
Install pyenv if not installed. Allows you to require pyenv be installed
prior to installing the plugins. Useful if you want to install pyenv
plugins via the git or file modules and need them installed before
installing any rubies.
Use the pyenv.root configuration option to set the path for pyenv if you
want a system wide install that is not in a user home dir.
user: None
The user to run pyenv as.
'''
ret = {'name': name, 'result': None, 'comment': '', 'changes': {}}
if __opts__['test']:
ret['comment'] = 'pyenv is set to be installed'
return ret
return _check_and_install_python(ret, user) | [
"def",
"install_pyenv",
"(",
"name",
",",
"user",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"None",
",",
"'comment'",
":",
"''",
",",
"'changes'",
":",
"{",
"}",
"}",
"if",
"__opts__",
"[",
"'test'",
"]",
... | Install pyenv if not installed. Allows you to require pyenv be installed
prior to installing the plugins. Useful if you want to install pyenv
plugins via the git or file modules and need them installed before
installing any rubies.
Use the pyenv.root configuration option to set the path for pyenv if you
want a system wide install that is not in a user home dir.
user: None
The user to run pyenv as. | [
"Install",
"pyenv",
"if",
"not",
"installed",
".",
"Allows",
"you",
"to",
"require",
"pyenv",
"be",
"installed",
"prior",
"to",
"installing",
"the",
"plugins",
".",
"Useful",
"if",
"you",
"want",
"to",
"install",
"pyenv",
"plugins",
"via",
"the",
"git",
"o... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/pyenv.py#L200-L219 | train |
saltstack/salt | salt/states/smtp.py | send_msg | def send_msg(name,
recipient,
subject,
sender=None,
profile=None,
use_ssl='True',
attachments=None):
'''
Send a message via SMTP
.. code-block:: yaml
server-warning-message:
smtp.send_msg:
- name: 'This is a server warning message'
- profile: my-smtp-account
- subject: 'Message from Salt'
- recipient: admin@example.com
- sender: admin@example.com
- use_ssl: True
- attachments:
- /var/log/syslog
- /var/log/messages
name
The message to send via SMTP
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
if profile is None and sender is None:
ret['result'] = False
ret['comment'] = 'Missing parameter sender or profile for state smtp.send_msg'
return ret
if __opts__['test']:
ret['comment'] = 'Need to send message to {0}: {1}'.format(
recipient,
name,
)
return ret
command = __salt__['smtp.send_msg'](
message=name,
recipient=recipient,
profile=profile,
subject=subject,
sender=sender,
use_ssl=use_ssl,
attachments=attachments,
)
if command:
ret['result'] = True
if attachments:
atts = ', '.join(attachments)
ret['comment'] = 'Sent message to {0} with attachments ({2}): {1}' \
.format(recipient, name, atts)
else:
ret['comment'] = 'Sent message to {0}: {1}'.format(recipient, name)
else:
ret['result'] = False
ret['comment'] = 'Unable to send message to {0}: {1}'.format(recipient, name)
return ret | python | def send_msg(name,
recipient,
subject,
sender=None,
profile=None,
use_ssl='True',
attachments=None):
'''
Send a message via SMTP
.. code-block:: yaml
server-warning-message:
smtp.send_msg:
- name: 'This is a server warning message'
- profile: my-smtp-account
- subject: 'Message from Salt'
- recipient: admin@example.com
- sender: admin@example.com
- use_ssl: True
- attachments:
- /var/log/syslog
- /var/log/messages
name
The message to send via SMTP
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
if profile is None and sender is None:
ret['result'] = False
ret['comment'] = 'Missing parameter sender or profile for state smtp.send_msg'
return ret
if __opts__['test']:
ret['comment'] = 'Need to send message to {0}: {1}'.format(
recipient,
name,
)
return ret
command = __salt__['smtp.send_msg'](
message=name,
recipient=recipient,
profile=profile,
subject=subject,
sender=sender,
use_ssl=use_ssl,
attachments=attachments,
)
if command:
ret['result'] = True
if attachments:
atts = ', '.join(attachments)
ret['comment'] = 'Sent message to {0} with attachments ({2}): {1}' \
.format(recipient, name, atts)
else:
ret['comment'] = 'Sent message to {0}: {1}'.format(recipient, name)
else:
ret['result'] = False
ret['comment'] = 'Unable to send message to {0}: {1}'.format(recipient, name)
return ret | [
"def",
"send_msg",
"(",
"name",
",",
"recipient",
",",
"subject",
",",
"sender",
"=",
"None",
",",
"profile",
"=",
"None",
",",
"use_ssl",
"=",
"'True'",
",",
"attachments",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'change... | Send a message via SMTP
.. code-block:: yaml
server-warning-message:
smtp.send_msg:
- name: 'This is a server warning message'
- profile: my-smtp-account
- subject: 'Message from Salt'
- recipient: admin@example.com
- sender: admin@example.com
- use_ssl: True
- attachments:
- /var/log/syslog
- /var/log/messages
name
The message to send via SMTP | [
"Send",
"a",
"message",
"via",
"SMTP"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/smtp.py#L30-L94 | train |
saltstack/salt | salt/modules/debconfmod.py | get_selections | def get_selections(fetchempty=True):
'''
Answers to debconf questions for all packages in the following format::
{'package': [['question', 'type', 'value'], ...]}
CLI Example:
.. code-block:: bash
salt '*' debconf.get_selections
'''
selections = {}
cmd = 'debconf-get-selections'
out = __salt__['cmd.run_stdout'](cmd)
lines = _unpack_lines(out)
for line in lines:
package, question, type_, value = line
if fetchempty or value:
(selections
.setdefault(package, [])
.append([question, type_, value]))
return selections | python | def get_selections(fetchempty=True):
'''
Answers to debconf questions for all packages in the following format::
{'package': [['question', 'type', 'value'], ...]}
CLI Example:
.. code-block:: bash
salt '*' debconf.get_selections
'''
selections = {}
cmd = 'debconf-get-selections'
out = __salt__['cmd.run_stdout'](cmd)
lines = _unpack_lines(out)
for line in lines:
package, question, type_, value = line
if fetchempty or value:
(selections
.setdefault(package, [])
.append([question, type_, value]))
return selections | [
"def",
"get_selections",
"(",
"fetchempty",
"=",
"True",
")",
":",
"selections",
"=",
"{",
"}",
"cmd",
"=",
"'debconf-get-selections'",
"out",
"=",
"__salt__",
"[",
"'cmd.run_stdout'",
"]",
"(",
"cmd",
")",
"lines",
"=",
"_unpack_lines",
"(",
"out",
")",
"... | Answers to debconf questions for all packages in the following format::
{'package': [['question', 'type', 'value'], ...]}
CLI Example:
.. code-block:: bash
salt '*' debconf.get_selections | [
"Answers",
"to",
"debconf",
"questions",
"for",
"all",
"packages",
"in",
"the",
"following",
"format",
"::"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/debconfmod.py#L57-L83 | train |
saltstack/salt | salt/modules/debconfmod.py | set_ | def set_(package, question, type, value, *extra):
'''
Set answers to debconf questions for a package.
CLI Example:
.. code-block:: bash
salt '*' debconf.set <package> <question> <type> <value> [<value> ...]
'''
if extra:
value = ' '.join((value,) + tuple(extra))
fd_, fname = salt.utils.files.mkstemp(prefix="salt-", close_fd=False)
line = "{0} {1} {2} {3}".format(package, question, type, value)
os.write(fd_, salt.utils.stringutils.to_bytes(line))
os.close(fd_)
_set_file(fname)
os.unlink(fname)
return True | python | def set_(package, question, type, value, *extra):
'''
Set answers to debconf questions for a package.
CLI Example:
.. code-block:: bash
salt '*' debconf.set <package> <question> <type> <value> [<value> ...]
'''
if extra:
value = ' '.join((value,) + tuple(extra))
fd_, fname = salt.utils.files.mkstemp(prefix="salt-", close_fd=False)
line = "{0} {1} {2} {3}".format(package, question, type, value)
os.write(fd_, salt.utils.stringutils.to_bytes(line))
os.close(fd_)
_set_file(fname)
os.unlink(fname)
return True | [
"def",
"set_",
"(",
"package",
",",
"question",
",",
"type",
",",
"value",
",",
"*",
"extra",
")",
":",
"if",
"extra",
":",
"value",
"=",
"' '",
".",
"join",
"(",
"(",
"value",
",",
")",
"+",
"tuple",
"(",
"extra",
")",
")",
"fd_",
",",
"fname"... | Set answers to debconf questions for a package.
CLI Example:
.. code-block:: bash
salt '*' debconf.set <package> <question> <type> <value> [<value> ...] | [
"Set",
"answers",
"to",
"debconf",
"questions",
"for",
"a",
"package",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/debconfmod.py#L115-L139 | train |
saltstack/salt | salt/modules/debconfmod.py | set_template | def set_template(path, template, context, defaults, saltenv='base', **kwargs):
'''
Set answers to debconf questions from a template.
path
location of the file containing the package selections
template
template format
context
variables to add to the template environment
default
default values for the template environment
CLI Example:
.. code-block:: bash
salt '*' debconf.set_template salt://pathto/pkg.selections.jinja jinja None None
'''
path = __salt__['cp.get_template'](
path=path,
dest=None,
template=template,
saltenv=saltenv,
context=context,
defaults=defaults,
**kwargs)
return set_file(path, saltenv, **kwargs) | python | def set_template(path, template, context, defaults, saltenv='base', **kwargs):
'''
Set answers to debconf questions from a template.
path
location of the file containing the package selections
template
template format
context
variables to add to the template environment
default
default values for the template environment
CLI Example:
.. code-block:: bash
salt '*' debconf.set_template salt://pathto/pkg.selections.jinja jinja None None
'''
path = __salt__['cp.get_template'](
path=path,
dest=None,
template=template,
saltenv=saltenv,
context=context,
defaults=defaults,
**kwargs)
return set_file(path, saltenv, **kwargs) | [
"def",
"set_template",
"(",
"path",
",",
"template",
",",
"context",
",",
"defaults",
",",
"saltenv",
"=",
"'base'",
",",
"*",
"*",
"kwargs",
")",
":",
"path",
"=",
"__salt__",
"[",
"'cp.get_template'",
"]",
"(",
"path",
"=",
"path",
",",
"dest",
"=",
... | Set answers to debconf questions from a template.
path
location of the file containing the package selections
template
template format
context
variables to add to the template environment
default
default values for the template environment
CLI Example:
.. code-block:: bash
salt '*' debconf.set_template salt://pathto/pkg.selections.jinja jinja None None | [
"Set",
"answers",
"to",
"debconf",
"questions",
"from",
"a",
"template",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/debconfmod.py#L142-L175 | train |
saltstack/salt | salt/modules/debconfmod.py | set_file | def set_file(path, saltenv='base', **kwargs):
'''
Set answers to debconf questions from a file.
CLI Example:
.. code-block:: bash
salt '*' debconf.set_file salt://pathto/pkg.selections
'''
if '__env__' in kwargs:
# "env" is not supported; Use "saltenv".
kwargs.pop('__env__')
path = __salt__['cp.cache_file'](path, saltenv)
if path:
_set_file(path)
return True
return False | python | def set_file(path, saltenv='base', **kwargs):
'''
Set answers to debconf questions from a file.
CLI Example:
.. code-block:: bash
salt '*' debconf.set_file salt://pathto/pkg.selections
'''
if '__env__' in kwargs:
# "env" is not supported; Use "saltenv".
kwargs.pop('__env__')
path = __salt__['cp.cache_file'](path, saltenv)
if path:
_set_file(path)
return True
return False | [
"def",
"set_file",
"(",
"path",
",",
"saltenv",
"=",
"'base'",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'__env__'",
"in",
"kwargs",
":",
"# \"env\" is not supported; Use \"saltenv\".",
"kwargs",
".",
"pop",
"(",
"'__env__'",
")",
"path",
"=",
"__salt__",
"[... | Set answers to debconf questions from a file.
CLI Example:
.. code-block:: bash
salt '*' debconf.set_file salt://pathto/pkg.selections | [
"Set",
"answers",
"to",
"debconf",
"questions",
"from",
"a",
"file",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/debconfmod.py#L178-L197 | train |
saltstack/salt | salt/returners/multi_returner.py | prep_jid | def prep_jid(nocache=False, passed_jid=None):
'''
Call both with prep_jid on all returners in multi_returner
TODO: finish this, what do do when you get different jids from 2 returners...
since our jids are time based, this make this problem hard, because they
aren't unique, meaning that we have to make sure that no one else got the jid
and if they did we spin to get a new one, which means "locking" the jid in 2
returners is non-trivial
'''
jid = passed_jid
for returner_ in __opts__[CONFIG_KEY]:
if jid is None:
jid = _mminion().returners['{0}.prep_jid'.format(returner_)](nocache=nocache)
else:
r_jid = _mminion().returners['{0}.prep_jid'.format(returner_)](nocache=nocache)
if r_jid != jid:
log.debug('Uhh.... crud the jids do not match')
return jid | python | def prep_jid(nocache=False, passed_jid=None):
'''
Call both with prep_jid on all returners in multi_returner
TODO: finish this, what do do when you get different jids from 2 returners...
since our jids are time based, this make this problem hard, because they
aren't unique, meaning that we have to make sure that no one else got the jid
and if they did we spin to get a new one, which means "locking" the jid in 2
returners is non-trivial
'''
jid = passed_jid
for returner_ in __opts__[CONFIG_KEY]:
if jid is None:
jid = _mminion().returners['{0}.prep_jid'.format(returner_)](nocache=nocache)
else:
r_jid = _mminion().returners['{0}.prep_jid'.format(returner_)](nocache=nocache)
if r_jid != jid:
log.debug('Uhh.... crud the jids do not match')
return jid | [
"def",
"prep_jid",
"(",
"nocache",
"=",
"False",
",",
"passed_jid",
"=",
"None",
")",
":",
"jid",
"=",
"passed_jid",
"for",
"returner_",
"in",
"__opts__",
"[",
"CONFIG_KEY",
"]",
":",
"if",
"jid",
"is",
"None",
":",
"jid",
"=",
"_mminion",
"(",
")",
... | Call both with prep_jid on all returners in multi_returner
TODO: finish this, what do do when you get different jids from 2 returners...
since our jids are time based, this make this problem hard, because they
aren't unique, meaning that we have to make sure that no one else got the jid
and if they did we spin to get a new one, which means "locking" the jid in 2
returners is non-trivial | [
"Call",
"both",
"with",
"prep_jid",
"on",
"all",
"returners",
"in",
"multi_returner"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/multi_returner.py#L34-L53 | train |
saltstack/salt | salt/returners/multi_returner.py | returner | def returner(load):
'''
Write return to all returners in multi_returner
'''
for returner_ in __opts__[CONFIG_KEY]:
_mminion().returners['{0}.returner'.format(returner_)](load) | python | def returner(load):
'''
Write return to all returners in multi_returner
'''
for returner_ in __opts__[CONFIG_KEY]:
_mminion().returners['{0}.returner'.format(returner_)](load) | [
"def",
"returner",
"(",
"load",
")",
":",
"for",
"returner_",
"in",
"__opts__",
"[",
"CONFIG_KEY",
"]",
":",
"_mminion",
"(",
")",
".",
"returners",
"[",
"'{0}.returner'",
".",
"format",
"(",
"returner_",
")",
"]",
"(",
"load",
")"
] | Write return to all returners in multi_returner | [
"Write",
"return",
"to",
"all",
"returners",
"in",
"multi_returner"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/multi_returner.py#L56-L61 | train |
saltstack/salt | salt/returners/multi_returner.py | save_load | def save_load(jid, clear_load, minions=None):
'''
Write load to all returners in multi_returner
'''
for returner_ in __opts__[CONFIG_KEY]:
_mminion().returners['{0}.save_load'.format(returner_)](jid, clear_load) | python | def save_load(jid, clear_load, minions=None):
'''
Write load to all returners in multi_returner
'''
for returner_ in __opts__[CONFIG_KEY]:
_mminion().returners['{0}.save_load'.format(returner_)](jid, clear_load) | [
"def",
"save_load",
"(",
"jid",
",",
"clear_load",
",",
"minions",
"=",
"None",
")",
":",
"for",
"returner_",
"in",
"__opts__",
"[",
"CONFIG_KEY",
"]",
":",
"_mminion",
"(",
")",
".",
"returners",
"[",
"'{0}.save_load'",
".",
"format",
"(",
"returner_",
... | Write load to all returners in multi_returner | [
"Write",
"load",
"to",
"all",
"returners",
"in",
"multi_returner"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/multi_returner.py#L64-L69 | train |
saltstack/salt | salt/returners/multi_returner.py | get_load | def get_load(jid):
'''
Merge the load data from all returners
'''
ret = {}
for returner_ in __opts__[CONFIG_KEY]:
ret.update(_mminion().returners['{0}.get_load'.format(returner_)](jid))
return ret | python | def get_load(jid):
'''
Merge the load data from all returners
'''
ret = {}
for returner_ in __opts__[CONFIG_KEY]:
ret.update(_mminion().returners['{0}.get_load'.format(returner_)](jid))
return ret | [
"def",
"get_load",
"(",
"jid",
")",
":",
"ret",
"=",
"{",
"}",
"for",
"returner_",
"in",
"__opts__",
"[",
"CONFIG_KEY",
"]",
":",
"ret",
".",
"update",
"(",
"_mminion",
"(",
")",
".",
"returners",
"[",
"'{0}.get_load'",
".",
"format",
"(",
"returner_",... | Merge the load data from all returners | [
"Merge",
"the",
"load",
"data",
"from",
"all",
"returners"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/multi_returner.py#L79-L87 | train |
saltstack/salt | salt/returners/multi_returner.py | get_jids | def get_jids():
'''
Return all job data from all returners
'''
ret = {}
for returner_ in __opts__[CONFIG_KEY]:
ret.update(_mminion().returners['{0}.get_jids'.format(returner_)]())
return ret | python | def get_jids():
'''
Return all job data from all returners
'''
ret = {}
for returner_ in __opts__[CONFIG_KEY]:
ret.update(_mminion().returners['{0}.get_jids'.format(returner_)]())
return ret | [
"def",
"get_jids",
"(",
")",
":",
"ret",
"=",
"{",
"}",
"for",
"returner_",
"in",
"__opts__",
"[",
"CONFIG_KEY",
"]",
":",
"ret",
".",
"update",
"(",
"_mminion",
"(",
")",
".",
"returners",
"[",
"'{0}.get_jids'",
".",
"format",
"(",
"returner_",
")",
... | Return all job data from all returners | [
"Return",
"all",
"job",
"data",
"from",
"all",
"returners"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/multi_returner.py#L101-L109 | train |
saltstack/salt | salt/returners/multi_returner.py | clean_old_jobs | def clean_old_jobs():
'''
Clean out the old jobs from all returners (if you have it)
'''
for returner_ in __opts__[CONFIG_KEY]:
fstr = '{0}.clean_old_jobs'.format(returner_)
if fstr in _mminion().returners:
_mminion().returners[fstr]() | python | def clean_old_jobs():
'''
Clean out the old jobs from all returners (if you have it)
'''
for returner_ in __opts__[CONFIG_KEY]:
fstr = '{0}.clean_old_jobs'.format(returner_)
if fstr in _mminion().returners:
_mminion().returners[fstr]() | [
"def",
"clean_old_jobs",
"(",
")",
":",
"for",
"returner_",
"in",
"__opts__",
"[",
"CONFIG_KEY",
"]",
":",
"fstr",
"=",
"'{0}.clean_old_jobs'",
".",
"format",
"(",
"returner_",
")",
"if",
"fstr",
"in",
"_mminion",
"(",
")",
".",
"returners",
":",
"_mminion... | Clean out the old jobs from all returners (if you have it) | [
"Clean",
"out",
"the",
"old",
"jobs",
"from",
"all",
"returners",
"(",
"if",
"you",
"have",
"it",
")"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/multi_returner.py#L112-L119 | train |
saltstack/salt | salt/states/keystone_domain.py | present | def present(name, auth=None, **kwargs):
'''
Ensure domain exists and is up-to-date
name
Name of the domain
enabled
Boolean to control if domain is enabled
description
An arbitrary description of the domain
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
kwargs = __utils__['args.clean_kwargs'](**kwargs)
__salt__['keystoneng.setup_clouds'](auth)
domain = __salt__['keystoneng.domain_get'](name=name)
if not domain:
if __opts__['test']:
ret['result'] = None
ret['changes'] = kwargs
ret['comment'] = 'Domain {} will be created.'.format(name)
return ret
kwargs['name'] = name
domain = __salt__['keystoneng.domain_create'](**kwargs)
ret['changes'] = domain
ret['comment'] = 'Created domain'
return ret
changes = __salt__['keystoneng.compare_changes'](domain, **kwargs)
if changes:
if __opts__['test']:
ret['result'] = None
ret['changes'] = changes
ret['comment'] = 'Domain {} will be updated.'.format(name)
return ret
kwargs['domain_id'] = domain.id
__salt__['keystoneng.domain_update'](**kwargs)
ret['changes'].update(changes)
ret['comment'] = 'Updated domain'
return ret | python | def present(name, auth=None, **kwargs):
'''
Ensure domain exists and is up-to-date
name
Name of the domain
enabled
Boolean to control if domain is enabled
description
An arbitrary description of the domain
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
kwargs = __utils__['args.clean_kwargs'](**kwargs)
__salt__['keystoneng.setup_clouds'](auth)
domain = __salt__['keystoneng.domain_get'](name=name)
if not domain:
if __opts__['test']:
ret['result'] = None
ret['changes'] = kwargs
ret['comment'] = 'Domain {} will be created.'.format(name)
return ret
kwargs['name'] = name
domain = __salt__['keystoneng.domain_create'](**kwargs)
ret['changes'] = domain
ret['comment'] = 'Created domain'
return ret
changes = __salt__['keystoneng.compare_changes'](domain, **kwargs)
if changes:
if __opts__['test']:
ret['result'] = None
ret['changes'] = changes
ret['comment'] = 'Domain {} will be updated.'.format(name)
return ret
kwargs['domain_id'] = domain.id
__salt__['keystoneng.domain_update'](**kwargs)
ret['changes'].update(changes)
ret['comment'] = 'Updated domain'
return ret | [
"def",
"present",
"(",
"name",
",",
"auth",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",
"''",
"}",
"kwargs",
"=",
... | Ensure domain exists and is up-to-date
name
Name of the domain
enabled
Boolean to control if domain is enabled
description
An arbitrary description of the domain | [
"Ensure",
"domain",
"exists",
"and",
"is",
"up",
"-",
"to",
"-",
"date"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/keystone_domain.py#L41-L91 | train |
saltstack/salt | salt/states/keystone_domain.py | absent | def absent(name, auth=None):
'''
Ensure domain does not exist
name
Name of the domain
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
__salt__['keystoneng.setup_clouds'](auth)
domain = __salt__['keystoneng.domain_get'](name=name)
if domain:
if __opts__['test'] is True:
ret['result'] = None
ret['changes'] = {'name': name}
ret['comment'] = 'Domain {} will be deleted.'.format(name)
return ret
__salt__['keystoneng.domain_delete'](name=domain)
ret['changes']['id'] = domain.id
ret['comment'] = 'Deleted domain'
return ret | python | def absent(name, auth=None):
'''
Ensure domain does not exist
name
Name of the domain
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
__salt__['keystoneng.setup_clouds'](auth)
domain = __salt__['keystoneng.domain_get'](name=name)
if domain:
if __opts__['test'] is True:
ret['result'] = None
ret['changes'] = {'name': name}
ret['comment'] = 'Domain {} will be deleted.'.format(name)
return ret
__salt__['keystoneng.domain_delete'](name=domain)
ret['changes']['id'] = domain.id
ret['comment'] = 'Deleted domain'
return ret | [
"def",
"absent",
"(",
"name",
",",
"auth",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",
"''",
"}",
"__salt__",
"[",
"'keystoneng.setup_clouds'",
"... | Ensure domain does not exist
name
Name of the domain | [
"Ensure",
"domain",
"does",
"not",
"exist"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/keystone_domain.py#L94-L121 | train |
saltstack/salt | salt/matchers/compound_match.py | match | def match(tgt, opts=None):
'''
Runs the compound target check
'''
if not opts:
opts = __opts__
nodegroups = opts.get('nodegroups', {})
matchers = salt.loader.matchers(opts)
if not isinstance(tgt, six.string_types) and not isinstance(tgt, (list, tuple)):
log.error('Compound target received that is neither string, list nor tuple')
return False
log.debug('compound_match: %s ? %s', opts['id'], tgt)
ref = {'G': 'grain',
'P': 'grain_pcre',
'I': 'pillar',
'J': 'pillar_pcre',
'L': 'list',
'N': None, # Nodegroups should already be expanded
'S': 'ipcidr',
'E': 'pcre'}
if HAS_RANGE:
ref['R'] = 'range'
results = []
opers = ['and', 'or', 'not', '(', ')']
if isinstance(tgt, six.string_types):
words = tgt.split()
else:
# we make a shallow copy in order to not affect the passed in arg
words = tgt[:]
while words:
word = words.pop(0)
target_info = salt.utils.minions.parse_target(word)
# Easy check first
if word in opers:
if results:
if results[-1] == '(' and word in ('and', 'or'):
log.error('Invalid beginning operator after "(": %s', word)
return False
if word == 'not':
if not results[-1] in ('and', 'or', '('):
results.append('and')
results.append(word)
else:
# seq start with binary oper, fail
if word not in ['(', 'not']:
log.error('Invalid beginning operator: %s', word)
return False
results.append(word)
elif target_info and target_info['engine']:
if 'N' == target_info['engine']:
# if we encounter a node group, just evaluate it in-place
decomposed = salt.utils.minions.nodegroup_comp(target_info['pattern'], nodegroups)
if decomposed:
words = decomposed + words
continue
engine = ref.get(target_info['engine'])
if not engine:
# If an unknown engine is called at any time, fail out
log.error(
'Unrecognized target engine "%s" for target '
'expression "%s"', target_info['engine'], word
)
return False
engine_args = [target_info['pattern']]
engine_kwargs = {}
if target_info['delimiter']:
engine_kwargs['delimiter'] = target_info['delimiter']
results.append(
six.text_type(matchers['{0}_match.match'.format(engine)](*engine_args, **engine_kwargs))
)
else:
# The match is not explicitly defined, evaluate it as a glob
results.append(six.text_type(matchers['glob_match.match'](word)))
results = ' '.join(results)
log.debug('compound_match %s ? "%s" => "%s"', opts['id'], tgt, results)
try:
return eval(results) # pylint: disable=W0123
except Exception:
log.error(
'Invalid compound target: %s for results: %s', tgt, results)
return False
return False | python | def match(tgt, opts=None):
'''
Runs the compound target check
'''
if not opts:
opts = __opts__
nodegroups = opts.get('nodegroups', {})
matchers = salt.loader.matchers(opts)
if not isinstance(tgt, six.string_types) and not isinstance(tgt, (list, tuple)):
log.error('Compound target received that is neither string, list nor tuple')
return False
log.debug('compound_match: %s ? %s', opts['id'], tgt)
ref = {'G': 'grain',
'P': 'grain_pcre',
'I': 'pillar',
'J': 'pillar_pcre',
'L': 'list',
'N': None, # Nodegroups should already be expanded
'S': 'ipcidr',
'E': 'pcre'}
if HAS_RANGE:
ref['R'] = 'range'
results = []
opers = ['and', 'or', 'not', '(', ')']
if isinstance(tgt, six.string_types):
words = tgt.split()
else:
# we make a shallow copy in order to not affect the passed in arg
words = tgt[:]
while words:
word = words.pop(0)
target_info = salt.utils.minions.parse_target(word)
# Easy check first
if word in opers:
if results:
if results[-1] == '(' and word in ('and', 'or'):
log.error('Invalid beginning operator after "(": %s', word)
return False
if word == 'not':
if not results[-1] in ('and', 'or', '('):
results.append('and')
results.append(word)
else:
# seq start with binary oper, fail
if word not in ['(', 'not']:
log.error('Invalid beginning operator: %s', word)
return False
results.append(word)
elif target_info and target_info['engine']:
if 'N' == target_info['engine']:
# if we encounter a node group, just evaluate it in-place
decomposed = salt.utils.minions.nodegroup_comp(target_info['pattern'], nodegroups)
if decomposed:
words = decomposed + words
continue
engine = ref.get(target_info['engine'])
if not engine:
# If an unknown engine is called at any time, fail out
log.error(
'Unrecognized target engine "%s" for target '
'expression "%s"', target_info['engine'], word
)
return False
engine_args = [target_info['pattern']]
engine_kwargs = {}
if target_info['delimiter']:
engine_kwargs['delimiter'] = target_info['delimiter']
results.append(
six.text_type(matchers['{0}_match.match'.format(engine)](*engine_args, **engine_kwargs))
)
else:
# The match is not explicitly defined, evaluate it as a glob
results.append(six.text_type(matchers['glob_match.match'](word)))
results = ' '.join(results)
log.debug('compound_match %s ? "%s" => "%s"', opts['id'], tgt, results)
try:
return eval(results) # pylint: disable=W0123
except Exception:
log.error(
'Invalid compound target: %s for results: %s', tgt, results)
return False
return False | [
"def",
"match",
"(",
"tgt",
",",
"opts",
"=",
"None",
")",
":",
"if",
"not",
"opts",
":",
"opts",
"=",
"__opts__",
"nodegroups",
"=",
"opts",
".",
"get",
"(",
"'nodegroups'",
",",
"{",
"}",
")",
"matchers",
"=",
"salt",
".",
"loader",
".",
"matcher... | Runs the compound target check | [
"Runs",
"the",
"compound",
"target",
"check"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/matchers/compound_match.py#L22-L114 | train |
saltstack/salt | salt/states/marathon_app.py | config | def config(name, config):
'''
Ensure that the marathon app with the given id is present and is configured
to match the given config values.
:param name: The app name/id
:param config: The configuration to apply (dict)
:return: A standard Salt changes dictionary
'''
# setup return structure
ret = {
'name': name,
'changes': {},
'result': False,
'comment': '',
}
# get existing config if app is present
existing_config = None
if __salt__['marathon.has_app'](name):
existing_config = __salt__['marathon.app'](name)['app']
# compare existing config with defined config
if existing_config:
update_config = copy.deepcopy(existing_config)
salt.utils.configcomparer.compare_and_update_config(
config,
update_config,
ret['changes'],
)
else:
# the app is not configured--we need to create it from scratch
ret['changes']['app'] = {
'new': config,
'old': None,
}
update_config = config
# update the config if we registered any changes
if ret['changes']:
# if test, report there will be an update
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Marathon app {0} is set to be updated'.format(
name
)
return ret
update_result = __salt__['marathon.update_app'](name, update_config)
if 'exception' in update_result:
ret['result'] = False
ret['comment'] = 'Failed to update app config for {0}: {1}'.format(
name,
update_result['exception'],
)
return ret
else:
ret['result'] = True
ret['comment'] = 'Updated app config for {0}'.format(name)
return ret
ret['result'] = True
ret['comment'] = 'Marathon app {0} configured correctly'.format(name)
return ret | python | def config(name, config):
'''
Ensure that the marathon app with the given id is present and is configured
to match the given config values.
:param name: The app name/id
:param config: The configuration to apply (dict)
:return: A standard Salt changes dictionary
'''
# setup return structure
ret = {
'name': name,
'changes': {},
'result': False,
'comment': '',
}
# get existing config if app is present
existing_config = None
if __salt__['marathon.has_app'](name):
existing_config = __salt__['marathon.app'](name)['app']
# compare existing config with defined config
if existing_config:
update_config = copy.deepcopy(existing_config)
salt.utils.configcomparer.compare_and_update_config(
config,
update_config,
ret['changes'],
)
else:
# the app is not configured--we need to create it from scratch
ret['changes']['app'] = {
'new': config,
'old': None,
}
update_config = config
# update the config if we registered any changes
if ret['changes']:
# if test, report there will be an update
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Marathon app {0} is set to be updated'.format(
name
)
return ret
update_result = __salt__['marathon.update_app'](name, update_config)
if 'exception' in update_result:
ret['result'] = False
ret['comment'] = 'Failed to update app config for {0}: {1}'.format(
name,
update_result['exception'],
)
return ret
else:
ret['result'] = True
ret['comment'] = 'Updated app config for {0}'.format(name)
return ret
ret['result'] = True
ret['comment'] = 'Marathon app {0} configured correctly'.format(name)
return ret | [
"def",
"config",
"(",
"name",
",",
"config",
")",
":",
"# setup return structure",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"False",
",",
"'comment'",
":",
"''",
",",
"}",
"# get existing config if app ... | Ensure that the marathon app with the given id is present and is configured
to match the given config values.
:param name: The app name/id
:param config: The configuration to apply (dict)
:return: A standard Salt changes dictionary | [
"Ensure",
"that",
"the",
"marathon",
"app",
"with",
"the",
"given",
"id",
"is",
"present",
"and",
"is",
"configured",
"to",
"match",
"the",
"given",
"config",
"values",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/marathon_app.py#L27-L89 | train |
saltstack/salt | salt/states/marathon_app.py | running | def running(name, restart=False, force=True):
'''
Ensure that the marathon app with the given id is present and restart if set.
:param name: The app name/id
:param restart: Restart the app
:param force: Override the current deployment
:return: A standard Salt changes dictionary
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
if not __salt__['marathon.has_app'](name):
ret['result'] = False
ret['comment'] = 'App {0} cannot be restarted because it is absent'.format(name)
return ret
if __opts__['test']:
ret['result'] = None
qualifier = 'is' if restart else 'is not'
ret['comment'] = 'App {0} {1} set to be restarted'.format(name, qualifier)
return ret
restart_result = __salt__['marathon.restart_app'](name, restart, force)
if 'exception' in restart_result:
ret['result'] = False
ret['comment'] = 'Failed to restart app {0}: {1}'.format(
name,
restart_result['exception']
)
return ret
else:
ret['changes'] = restart_result
ret['result'] = True
qualifier = 'Restarted' if restart else 'Did not restart'
ret['comment'] = '{0} app {1}'.format(qualifier, name)
return ret | python | def running(name, restart=False, force=True):
'''
Ensure that the marathon app with the given id is present and restart if set.
:param name: The app name/id
:param restart: Restart the app
:param force: Override the current deployment
:return: A standard Salt changes dictionary
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
if not __salt__['marathon.has_app'](name):
ret['result'] = False
ret['comment'] = 'App {0} cannot be restarted because it is absent'.format(name)
return ret
if __opts__['test']:
ret['result'] = None
qualifier = 'is' if restart else 'is not'
ret['comment'] = 'App {0} {1} set to be restarted'.format(name, qualifier)
return ret
restart_result = __salt__['marathon.restart_app'](name, restart, force)
if 'exception' in restart_result:
ret['result'] = False
ret['comment'] = 'Failed to restart app {0}: {1}'.format(
name,
restart_result['exception']
)
return ret
else:
ret['changes'] = restart_result
ret['result'] = True
qualifier = 'Restarted' if restart else 'Did not restart'
ret['comment'] = '{0} app {1}'.format(qualifier, name)
return ret | [
"def",
"running",
"(",
"name",
",",
"restart",
"=",
"False",
",",
"force",
"=",
"True",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"False",
",",
"'comment'",
":",
"''",
"}",
"if",
"not... | Ensure that the marathon app with the given id is present and restart if set.
:param name: The app name/id
:param restart: Restart the app
:param force: Override the current deployment
:return: A standard Salt changes dictionary | [
"Ensure",
"that",
"the",
"marathon",
"app",
"with",
"the",
"given",
"id",
"is",
"present",
"and",
"restart",
"if",
"set",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/marathon_app.py#L122-L157 | train |
saltstack/salt | salt/states/boto_cfn.py | present | def present(name, template_body=None, template_url=None, parameters=None, notification_arns=None, disable_rollback=None,
timeout_in_minutes=None, capabilities=None, tags=None, on_failure=None, stack_policy_body=None,
stack_policy_url=None, use_previous_template=None, stack_policy_during_update_body=None,
stack_policy_during_update_url=None, region=None, key=None, keyid=None, profile=None):
'''
Ensure cloud formation stack is present.
name (string) - Name of the stack.
template_body (string) – Structure containing the template body. Can also be loaded from a file by using salt://.
template_url (string) – Location of file containing the template body. The URL must point to a template located in
an S3 bucket in the same region as the stack.
parameters (list) – A list of key/value tuples that specify input parameters for the stack. A 3-tuple (key, value,
bool) may be used to specify the UsePreviousValue option.
notification_arns (list) – The Simple Notification Service (SNS) topic ARNs to publish stack related events.
You can find your SNS topic ARNs using the `SNS_console`_ or your Command Line Interface (CLI).
disable_rollback (bool) – Indicates whether or not to rollback on failure.
timeout_in_minutes (integer) – The amount of time that can pass before the stack status becomes CREATE_FAILED; if
DisableRollback is not set or is set to False, the stack will be rolled back.
capabilities (list) – The list of capabilities you want to allow in the stack. Currently, the only valid capability
is ‘CAPABILITY_IAM’.
tags (dict) – A set of user-defined Tags to associate with this stack, represented by key/value pairs. Tags defined
for the stack are propagated to EC2 resources that are created as part of the stack. A maximum number of 10 tags can
be specified.
on_failure (string) – Determines what action will be taken if stack creation fails. This must be one of:
DO_NOTHING, ROLLBACK, or DELETE. You can specify either OnFailure or DisableRollback, but not both.
stack_policy_body (string) – Structure containing the stack policy body. Can also be loaded from a file by using
salt://.
stack_policy_url (string) – Location of a file containing the stack policy. The URL must point to a policy
(max size: 16KB) located in an S3 bucket in the same region as the stack.If you pass StackPolicyBody and
StackPolicyURL, only StackPolicyBody is used.
use_previous_template (boolean) – Used only when templates are not the same. Set to True to use the previous
template instead of uploading a new one via TemplateBody or TemplateURL.
stack_policy_during_update_body (string) – Used only when templates are not the same. Structure containing the
temporary overriding stack policy body. If you pass StackPolicyDuringUpdateBody and StackPolicyDuringUpdateURL,
only StackPolicyDuringUpdateBody is used. Can also be loaded from a file by using salt://.
stack_policy_during_update_url (string) – Used only when templates are not the same. Location of a file containing
the temporary overriding stack policy. The URL must point to a policy (max size: 16KB) located in an S3 bucket in
the same region as the stack. If you pass StackPolicyDuringUpdateBody and StackPolicyDuringUpdateURL, only
StackPolicyDuringUpdateBody is used.
region (string) - Region to connect to.
key (string) - Secret key to be used.
keyid (string) - Access key to be used.
profile (dict) - A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key
and keyid.
.. _`SNS_console`: https://console.aws.amazon.com/sns
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
template_body = _get_template(template_body, name)
stack_policy_body = _get_template(stack_policy_body, name)
stack_policy_during_update_body = _get_template(stack_policy_during_update_body, name)
for i in [template_body, stack_policy_body, stack_policy_during_update_body]:
if isinstance(i, dict):
return i
_valid = _validate(template_body, template_url, region, key, keyid, profile)
log.debug('Validate is : %s.', _valid)
if _valid is not True:
code, message = _valid
ret['result'] = False
ret['comment'] = 'Template could not be validated.\n{0} \n{1}'.format(code, message)
return ret
log.debug('Template %s is valid.', name)
if __salt__['boto_cfn.exists'](name, region, key, keyid, profile):
template = __salt__['boto_cfn.get_template'](name, region, key, keyid, profile)
template = template['GetTemplateResponse']['GetTemplateResult']['TemplateBody'].encode('ascii', 'ignore')
template = salt.utils.json.loads(template)
_template_body = salt.utils.json.loads(template_body)
compare = salt.utils.compat.cmp(template, _template_body)
if compare != 0:
log.debug('Templates are not the same. Compare value is %s', compare)
# At this point we should be able to run update safely since we already validated the template
if __opts__['test']:
ret['comment'] = 'Stack {0} is set to be updated.'.format(name)
ret['result'] = None
return ret
updated = __salt__['boto_cfn.update_stack'](name, template_body, template_url, parameters,
notification_arns, disable_rollback, timeout_in_minutes,
capabilities, tags, use_previous_template,
stack_policy_during_update_body,
stack_policy_during_update_url, stack_policy_body,
stack_policy_url,
region, key, keyid, profile)
if isinstance(updated, six.string_types):
code, message = _get_error(updated)
log.debug('Update error is %s and message is %s', code, message)
ret['result'] = False
ret['comment'] = 'Stack {0} could not be updated.\n{1} \n{2}.'.format(name, code, message)
return ret
ret['comment'] = 'Cloud formation template {0} has been updated.'.format(name)
ret['changes']['new'] = updated
return ret
ret['comment'] = 'Stack {0} exists.'.format(name)
ret['changes'] = {}
return ret
if __opts__['test']:
ret['comment'] = 'Stack {0} is set to be created.'.format(name)
ret['result'] = None
return ret
created = __salt__['boto_cfn.create'](name, template_body, template_url, parameters, notification_arns,
disable_rollback, timeout_in_minutes, capabilities, tags, on_failure,
stack_policy_body, stack_policy_url, region, key, keyid, profile)
if created:
ret['comment'] = 'Stack {0} was created.'.format(name)
ret['changes']['new'] = created
return ret
ret['result'] = False
return ret | python | def present(name, template_body=None, template_url=None, parameters=None, notification_arns=None, disable_rollback=None,
timeout_in_minutes=None, capabilities=None, tags=None, on_failure=None, stack_policy_body=None,
stack_policy_url=None, use_previous_template=None, stack_policy_during_update_body=None,
stack_policy_during_update_url=None, region=None, key=None, keyid=None, profile=None):
'''
Ensure cloud formation stack is present.
name (string) - Name of the stack.
template_body (string) – Structure containing the template body. Can also be loaded from a file by using salt://.
template_url (string) – Location of file containing the template body. The URL must point to a template located in
an S3 bucket in the same region as the stack.
parameters (list) – A list of key/value tuples that specify input parameters for the stack. A 3-tuple (key, value,
bool) may be used to specify the UsePreviousValue option.
notification_arns (list) – The Simple Notification Service (SNS) topic ARNs to publish stack related events.
You can find your SNS topic ARNs using the `SNS_console`_ or your Command Line Interface (CLI).
disable_rollback (bool) – Indicates whether or not to rollback on failure.
timeout_in_minutes (integer) – The amount of time that can pass before the stack status becomes CREATE_FAILED; if
DisableRollback is not set or is set to False, the stack will be rolled back.
capabilities (list) – The list of capabilities you want to allow in the stack. Currently, the only valid capability
is ‘CAPABILITY_IAM’.
tags (dict) – A set of user-defined Tags to associate with this stack, represented by key/value pairs. Tags defined
for the stack are propagated to EC2 resources that are created as part of the stack. A maximum number of 10 tags can
be specified.
on_failure (string) – Determines what action will be taken if stack creation fails. This must be one of:
DO_NOTHING, ROLLBACK, or DELETE. You can specify either OnFailure or DisableRollback, but not both.
stack_policy_body (string) – Structure containing the stack policy body. Can also be loaded from a file by using
salt://.
stack_policy_url (string) – Location of a file containing the stack policy. The URL must point to a policy
(max size: 16KB) located in an S3 bucket in the same region as the stack.If you pass StackPolicyBody and
StackPolicyURL, only StackPolicyBody is used.
use_previous_template (boolean) – Used only when templates are not the same. Set to True to use the previous
template instead of uploading a new one via TemplateBody or TemplateURL.
stack_policy_during_update_body (string) – Used only when templates are not the same. Structure containing the
temporary overriding stack policy body. If you pass StackPolicyDuringUpdateBody and StackPolicyDuringUpdateURL,
only StackPolicyDuringUpdateBody is used. Can also be loaded from a file by using salt://.
stack_policy_during_update_url (string) – Used only when templates are not the same. Location of a file containing
the temporary overriding stack policy. The URL must point to a policy (max size: 16KB) located in an S3 bucket in
the same region as the stack. If you pass StackPolicyDuringUpdateBody and StackPolicyDuringUpdateURL, only
StackPolicyDuringUpdateBody is used.
region (string) - Region to connect to.
key (string) - Secret key to be used.
keyid (string) - Access key to be used.
profile (dict) - A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key
and keyid.
.. _`SNS_console`: https://console.aws.amazon.com/sns
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
template_body = _get_template(template_body, name)
stack_policy_body = _get_template(stack_policy_body, name)
stack_policy_during_update_body = _get_template(stack_policy_during_update_body, name)
for i in [template_body, stack_policy_body, stack_policy_during_update_body]:
if isinstance(i, dict):
return i
_valid = _validate(template_body, template_url, region, key, keyid, profile)
log.debug('Validate is : %s.', _valid)
if _valid is not True:
code, message = _valid
ret['result'] = False
ret['comment'] = 'Template could not be validated.\n{0} \n{1}'.format(code, message)
return ret
log.debug('Template %s is valid.', name)
if __salt__['boto_cfn.exists'](name, region, key, keyid, profile):
template = __salt__['boto_cfn.get_template'](name, region, key, keyid, profile)
template = template['GetTemplateResponse']['GetTemplateResult']['TemplateBody'].encode('ascii', 'ignore')
template = salt.utils.json.loads(template)
_template_body = salt.utils.json.loads(template_body)
compare = salt.utils.compat.cmp(template, _template_body)
if compare != 0:
log.debug('Templates are not the same. Compare value is %s', compare)
# At this point we should be able to run update safely since we already validated the template
if __opts__['test']:
ret['comment'] = 'Stack {0} is set to be updated.'.format(name)
ret['result'] = None
return ret
updated = __salt__['boto_cfn.update_stack'](name, template_body, template_url, parameters,
notification_arns, disable_rollback, timeout_in_minutes,
capabilities, tags, use_previous_template,
stack_policy_during_update_body,
stack_policy_during_update_url, stack_policy_body,
stack_policy_url,
region, key, keyid, profile)
if isinstance(updated, six.string_types):
code, message = _get_error(updated)
log.debug('Update error is %s and message is %s', code, message)
ret['result'] = False
ret['comment'] = 'Stack {0} could not be updated.\n{1} \n{2}.'.format(name, code, message)
return ret
ret['comment'] = 'Cloud formation template {0} has been updated.'.format(name)
ret['changes']['new'] = updated
return ret
ret['comment'] = 'Stack {0} exists.'.format(name)
ret['changes'] = {}
return ret
if __opts__['test']:
ret['comment'] = 'Stack {0} is set to be created.'.format(name)
ret['result'] = None
return ret
created = __salt__['boto_cfn.create'](name, template_body, template_url, parameters, notification_arns,
disable_rollback, timeout_in_minutes, capabilities, tags, on_failure,
stack_policy_body, stack_policy_url, region, key, keyid, profile)
if created:
ret['comment'] = 'Stack {0} was created.'.format(name)
ret['changes']['new'] = created
return ret
ret['result'] = False
return ret | [
"def",
"present",
"(",
"name",
",",
"template_body",
"=",
"None",
",",
"template_url",
"=",
"None",
",",
"parameters",
"=",
"None",
",",
"notification_arns",
"=",
"None",
",",
"disable_rollback",
"=",
"None",
",",
"timeout_in_minutes",
"=",
"None",
",",
"cap... | Ensure cloud formation stack is present.
name (string) - Name of the stack.
template_body (string) – Structure containing the template body. Can also be loaded from a file by using salt://.
template_url (string) – Location of file containing the template body. The URL must point to a template located in
an S3 bucket in the same region as the stack.
parameters (list) – A list of key/value tuples that specify input parameters for the stack. A 3-tuple (key, value,
bool) may be used to specify the UsePreviousValue option.
notification_arns (list) – The Simple Notification Service (SNS) topic ARNs to publish stack related events.
You can find your SNS topic ARNs using the `SNS_console`_ or your Command Line Interface (CLI).
disable_rollback (bool) – Indicates whether or not to rollback on failure.
timeout_in_minutes (integer) – The amount of time that can pass before the stack status becomes CREATE_FAILED; if
DisableRollback is not set or is set to False, the stack will be rolled back.
capabilities (list) – The list of capabilities you want to allow in the stack. Currently, the only valid capability
is ‘CAPABILITY_IAM’.
tags (dict) – A set of user-defined Tags to associate with this stack, represented by key/value pairs. Tags defined
for the stack are propagated to EC2 resources that are created as part of the stack. A maximum number of 10 tags can
be specified.
on_failure (string) – Determines what action will be taken if stack creation fails. This must be one of:
DO_NOTHING, ROLLBACK, or DELETE. You can specify either OnFailure or DisableRollback, but not both.
stack_policy_body (string) – Structure containing the stack policy body. Can also be loaded from a file by using
salt://.
stack_policy_url (string) – Location of a file containing the stack policy. The URL must point to a policy
(max size: 16KB) located in an S3 bucket in the same region as the stack.If you pass StackPolicyBody and
StackPolicyURL, only StackPolicyBody is used.
use_previous_template (boolean) – Used only when templates are not the same. Set to True to use the previous
template instead of uploading a new one via TemplateBody or TemplateURL.
stack_policy_during_update_body (string) – Used only when templates are not the same. Structure containing the
temporary overriding stack policy body. If you pass StackPolicyDuringUpdateBody and StackPolicyDuringUpdateURL,
only StackPolicyDuringUpdateBody is used. Can also be loaded from a file by using salt://.
stack_policy_during_update_url (string) – Used only when templates are not the same. Location of a file containing
the temporary overriding stack policy. The URL must point to a policy (max size: 16KB) located in an S3 bucket in
the same region as the stack. If you pass StackPolicyDuringUpdateBody and StackPolicyDuringUpdateURL, only
StackPolicyDuringUpdateBody is used.
region (string) - Region to connect to.
key (string) - Secret key to be used.
keyid (string) - Access key to be used.
profile (dict) - A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key
and keyid.
.. _`SNS_console`: https://console.aws.amazon.com/sns | [
"Ensure",
"cloud",
"formation",
"stack",
"is",
"present",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_cfn.py#L75-L203 | train |
saltstack/salt | salt/states/boto_cfn.py | absent | def absent(name, region=None, key=None, keyid=None, profile=None):
'''
Ensure cloud formation stack is absent.
name (string) – The name of the stack to delete.
region (string) - Region to connect to.
key (string) - Secret key to be used.
keyid (string) - Access key to be used.
profile (dict) - A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key
and keyid.
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
if not __salt__['boto_cfn.exists'](name, region, key, keyid, profile):
ret['comment'] = 'Stack {0} does not exist.'.format(name)
ret['changes'] = {}
return ret
if __opts__['test']:
ret['comment'] = 'Stack {0} is set to be deleted.'.format(name)
ret['result'] = None
return ret
deleted = __salt__['boto_cfn.delete'](name, region, key, keyid, profile)
if isinstance(deleted, six.string_types):
code, message = _get_error(deleted)
ret['comment'] = 'Stack {0} could not be deleted.\n{1}\n{2}'.format(name, code, message)
ret['result'] = False
ret['changes'] = {}
return ret
if deleted:
ret['comment'] = 'Stack {0} was deleted.'.format(name)
ret['changes']['deleted'] = name
return ret | python | def absent(name, region=None, key=None, keyid=None, profile=None):
'''
Ensure cloud formation stack is absent.
name (string) – The name of the stack to delete.
region (string) - Region to connect to.
key (string) - Secret key to be used.
keyid (string) - Access key to be used.
profile (dict) - A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key
and keyid.
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
if not __salt__['boto_cfn.exists'](name, region, key, keyid, profile):
ret['comment'] = 'Stack {0} does not exist.'.format(name)
ret['changes'] = {}
return ret
if __opts__['test']:
ret['comment'] = 'Stack {0} is set to be deleted.'.format(name)
ret['result'] = None
return ret
deleted = __salt__['boto_cfn.delete'](name, region, key, keyid, profile)
if isinstance(deleted, six.string_types):
code, message = _get_error(deleted)
ret['comment'] = 'Stack {0} could not be deleted.\n{1}\n{2}'.format(name, code, message)
ret['result'] = False
ret['changes'] = {}
return ret
if deleted:
ret['comment'] = 'Stack {0} was deleted.'.format(name)
ret['changes']['deleted'] = name
return ret | [
"def",
"absent",
"(",
"name",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",
"''"... | Ensure cloud formation stack is absent.
name (string) – The name of the stack to delete.
region (string) - Region to connect to.
key (string) - Secret key to be used.
keyid (string) - Access key to be used.
profile (dict) - A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key
and keyid. | [
"Ensure",
"cloud",
"formation",
"stack",
"is",
"absent",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_cfn.py#L206-L240 | train |
saltstack/salt | salt/states/influxdb_continuous_query.py | present | def present(name, database, query, resample_time=None, coverage_period=None, **client_args):
'''
Ensure that given continuous query is present.
name
Name of the continuous query to create.
database
Database to create continuous query on.
query
The query content
resample_time : None
Duration between continuous query resampling.
coverage_period : None
Duration specifying time period per sample.
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': 'continuous query {0} is already present'.format(name)}
if not __salt__['influxdb.continuous_query_exists'](name=name,
database=database,
**client_args):
if __opts__['test']:
ret['result'] = None
ret['comment'] = ' {0} is absent and will be created'\
.format(name)
return ret
if __salt__['influxdb.create_continuous_query'](
database, name, query, resample_time, coverage_period
):
ret['comment'] = 'continuous query {0} has been created'\
.format(name)
ret['changes'][name] = 'Present'
return ret
else:
ret['comment'] = 'Failed to create continuous query {0}'\
.format(name)
ret['result'] = False
return ret
return ret | python | def present(name, database, query, resample_time=None, coverage_period=None, **client_args):
'''
Ensure that given continuous query is present.
name
Name of the continuous query to create.
database
Database to create continuous query on.
query
The query content
resample_time : None
Duration between continuous query resampling.
coverage_period : None
Duration specifying time period per sample.
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': 'continuous query {0} is already present'.format(name)}
if not __salt__['influxdb.continuous_query_exists'](name=name,
database=database,
**client_args):
if __opts__['test']:
ret['result'] = None
ret['comment'] = ' {0} is absent and will be created'\
.format(name)
return ret
if __salt__['influxdb.create_continuous_query'](
database, name, query, resample_time, coverage_period
):
ret['comment'] = 'continuous query {0} has been created'\
.format(name)
ret['changes'][name] = 'Present'
return ret
else:
ret['comment'] = 'Failed to create continuous query {0}'\
.format(name)
ret['result'] = False
return ret
return ret | [
"def",
"present",
"(",
"name",
",",
"database",
",",
"query",
",",
"resample_time",
"=",
"None",
",",
"coverage_period",
"=",
"None",
",",
"*",
"*",
"client_args",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
","... | Ensure that given continuous query is present.
name
Name of the continuous query to create.
database
Database to create continuous query on.
query
The query content
resample_time : None
Duration between continuous query resampling.
coverage_period : None
Duration specifying time period per sample. | [
"Ensure",
"that",
"given",
"continuous",
"query",
"is",
"present",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/influxdb_continuous_query.py#L24-L69 | train |
saltstack/salt | salt/states/timezone.py | system | def system(name, utc=True):
'''
Set the timezone for the system.
name
The name of the timezone to use (e.g.: America/Denver)
utc
Whether or not to set the hardware clock to UTC (default is True)
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
# Set up metadata
do_utc = False
do_zone = False
try:
compzone = __salt__['timezone.zone_compare'](name)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['result'] = False
ret['comment'] = (
'Unable to compare desired timezone \'{0}\' to system timezone: {1}'
.format(name, exc)
)
return ret
myutc = True
messages = []
if __salt__['timezone.get_hwclock']() == 'localtime':
myutc = False
# Check the time zone
if compzone is True:
ret['result'] = True
messages.append('Timezone {0} already set'.format(name))
else:
do_zone = True
# If the user passed in utc, do a check
if utc and utc != myutc:
ret['result'] = None
do_utc = True
elif utc and utc == myutc:
messages.append('UTC already set to {0}'.format(name))
if ret['result'] is True:
ret['comment'] = ', '.join(messages)
return ret
if __opts__['test']:
messages = []
if compzone is False:
messages.append('Timezone {0} needs to be set'.format(name))
if utc and myutc != utc:
messages.append('UTC needs to be set to {0}'.format(utc))
ret['comment'] = ', '.join(messages)
return ret
messages = []
if do_zone:
if __salt__['timezone.set_zone'](name):
ret['changes']['timezone'] = name
messages.append('Set timezone {0}'.format(name))
ret['result'] = True
else:
messages.append('Failed to set timezone')
ret['result'] = False
if do_utc:
clock = 'localtime'
if utc:
clock = 'UTC'
if __salt__['timezone.set_hwclock'](clock):
ret['changes']['utc'] = utc
messages.append('Set UTC to {0}'.format(utc))
ret['result'] = True
else:
messages.append('Failed to set UTC to {0}'.format(utc))
ret['result'] = False
ret['comment'] = ', '.join(messages)
return ret | python | def system(name, utc=True):
'''
Set the timezone for the system.
name
The name of the timezone to use (e.g.: America/Denver)
utc
Whether or not to set the hardware clock to UTC (default is True)
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
# Set up metadata
do_utc = False
do_zone = False
try:
compzone = __salt__['timezone.zone_compare'](name)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['result'] = False
ret['comment'] = (
'Unable to compare desired timezone \'{0}\' to system timezone: {1}'
.format(name, exc)
)
return ret
myutc = True
messages = []
if __salt__['timezone.get_hwclock']() == 'localtime':
myutc = False
# Check the time zone
if compzone is True:
ret['result'] = True
messages.append('Timezone {0} already set'.format(name))
else:
do_zone = True
# If the user passed in utc, do a check
if utc and utc != myutc:
ret['result'] = None
do_utc = True
elif utc and utc == myutc:
messages.append('UTC already set to {0}'.format(name))
if ret['result'] is True:
ret['comment'] = ', '.join(messages)
return ret
if __opts__['test']:
messages = []
if compzone is False:
messages.append('Timezone {0} needs to be set'.format(name))
if utc and myutc != utc:
messages.append('UTC needs to be set to {0}'.format(utc))
ret['comment'] = ', '.join(messages)
return ret
messages = []
if do_zone:
if __salt__['timezone.set_zone'](name):
ret['changes']['timezone'] = name
messages.append('Set timezone {0}'.format(name))
ret['result'] = True
else:
messages.append('Failed to set timezone')
ret['result'] = False
if do_utc:
clock = 'localtime'
if utc:
clock = 'UTC'
if __salt__['timezone.set_hwclock'](clock):
ret['changes']['utc'] = utc
messages.append('Set UTC to {0}'.format(utc))
ret['result'] = True
else:
messages.append('Failed to set UTC to {0}'.format(utc))
ret['result'] = False
ret['comment'] = ', '.join(messages)
return ret | [
"def",
"system",
"(",
"name",
",",
"utc",
"=",
"True",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"None",
",",
"'comment'",
":",
"''",
"}",
"# Set up metadata",
"do_utc",
"=",
"False",
"... | Set the timezone for the system.
name
The name of the timezone to use (e.g.: America/Denver)
utc
Whether or not to set the hardware clock to UTC (default is True) | [
"Set",
"the",
"timezone",
"for",
"the",
"system",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/timezone.py#L43-L127 | train |
saltstack/salt | salt/modules/nova.py | _auth | def _auth(profile=None, **kwargs):
'''
Set up nova credentials
'''
keystone_api_args = None
if kwargs is not None:
if kwargs.get('keystone_api_args') is not None:
keystone_api_args = kwargs['keystone_api_args']
if profile:
credentials = __salt__['config.option'](profile)
user = credentials['keystone.user']
password = credentials['keystone.password']
tenant = credentials['keystone.tenant']
auth_url = credentials['keystone.auth_url']
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)
use_keystoneauth = credentials.get('keystone.use_keystoneauth', False)
else:
user = __salt__['config.option']('keystone.user')
password = __salt__['config.option']('keystone.password')
tenant = __salt__['config.option']('keystone.tenant')
auth_url = __salt__['config.option']('keystone.auth_url')
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')
use_keystoneauth = __salt__['config.option']('keystone.use_keystoneauth')
# Override pillar settings with settings provided by module argument
if keystone_api_args:
user = keystone_api_args.get('user', user)
password = keystone_api_args.get('password', password)
tenant = keystone_api_args.get('tenant', tenant)
auth_url = keystone_api_args.get('auth_url', auth_url)
region_name = keystone_api_args.get('region_name', region_name)
api_key = keystone_api_args.get('api_key', api_key)
os_auth_system = keystone_api_args.get('os_auth_system', os_auth_system)
use_keystoneauth = keystone_api_args.get('use_keystoneauth', use_keystoneauth)
if use_keystoneauth is True:
if profile:
credentials = __salt__['config.option'](profile)
project_id = credentials.get('keystone.project_id', None)
project_name = credentials.get('keystone.project_name', None)
user_domain_name = credentials.get('keystone.user_domain_name', None)
project_domain_name = credentials.get('keystone.project_domain_name', None)
verify = credentials.get('keystone.verify', None)
else:
project_id = __salt__['config.option']('keystone.project_id')
project_name = __salt__['config.option']('keystone.project_name')
user_domain_name = __salt__['config.option']('keystone.user_domain_name')
project_domain_name = __salt__['config.option']('keystone.project_domain_name')
verify = __salt__['config.option']('keystone.verify')
# Override pillar settings with settings provided by module argument
if keystone_api_args:
project_id = keystone_api_args.get('project_id', project_id)
project_name = keystone_api_args.get('project_name', project_name)
user_domain_name = keystone_api_args.get('user_domain_name', user_domain_name)
project_domain_name = keystone_api_args.get('project_domain_name', project_domain_name)
verify = keystone_api_args.get('verify', verify)
send_kwargs = {
'username': user,
'password': password,
'project_id': project_id,
'auth_url': auth_url,
'region_name': region_name,
'use_keystoneauth': use_keystoneauth,
'verify': verify,
'project_name': project_name,
'project_domain_name': project_domain_name,
'user_domain_name': user_domain_name
}
else:
send_kwargs = {
'username': user,
'password': password,
'api_key': api_key,
'project_id': tenant,
'auth_url': auth_url,
'region_name': region_name,
'os_auth_plugin': os_auth_system
}
log.debug('SEND_KWARGS: %s', send_kwargs)
return suon.SaltNova(**send_kwargs) | python | def _auth(profile=None, **kwargs):
'''
Set up nova credentials
'''
keystone_api_args = None
if kwargs is not None:
if kwargs.get('keystone_api_args') is not None:
keystone_api_args = kwargs['keystone_api_args']
if profile:
credentials = __salt__['config.option'](profile)
user = credentials['keystone.user']
password = credentials['keystone.password']
tenant = credentials['keystone.tenant']
auth_url = credentials['keystone.auth_url']
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)
use_keystoneauth = credentials.get('keystone.use_keystoneauth', False)
else:
user = __salt__['config.option']('keystone.user')
password = __salt__['config.option']('keystone.password')
tenant = __salt__['config.option']('keystone.tenant')
auth_url = __salt__['config.option']('keystone.auth_url')
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')
use_keystoneauth = __salt__['config.option']('keystone.use_keystoneauth')
# Override pillar settings with settings provided by module argument
if keystone_api_args:
user = keystone_api_args.get('user', user)
password = keystone_api_args.get('password', password)
tenant = keystone_api_args.get('tenant', tenant)
auth_url = keystone_api_args.get('auth_url', auth_url)
region_name = keystone_api_args.get('region_name', region_name)
api_key = keystone_api_args.get('api_key', api_key)
os_auth_system = keystone_api_args.get('os_auth_system', os_auth_system)
use_keystoneauth = keystone_api_args.get('use_keystoneauth', use_keystoneauth)
if use_keystoneauth is True:
if profile:
credentials = __salt__['config.option'](profile)
project_id = credentials.get('keystone.project_id', None)
project_name = credentials.get('keystone.project_name', None)
user_domain_name = credentials.get('keystone.user_domain_name', None)
project_domain_name = credentials.get('keystone.project_domain_name', None)
verify = credentials.get('keystone.verify', None)
else:
project_id = __salt__['config.option']('keystone.project_id')
project_name = __salt__['config.option']('keystone.project_name')
user_domain_name = __salt__['config.option']('keystone.user_domain_name')
project_domain_name = __salt__['config.option']('keystone.project_domain_name')
verify = __salt__['config.option']('keystone.verify')
# Override pillar settings with settings provided by module argument
if keystone_api_args:
project_id = keystone_api_args.get('project_id', project_id)
project_name = keystone_api_args.get('project_name', project_name)
user_domain_name = keystone_api_args.get('user_domain_name', user_domain_name)
project_domain_name = keystone_api_args.get('project_domain_name', project_domain_name)
verify = keystone_api_args.get('verify', verify)
send_kwargs = {
'username': user,
'password': password,
'project_id': project_id,
'auth_url': auth_url,
'region_name': region_name,
'use_keystoneauth': use_keystoneauth,
'verify': verify,
'project_name': project_name,
'project_domain_name': project_domain_name,
'user_domain_name': user_domain_name
}
else:
send_kwargs = {
'username': user,
'password': password,
'api_key': api_key,
'project_id': tenant,
'auth_url': auth_url,
'region_name': region_name,
'os_auth_plugin': os_auth_system
}
log.debug('SEND_KWARGS: %s', send_kwargs)
return suon.SaltNova(**send_kwargs) | [
"def",
"_auth",
"(",
"profile",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"keystone_api_args",
"=",
"None",
"if",
"kwargs",
"is",
"not",
"None",
":",
"if",
"kwargs",
".",
"get",
"(",
"'keystone_api_args'",
")",
"is",
"not",
"None",
":",
"keystone... | Set up nova credentials | [
"Set",
"up",
"nova",
"credentials"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nova.py#L124-L210 | train |
saltstack/salt | salt/modules/nova.py | boot | def boot(name, flavor_id=0, image_id=0, profile=None, timeout=300, **kwargs):
'''
Boot (create) a new instance
name
Name of the new instance (must be first)
flavor_id
Unique integer ID for the flavor
image_id
Unique integer ID for the image
timeout
How long to wait, after creating the instance, for the provider to
return information about it (default 300 seconds).
.. versionadded:: 2014.1.0
CLI Example:
.. code-block:: bash
salt '*' nova.boot myinstance flavor_id=4596 image_id=2
The flavor_id and image_id are obtained from nova.flavor_list and
nova.image_list
.. code-block:: bash
salt '*' nova.flavor_list
salt '*' nova.image_list
'''
conn = _auth(profile, **kwargs)
return conn.boot(name, flavor_id, image_id, timeout) | python | def boot(name, flavor_id=0, image_id=0, profile=None, timeout=300, **kwargs):
'''
Boot (create) a new instance
name
Name of the new instance (must be first)
flavor_id
Unique integer ID for the flavor
image_id
Unique integer ID for the image
timeout
How long to wait, after creating the instance, for the provider to
return information about it (default 300 seconds).
.. versionadded:: 2014.1.0
CLI Example:
.. code-block:: bash
salt '*' nova.boot myinstance flavor_id=4596 image_id=2
The flavor_id and image_id are obtained from nova.flavor_list and
nova.image_list
.. code-block:: bash
salt '*' nova.flavor_list
salt '*' nova.image_list
'''
conn = _auth(profile, **kwargs)
return conn.boot(name, flavor_id, image_id, timeout) | [
"def",
"boot",
"(",
"name",
",",
"flavor_id",
"=",
"0",
",",
"image_id",
"=",
"0",
",",
"profile",
"=",
"None",
",",
"timeout",
"=",
"300",
",",
"*",
"*",
"kwargs",
")",
":",
"conn",
"=",
"_auth",
"(",
"profile",
",",
"*",
"*",
"kwargs",
")",
"... | Boot (create) a new instance
name
Name of the new instance (must be first)
flavor_id
Unique integer ID for the flavor
image_id
Unique integer ID for the image
timeout
How long to wait, after creating the instance, for the provider to
return information about it (default 300 seconds).
.. versionadded:: 2014.1.0
CLI Example:
.. code-block:: bash
salt '*' nova.boot myinstance flavor_id=4596 image_id=2
The flavor_id and image_id are obtained from nova.flavor_list and
nova.image_list
.. code-block:: bash
salt '*' nova.flavor_list
salt '*' nova.image_list | [
"Boot",
"(",
"create",
")",
"a",
"new",
"instance"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nova.py#L213-L247 | train |
saltstack/salt | salt/modules/nova.py | volume_list | def volume_list(search_opts=None, profile=None, **kwargs):
'''
List storage volumes
search_opts
Dictionary of search options
profile
Profile to use
CLI Example:
.. code-block:: bash
salt '*' nova.volume_list search_opts='{"display_name": "myblock"}' profile=openstack
'''
conn = _auth(profile, **kwargs)
return conn.volume_list(search_opts=search_opts) | python | def volume_list(search_opts=None, profile=None, **kwargs):
'''
List storage volumes
search_opts
Dictionary of search options
profile
Profile to use
CLI Example:
.. code-block:: bash
salt '*' nova.volume_list search_opts='{"display_name": "myblock"}' profile=openstack
'''
conn = _auth(profile, **kwargs)
return conn.volume_list(search_opts=search_opts) | [
"def",
"volume_list",
"(",
"search_opts",
"=",
"None",
",",
"profile",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"conn",
"=",
"_auth",
"(",
"profile",
",",
"*",
"*",
"kwargs",
")",
"return",
"conn",
".",
"volume_list",
"(",
"search_opts",
"=",
... | List storage volumes
search_opts
Dictionary of search options
profile
Profile to use
CLI Example:
.. code-block:: bash
salt '*' nova.volume_list search_opts='{"display_name": "myblock"}' profile=openstack | [
"List",
"storage",
"volumes"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nova.py#L250-L268 | train |
saltstack/salt | salt/modules/nova.py | volume_show | def volume_show(name, profile=None, **kwargs):
'''
Create a block storage volume
name
Name of the volume
profile
Profile to use
CLI Example:
.. code-block:: bash
salt '*' nova.volume_show myblock profile=openstack
'''
conn = _auth(profile, **kwargs)
return conn.volume_show(name) | python | def volume_show(name, profile=None, **kwargs):
'''
Create a block storage volume
name
Name of the volume
profile
Profile to use
CLI Example:
.. code-block:: bash
salt '*' nova.volume_show myblock profile=openstack
'''
conn = _auth(profile, **kwargs)
return conn.volume_show(name) | [
"def",
"volume_show",
"(",
"name",
",",
"profile",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"conn",
"=",
"_auth",
"(",
"profile",
",",
"*",
"*",
"kwargs",
")",
"return",
"conn",
".",
"volume_show",
"(",
"name",
")"
] | Create a block storage volume
name
Name of the volume
profile
Profile to use
CLI Example:
.. code-block:: bash
salt '*' nova.volume_show myblock profile=openstack | [
"Create",
"a",
"block",
"storage",
"volume"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nova.py#L271-L289 | train |
saltstack/salt | salt/modules/nova.py | volume_create | def volume_create(name, size=100, snapshot=None, voltype=None, profile=None, **kwargs):
'''
Create a block storage volume
name
Name of the new volume (must be first)
size
Volume size
snapshot
Block storage snapshot id
voltype
Type of storage
profile
Profile to build on
CLI Example:
.. code-block:: bash
salt '*' nova.volume_create myblock size=300 profile=openstack
'''
conn = _auth(profile, **kwargs)
return conn.volume_create(
name,
size,
snapshot,
voltype
) | python | def volume_create(name, size=100, snapshot=None, voltype=None, profile=None, **kwargs):
'''
Create a block storage volume
name
Name of the new volume (must be first)
size
Volume size
snapshot
Block storage snapshot id
voltype
Type of storage
profile
Profile to build on
CLI Example:
.. code-block:: bash
salt '*' nova.volume_create myblock size=300 profile=openstack
'''
conn = _auth(profile, **kwargs)
return conn.volume_create(
name,
size,
snapshot,
voltype
) | [
"def",
"volume_create",
"(",
"name",
",",
"size",
"=",
"100",
",",
"snapshot",
"=",
"None",
",",
"voltype",
"=",
"None",
",",
"profile",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"conn",
"=",
"_auth",
"(",
"profile",
",",
"*",
"*",
"kwargs",
... | Create a block storage volume
name
Name of the new volume (must be first)
size
Volume size
snapshot
Block storage snapshot id
voltype
Type of storage
profile
Profile to build on
CLI Example:
.. code-block:: bash
salt '*' nova.volume_create myblock size=300 profile=openstack | [
"Create",
"a",
"block",
"storage",
"volume"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nova.py#L292-L324 | train |
saltstack/salt | salt/modules/nova.py | volume_delete | def volume_delete(name, profile=None, **kwargs):
'''
Destroy the volume
name
Name of the volume
profile
Profile to build on
CLI Example:
.. code-block:: bash
salt '*' nova.volume_delete myblock profile=openstack
'''
conn = _auth(profile, **kwargs)
return conn.volume_delete(name) | python | def volume_delete(name, profile=None, **kwargs):
'''
Destroy the volume
name
Name of the volume
profile
Profile to build on
CLI Example:
.. code-block:: bash
salt '*' nova.volume_delete myblock profile=openstack
'''
conn = _auth(profile, **kwargs)
return conn.volume_delete(name) | [
"def",
"volume_delete",
"(",
"name",
",",
"profile",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"conn",
"=",
"_auth",
"(",
"profile",
",",
"*",
"*",
"kwargs",
")",
"return",
"conn",
".",
"volume_delete",
"(",
"name",
")"
] | Destroy the volume
name
Name of the volume
profile
Profile to build on
CLI Example:
.. code-block:: bash
salt '*' nova.volume_delete myblock profile=openstack | [
"Destroy",
"the",
"volume"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nova.py#L327-L345 | train |
saltstack/salt | salt/modules/nova.py | volume_detach | def volume_detach(name, profile=None, timeout=300, **kwargs):
'''
Attach a block storage volume
name
Name of the new volume to attach
server_name
Name of the server to detach from
profile
Profile to build on
CLI Example:
.. code-block:: bash
salt '*' nova.volume_detach myblock profile=openstack
'''
conn = _auth(profile, **kwargs)
return conn.volume_detach(
name,
timeout
) | python | def volume_detach(name, profile=None, timeout=300, **kwargs):
'''
Attach a block storage volume
name
Name of the new volume to attach
server_name
Name of the server to detach from
profile
Profile to build on
CLI Example:
.. code-block:: bash
salt '*' nova.volume_detach myblock profile=openstack
'''
conn = _auth(profile, **kwargs)
return conn.volume_detach(
name,
timeout
) | [
"def",
"volume_detach",
"(",
"name",
",",
"profile",
"=",
"None",
",",
"timeout",
"=",
"300",
",",
"*",
"*",
"kwargs",
")",
":",
"conn",
"=",
"_auth",
"(",
"profile",
",",
"*",
"*",
"kwargs",
")",
"return",
"conn",
".",
"volume_detach",
"(",
"name",
... | Attach a block storage volume
name
Name of the new volume to attach
server_name
Name of the server to detach from
profile
Profile to build on
CLI Example:
.. code-block:: bash
salt '*' nova.volume_detach myblock profile=openstack | [
"Attach",
"a",
"block",
"storage",
"volume"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nova.py#L348-L372 | train |
saltstack/salt | salt/modules/nova.py | volume_attach | def volume_attach(name,
server_name,
device='/dev/xvdb',
profile=None,
timeout=300, **kwargs):
'''
Attach a block storage volume
name
Name of the new volume to attach
server_name
Name of the server to attach to
device
Name of the device on the server
profile
Profile to build on
CLI Example:
.. code-block:: bash
salt '*' nova.volume_attach myblock slice.example.com profile=openstack
salt '*' nova.volume_attach myblock server.example.com device='/dev/xvdb' profile=openstack
'''
conn = _auth(profile, **kwargs)
return conn.volume_attach(
name,
server_name,
device,
timeout
) | python | def volume_attach(name,
server_name,
device='/dev/xvdb',
profile=None,
timeout=300, **kwargs):
'''
Attach a block storage volume
name
Name of the new volume to attach
server_name
Name of the server to attach to
device
Name of the device on the server
profile
Profile to build on
CLI Example:
.. code-block:: bash
salt '*' nova.volume_attach myblock slice.example.com profile=openstack
salt '*' nova.volume_attach myblock server.example.com device='/dev/xvdb' profile=openstack
'''
conn = _auth(profile, **kwargs)
return conn.volume_attach(
name,
server_name,
device,
timeout
) | [
"def",
"volume_attach",
"(",
"name",
",",
"server_name",
",",
"device",
"=",
"'/dev/xvdb'",
",",
"profile",
"=",
"None",
",",
"timeout",
"=",
"300",
",",
"*",
"*",
"kwargs",
")",
":",
"conn",
"=",
"_auth",
"(",
"profile",
",",
"*",
"*",
"kwargs",
")"... | Attach a block storage volume
name
Name of the new volume to attach
server_name
Name of the server to attach to
device
Name of the device on the server
profile
Profile to build on
CLI Example:
.. code-block:: bash
salt '*' nova.volume_attach myblock slice.example.com profile=openstack
salt '*' nova.volume_attach myblock server.example.com device='/dev/xvdb' profile=openstack | [
"Attach",
"a",
"block",
"storage",
"volume"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nova.py#L375-L409 | train |
saltstack/salt | salt/modules/nova.py | suspend | def suspend(instance_id, profile=None, **kwargs):
'''
Suspend an instance
instance_id
ID of the instance to be suspended
CLI Example:
.. code-block:: bash
salt '*' nova.suspend 1138
'''
conn = _auth(profile, **kwargs)
return conn.suspend(instance_id) | python | def suspend(instance_id, profile=None, **kwargs):
'''
Suspend an instance
instance_id
ID of the instance to be suspended
CLI Example:
.. code-block:: bash
salt '*' nova.suspend 1138
'''
conn = _auth(profile, **kwargs)
return conn.suspend(instance_id) | [
"def",
"suspend",
"(",
"instance_id",
",",
"profile",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"conn",
"=",
"_auth",
"(",
"profile",
",",
"*",
"*",
"kwargs",
")",
"return",
"conn",
".",
"suspend",
"(",
"instance_id",
")"
] | Suspend an instance
instance_id
ID of the instance to be suspended
CLI Example:
.. code-block:: bash
salt '*' nova.suspend 1138 | [
"Suspend",
"an",
"instance"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nova.py#L412-L427 | train |
saltstack/salt | salt/modules/nova.py | resume | def resume(instance_id, profile=None, **kwargs):
'''
Resume an instance
instance_id
ID of the instance to be resumed
CLI Example:
.. code-block:: bash
salt '*' nova.resume 1138
'''
conn = _auth(profile, **kwargs)
return conn.resume(instance_id) | python | def resume(instance_id, profile=None, **kwargs):
'''
Resume an instance
instance_id
ID of the instance to be resumed
CLI Example:
.. code-block:: bash
salt '*' nova.resume 1138
'''
conn = _auth(profile, **kwargs)
return conn.resume(instance_id) | [
"def",
"resume",
"(",
"instance_id",
",",
"profile",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"conn",
"=",
"_auth",
"(",
"profile",
",",
"*",
"*",
"kwargs",
")",
"return",
"conn",
".",
"resume",
"(",
"instance_id",
")"
] | Resume an instance
instance_id
ID of the instance to be resumed
CLI Example:
.. code-block:: bash
salt '*' nova.resume 1138 | [
"Resume",
"an",
"instance"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nova.py#L430-L445 | train |
saltstack/salt | salt/modules/nova.py | lock | def lock(instance_id, profile=None, **kwargs):
'''
Lock an instance
instance_id
ID of the instance to be locked
CLI Example:
.. code-block:: bash
salt '*' nova.lock 1138
'''
conn = _auth(profile, **kwargs)
return conn.lock(instance_id) | python | def lock(instance_id, profile=None, **kwargs):
'''
Lock an instance
instance_id
ID of the instance to be locked
CLI Example:
.. code-block:: bash
salt '*' nova.lock 1138
'''
conn = _auth(profile, **kwargs)
return conn.lock(instance_id) | [
"def",
"lock",
"(",
"instance_id",
",",
"profile",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"conn",
"=",
"_auth",
"(",
"profile",
",",
"*",
"*",
"kwargs",
")",
"return",
"conn",
".",
"lock",
"(",
"instance_id",
")"
] | Lock an instance
instance_id
ID of the instance to be locked
CLI Example:
.. code-block:: bash
salt '*' nova.lock 1138 | [
"Lock",
"an",
"instance"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nova.py#L448-L463 | train |
saltstack/salt | salt/modules/nova.py | delete | def delete(instance_id, profile=None, **kwargs):
'''
Delete an instance
instance_id
ID of the instance to be deleted
CLI Example:
.. code-block:: bash
salt '*' nova.delete 1138
'''
conn = _auth(profile, **kwargs)
return conn.delete(instance_id) | python | def delete(instance_id, profile=None, **kwargs):
'''
Delete an instance
instance_id
ID of the instance to be deleted
CLI Example:
.. code-block:: bash
salt '*' nova.delete 1138
'''
conn = _auth(profile, **kwargs)
return conn.delete(instance_id) | [
"def",
"delete",
"(",
"instance_id",
",",
"profile",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"conn",
"=",
"_auth",
"(",
"profile",
",",
"*",
"*",
"kwargs",
")",
"return",
"conn",
".",
"delete",
"(",
"instance_id",
")"
] | Delete an instance
instance_id
ID of the instance to be deleted
CLI Example:
.. code-block:: bash
salt '*' nova.delete 1138 | [
"Delete",
"an",
"instance"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nova.py#L466-L481 | train |
saltstack/salt | salt/modules/nova.py | flavor_list | def flavor_list(profile=None, **kwargs):
'''
Return a list of available flavors (nova flavor-list)
CLI Example:
.. code-block:: bash
salt '*' nova.flavor_list
'''
filters = kwargs.get('filter', {})
conn = _auth(profile, **kwargs)
return conn.flavor_list(**filters) | python | def flavor_list(profile=None, **kwargs):
'''
Return a list of available flavors (nova flavor-list)
CLI Example:
.. code-block:: bash
salt '*' nova.flavor_list
'''
filters = kwargs.get('filter', {})
conn = _auth(profile, **kwargs)
return conn.flavor_list(**filters) | [
"def",
"flavor_list",
"(",
"profile",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"filters",
"=",
"kwargs",
".",
"get",
"(",
"'filter'",
",",
"{",
"}",
")",
"conn",
"=",
"_auth",
"(",
"profile",
",",
"*",
"*",
"kwargs",
")",
"return",
"conn",
... | Return a list of available flavors (nova flavor-list)
CLI Example:
.. code-block:: bash
salt '*' nova.flavor_list | [
"Return",
"a",
"list",
"of",
"available",
"flavors",
"(",
"nova",
"flavor",
"-",
"list",
")"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nova.py#L484-L496 | train |
saltstack/salt | salt/modules/nova.py | flavor_create | def flavor_create(name, # pylint: disable=C0103
flavor_id=0, # pylint: disable=C0103
ram=0,
disk=0,
vcpus=1,
is_public=True,
profile=None, **kwargs):
'''
Add a flavor to nova (nova flavor-create). The following parameters are
required:
name
Name of the new flavor (must be first)
flavor_id
Unique integer ID for the new flavor
ram
Memory size in MB
disk
Disk size in GB
vcpus
Number of vcpus
is_public
Whether flavor is public. Default is True.
CLI Example:
.. code-block:: bash
salt '*' nova.flavor_create myflavor flavor_id=6 ram=4096 disk=10 vcpus=1
'''
conn = _auth(profile, **kwargs)
return conn.flavor_create(
name,
flavor_id,
ram,
disk,
vcpus,
is_public
) | python | def flavor_create(name, # pylint: disable=C0103
flavor_id=0, # pylint: disable=C0103
ram=0,
disk=0,
vcpus=1,
is_public=True,
profile=None, **kwargs):
'''
Add a flavor to nova (nova flavor-create). The following parameters are
required:
name
Name of the new flavor (must be first)
flavor_id
Unique integer ID for the new flavor
ram
Memory size in MB
disk
Disk size in GB
vcpus
Number of vcpus
is_public
Whether flavor is public. Default is True.
CLI Example:
.. code-block:: bash
salt '*' nova.flavor_create myflavor flavor_id=6 ram=4096 disk=10 vcpus=1
'''
conn = _auth(profile, **kwargs)
return conn.flavor_create(
name,
flavor_id,
ram,
disk,
vcpus,
is_public
) | [
"def",
"flavor_create",
"(",
"name",
",",
"# pylint: disable=C0103",
"flavor_id",
"=",
"0",
",",
"# pylint: disable=C0103",
"ram",
"=",
"0",
",",
"disk",
"=",
"0",
",",
"vcpus",
"=",
"1",
",",
"is_public",
"=",
"True",
",",
"profile",
"=",
"None",
",",
"... | Add a flavor to nova (nova flavor-create). The following parameters are
required:
name
Name of the new flavor (must be first)
flavor_id
Unique integer ID for the new flavor
ram
Memory size in MB
disk
Disk size in GB
vcpus
Number of vcpus
is_public
Whether flavor is public. Default is True.
CLI Example:
.. code-block:: bash
salt '*' nova.flavor_create myflavor flavor_id=6 ram=4096 disk=10 vcpus=1 | [
"Add",
"a",
"flavor",
"to",
"nova",
"(",
"nova",
"flavor",
"-",
"create",
")",
".",
"The",
"following",
"parameters",
"are",
"required",
":"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nova.py#L499-L537 | train |
saltstack/salt | salt/modules/nova.py | flavor_delete | def flavor_delete(flavor_id, profile=None, **kwargs): # pylint: disable=C0103
'''
Delete a flavor from nova by id (nova flavor-delete)
CLI Example:
.. code-block:: bash
salt '*' nova.flavor_delete 7
'''
conn = _auth(profile, **kwargs)
return conn.flavor_delete(flavor_id) | python | def flavor_delete(flavor_id, profile=None, **kwargs): # pylint: disable=C0103
'''
Delete a flavor from nova by id (nova flavor-delete)
CLI Example:
.. code-block:: bash
salt '*' nova.flavor_delete 7
'''
conn = _auth(profile, **kwargs)
return conn.flavor_delete(flavor_id) | [
"def",
"flavor_delete",
"(",
"flavor_id",
",",
"profile",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=C0103",
"conn",
"=",
"_auth",
"(",
"profile",
",",
"*",
"*",
"kwargs",
")",
"return",
"conn",
".",
"flavor_delete",
"(",
"flavor_id... | Delete a flavor from nova by id (nova flavor-delete)
CLI Example:
.. code-block:: bash
salt '*' nova.flavor_delete 7 | [
"Delete",
"a",
"flavor",
"from",
"nova",
"by",
"id",
"(",
"nova",
"flavor",
"-",
"delete",
")"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nova.py#L540-L551 | train |
saltstack/salt | salt/modules/nova.py | flavor_access_list | def flavor_access_list(flavor_id, profile=None, **kwargs):
'''
Return a list of project IDs assigned to flavor ID
CLI Example:
.. code-block:: bash
salt '*' nova.flavor_access_list flavor_id=ID
'''
conn = _auth(profile, **kwargs)
return conn.flavor_access_list(flavor_id=flavor_id, **kwargs) | python | def flavor_access_list(flavor_id, profile=None, **kwargs):
'''
Return a list of project IDs assigned to flavor ID
CLI Example:
.. code-block:: bash
salt '*' nova.flavor_access_list flavor_id=ID
'''
conn = _auth(profile, **kwargs)
return conn.flavor_access_list(flavor_id=flavor_id, **kwargs) | [
"def",
"flavor_access_list",
"(",
"flavor_id",
",",
"profile",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"conn",
"=",
"_auth",
"(",
"profile",
",",
"*",
"*",
"kwargs",
")",
"return",
"conn",
".",
"flavor_access_list",
"(",
"flavor_id",
"=",
"flavor... | Return a list of project IDs assigned to flavor ID
CLI Example:
.. code-block:: bash
salt '*' nova.flavor_access_list flavor_id=ID | [
"Return",
"a",
"list",
"of",
"project",
"IDs",
"assigned",
"to",
"flavor",
"ID"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nova.py#L554-L565 | train |
saltstack/salt | salt/modules/nova.py | flavor_access_add | def flavor_access_add(flavor_id, project_id, profile=None, **kwargs):
'''
Add a project to the flavor access list
CLI Example:
.. code-block:: bash
salt '*' nova.flavor_access_add flavor_id=fID project_id=pID
'''
conn = _auth(profile, **kwargs)
return conn.flavor_access_add(flavor_id, project_id) | python | def flavor_access_add(flavor_id, project_id, profile=None, **kwargs):
'''
Add a project to the flavor access list
CLI Example:
.. code-block:: bash
salt '*' nova.flavor_access_add flavor_id=fID project_id=pID
'''
conn = _auth(profile, **kwargs)
return conn.flavor_access_add(flavor_id, project_id) | [
"def",
"flavor_access_add",
"(",
"flavor_id",
",",
"project_id",
",",
"profile",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"conn",
"=",
"_auth",
"(",
"profile",
",",
"*",
"*",
"kwargs",
")",
"return",
"conn",
".",
"flavor_access_add",
"(",
"flavor_... | Add a project to the flavor access list
CLI Example:
.. code-block:: bash
salt '*' nova.flavor_access_add flavor_id=fID project_id=pID | [
"Add",
"a",
"project",
"to",
"the",
"flavor",
"access",
"list"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nova.py#L568-L579 | train |
saltstack/salt | salt/modules/nova.py | flavor_access_remove | def flavor_access_remove(flavor_id, project_id, profile=None, **kwargs):
'''
Remove a project from the flavor access list
CLI Example:
.. code-block:: bash
salt '*' nova.flavor_access_remove flavor_id=fID project_id=pID
'''
conn = _auth(profile, **kwargs)
return conn.flavor_access_remove(flavor_id, project_id) | python | def flavor_access_remove(flavor_id, project_id, profile=None, **kwargs):
'''
Remove a project from the flavor access list
CLI Example:
.. code-block:: bash
salt '*' nova.flavor_access_remove flavor_id=fID project_id=pID
'''
conn = _auth(profile, **kwargs)
return conn.flavor_access_remove(flavor_id, project_id) | [
"def",
"flavor_access_remove",
"(",
"flavor_id",
",",
"project_id",
",",
"profile",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"conn",
"=",
"_auth",
"(",
"profile",
",",
"*",
"*",
"kwargs",
")",
"return",
"conn",
".",
"flavor_access_remove",
"(",
"f... | Remove a project from the flavor access list
CLI Example:
.. code-block:: bash
salt '*' nova.flavor_access_remove flavor_id=fID project_id=pID | [
"Remove",
"a",
"project",
"from",
"the",
"flavor",
"access",
"list"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nova.py#L582-L593 | train |
saltstack/salt | salt/modules/nova.py | keypair_add | def keypair_add(name, pubfile=None, pubkey=None, profile=None, **kwargs):
'''
Add a keypair to nova (nova keypair-add)
CLI Examples:
.. code-block:: bash
salt '*' nova.keypair_add mykey pubfile='/home/myuser/.ssh/id_rsa.pub'
salt '*' nova.keypair_add mykey pubkey='ssh-rsa <key> myuser@mybox'
'''
conn = _auth(profile, **kwargs)
return conn.keypair_add(
name,
pubfile,
pubkey
) | python | def keypair_add(name, pubfile=None, pubkey=None, profile=None, **kwargs):
'''
Add a keypair to nova (nova keypair-add)
CLI Examples:
.. code-block:: bash
salt '*' nova.keypair_add mykey pubfile='/home/myuser/.ssh/id_rsa.pub'
salt '*' nova.keypair_add mykey pubkey='ssh-rsa <key> myuser@mybox'
'''
conn = _auth(profile, **kwargs)
return conn.keypair_add(
name,
pubfile,
pubkey
) | [
"def",
"keypair_add",
"(",
"name",
",",
"pubfile",
"=",
"None",
",",
"pubkey",
"=",
"None",
",",
"profile",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"conn",
"=",
"_auth",
"(",
"profile",
",",
"*",
"*",
"kwargs",
")",
"return",
"conn",
".",
... | Add a keypair to nova (nova keypair-add)
CLI Examples:
.. code-block:: bash
salt '*' nova.keypair_add mykey pubfile='/home/myuser/.ssh/id_rsa.pub'
salt '*' nova.keypair_add mykey pubkey='ssh-rsa <key> myuser@mybox' | [
"Add",
"a",
"keypair",
"to",
"nova",
"(",
"nova",
"keypair",
"-",
"add",
")"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nova.py#L610-L626 | train |
saltstack/salt | salt/modules/nova.py | keypair_delete | def keypair_delete(name, profile=None, **kwargs):
'''
Add a keypair to nova (nova keypair-delete)
CLI Example:
.. code-block:: bash
salt '*' nova.keypair_delete mykey
'''
conn = _auth(profile, **kwargs)
return conn.keypair_delete(name) | python | def keypair_delete(name, profile=None, **kwargs):
'''
Add a keypair to nova (nova keypair-delete)
CLI Example:
.. code-block:: bash
salt '*' nova.keypair_delete mykey
'''
conn = _auth(profile, **kwargs)
return conn.keypair_delete(name) | [
"def",
"keypair_delete",
"(",
"name",
",",
"profile",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"conn",
"=",
"_auth",
"(",
"profile",
",",
"*",
"*",
"kwargs",
")",
"return",
"conn",
".",
"keypair_delete",
"(",
"name",
")"
] | Add a keypair to nova (nova keypair-delete)
CLI Example:
.. code-block:: bash
salt '*' nova.keypair_delete mykey | [
"Add",
"a",
"keypair",
"to",
"nova",
"(",
"nova",
"keypair",
"-",
"delete",
")"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nova.py#L629-L640 | train |
saltstack/salt | salt/modules/nova.py | image_list | def image_list(name=None, profile=None, **kwargs):
'''
Return a list of available images (nova images-list + nova image-show)
If a name is provided, only that image will be displayed.
CLI Examples:
.. code-block:: bash
salt '*' nova.image_list
salt '*' nova.image_list myimage
'''
conn = _auth(profile, **kwargs)
return conn.image_list(name) | python | def image_list(name=None, profile=None, **kwargs):
'''
Return a list of available images (nova images-list + nova image-show)
If a name is provided, only that image will be displayed.
CLI Examples:
.. code-block:: bash
salt '*' nova.image_list
salt '*' nova.image_list myimage
'''
conn = _auth(profile, **kwargs)
return conn.image_list(name) | [
"def",
"image_list",
"(",
"name",
"=",
"None",
",",
"profile",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"conn",
"=",
"_auth",
"(",
"profile",
",",
"*",
"*",
"kwargs",
")",
"return",
"conn",
".",
"image_list",
"(",
"name",
")"
] | Return a list of available images (nova images-list + nova image-show)
If a name is provided, only that image will be displayed.
CLI Examples:
.. code-block:: bash
salt '*' nova.image_list
salt '*' nova.image_list myimage | [
"Return",
"a",
"list",
"of",
"available",
"images",
"(",
"nova",
"images",
"-",
"list",
"+",
"nova",
"image",
"-",
"show",
")",
"If",
"a",
"name",
"is",
"provided",
"only",
"that",
"image",
"will",
"be",
"displayed",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nova.py#L643-L656 | train |
saltstack/salt | salt/modules/nova.py | image_meta_set | def image_meta_set(image_id=None,
name=None,
profile=None,
**kwargs): # pylint: disable=C0103
'''
Sets a key=value pair in the metadata for an image (nova image-meta set)
CLI Examples:
.. code-block:: bash
salt '*' nova.image_meta_set 6f52b2ff-0b31-4d84-8fd1-af45b84824f6 cheese=gruyere
salt '*' nova.image_meta_set name=myimage salad=pasta beans=baked
'''
conn = _auth(profile, **kwargs)
return conn.image_meta_set(
image_id,
name,
**kwargs
) | python | def image_meta_set(image_id=None,
name=None,
profile=None,
**kwargs): # pylint: disable=C0103
'''
Sets a key=value pair in the metadata for an image (nova image-meta set)
CLI Examples:
.. code-block:: bash
salt '*' nova.image_meta_set 6f52b2ff-0b31-4d84-8fd1-af45b84824f6 cheese=gruyere
salt '*' nova.image_meta_set name=myimage salad=pasta beans=baked
'''
conn = _auth(profile, **kwargs)
return conn.image_meta_set(
image_id,
name,
**kwargs
) | [
"def",
"image_meta_set",
"(",
"image_id",
"=",
"None",
",",
"name",
"=",
"None",
",",
"profile",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=C0103",
"conn",
"=",
"_auth",
"(",
"profile",
",",
"*",
"*",
"kwargs",
")",
"return",
"c... | Sets a key=value pair in the metadata for an image (nova image-meta set)
CLI Examples:
.. code-block:: bash
salt '*' nova.image_meta_set 6f52b2ff-0b31-4d84-8fd1-af45b84824f6 cheese=gruyere
salt '*' nova.image_meta_set name=myimage salad=pasta beans=baked | [
"Sets",
"a",
"key",
"=",
"value",
"pair",
"in",
"the",
"metadata",
"for",
"an",
"image",
"(",
"nova",
"image",
"-",
"meta",
"set",
")"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nova.py#L659-L678 | train |
saltstack/salt | salt/modules/nova.py | image_meta_delete | def image_meta_delete(image_id=None, # pylint: disable=C0103
name=None,
keys=None,
profile=None, **kwargs):
'''
Delete a key=value pair from the metadata for an image
(nova image-meta set)
CLI Examples:
.. code-block:: bash
salt '*' nova.image_meta_delete 6f52b2ff-0b31-4d84-8fd1-af45b84824f6 keys=cheese
salt '*' nova.image_meta_delete name=myimage keys=salad,beans
'''
conn = _auth(profile, **kwargs)
return conn.image_meta_delete(
image_id,
name,
keys
) | python | def image_meta_delete(image_id=None, # pylint: disable=C0103
name=None,
keys=None,
profile=None, **kwargs):
'''
Delete a key=value pair from the metadata for an image
(nova image-meta set)
CLI Examples:
.. code-block:: bash
salt '*' nova.image_meta_delete 6f52b2ff-0b31-4d84-8fd1-af45b84824f6 keys=cheese
salt '*' nova.image_meta_delete name=myimage keys=salad,beans
'''
conn = _auth(profile, **kwargs)
return conn.image_meta_delete(
image_id,
name,
keys
) | [
"def",
"image_meta_delete",
"(",
"image_id",
"=",
"None",
",",
"# pylint: disable=C0103",
"name",
"=",
"None",
",",
"keys",
"=",
"None",
",",
"profile",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"conn",
"=",
"_auth",
"(",
"profile",
",",
"*",
"*"... | Delete a key=value pair from the metadata for an image
(nova image-meta set)
CLI Examples:
.. code-block:: bash
salt '*' nova.image_meta_delete 6f52b2ff-0b31-4d84-8fd1-af45b84824f6 keys=cheese
salt '*' nova.image_meta_delete name=myimage keys=salad,beans | [
"Delete",
"a",
"key",
"=",
"value",
"pair",
"from",
"the",
"metadata",
"for",
"an",
"image",
"(",
"nova",
"image",
"-",
"meta",
"set",
")"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nova.py#L681-L701 | train |
saltstack/salt | salt/modules/nova.py | server_show | def server_show(server_id, profile=None, **kwargs):
'''
Return detailed information for an active server
CLI Example:
.. code-block:: bash
salt '*' nova.server_show <server_id>
'''
conn = _auth(profile, **kwargs)
return conn.server_show(server_id) | python | def server_show(server_id, profile=None, **kwargs):
'''
Return detailed information for an active server
CLI Example:
.. code-block:: bash
salt '*' nova.server_show <server_id>
'''
conn = _auth(profile, **kwargs)
return conn.server_show(server_id) | [
"def",
"server_show",
"(",
"server_id",
",",
"profile",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"conn",
"=",
"_auth",
"(",
"profile",
",",
"*",
"*",
"kwargs",
")",
"return",
"conn",
".",
"server_show",
"(",
"server_id",
")"
] | Return detailed information for an active server
CLI Example:
.. code-block:: bash
salt '*' nova.server_show <server_id> | [
"Return",
"detailed",
"information",
"for",
"an",
"active",
"server"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nova.py#L760-L771 | train |
saltstack/salt | salt/modules/nova.py | secgroup_create | def secgroup_create(name, description, profile=None, **kwargs):
'''
Add a secgroup to nova (nova secgroup-create)
CLI Example:
.. code-block:: bash
salt '*' nova.secgroup_create mygroup 'This is my security group'
'''
conn = _auth(profile, **kwargs)
return conn.secgroup_create(name, description) | python | def secgroup_create(name, description, profile=None, **kwargs):
'''
Add a secgroup to nova (nova secgroup-create)
CLI Example:
.. code-block:: bash
salt '*' nova.secgroup_create mygroup 'This is my security group'
'''
conn = _auth(profile, **kwargs)
return conn.secgroup_create(name, description) | [
"def",
"secgroup_create",
"(",
"name",
",",
"description",
",",
"profile",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"conn",
"=",
"_auth",
"(",
"profile",
",",
"*",
"*",
"kwargs",
")",
"return",
"conn",
".",
"secgroup_create",
"(",
"name",
",",
... | Add a secgroup to nova (nova secgroup-create)
CLI Example:
.. code-block:: bash
salt '*' nova.secgroup_create mygroup 'This is my security group' | [
"Add",
"a",
"secgroup",
"to",
"nova",
"(",
"nova",
"secgroup",
"-",
"create",
")"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nova.py#L774-L785 | train |
saltstack/salt | salt/modules/nova.py | secgroup_delete | def secgroup_delete(name, profile=None, **kwargs):
'''
Delete a secgroup to nova (nova secgroup-delete)
CLI Example:
.. code-block:: bash
salt '*' nova.secgroup_delete mygroup
'''
conn = _auth(profile, **kwargs)
return conn.secgroup_delete(name) | python | def secgroup_delete(name, profile=None, **kwargs):
'''
Delete a secgroup to nova (nova secgroup-delete)
CLI Example:
.. code-block:: bash
salt '*' nova.secgroup_delete mygroup
'''
conn = _auth(profile, **kwargs)
return conn.secgroup_delete(name) | [
"def",
"secgroup_delete",
"(",
"name",
",",
"profile",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"conn",
"=",
"_auth",
"(",
"profile",
",",
"*",
"*",
"kwargs",
")",
"return",
"conn",
".",
"secgroup_delete",
"(",
"name",
")"
] | Delete a secgroup to nova (nova secgroup-delete)
CLI Example:
.. code-block:: bash
salt '*' nova.secgroup_delete mygroup | [
"Delete",
"a",
"secgroup",
"to",
"nova",
"(",
"nova",
"secgroup",
"-",
"delete",
")"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nova.py#L788-L799 | train |
saltstack/salt | salt/modules/nova.py | server_by_name | def server_by_name(name, profile=None, **kwargs):
'''
Return information about a server
name
Server Name
CLI Example:
.. code-block:: bash
salt '*' nova.server_by_name myserver profile=openstack
'''
conn = _auth(profile, **kwargs)
return conn.server_by_name(name) | python | def server_by_name(name, profile=None, **kwargs):
'''
Return information about a server
name
Server Name
CLI Example:
.. code-block:: bash
salt '*' nova.server_by_name myserver profile=openstack
'''
conn = _auth(profile, **kwargs)
return conn.server_by_name(name) | [
"def",
"server_by_name",
"(",
"name",
",",
"profile",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"conn",
"=",
"_auth",
"(",
"profile",
",",
"*",
"*",
"kwargs",
")",
"return",
"conn",
".",
"server_by_name",
"(",
"name",
")"
] | Return information about a server
name
Server Name
CLI Example:
.. code-block:: bash
salt '*' nova.server_by_name myserver profile=openstack | [
"Return",
"information",
"about",
"a",
"server"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nova.py#L816-L830 | train |
saltstack/salt | salt/modules/napalm_yang_mod.py | _get_root_object | def _get_root_object(models):
'''
Read list of models and returns a Root object with the proper models added.
'''
root = napalm_yang.base.Root()
for model in models:
current = napalm_yang
for part in model.split('.'):
current = getattr(current, part)
root.add_model(current)
return root | python | def _get_root_object(models):
'''
Read list of models and returns a Root object with the proper models added.
'''
root = napalm_yang.base.Root()
for model in models:
current = napalm_yang
for part in model.split('.'):
current = getattr(current, part)
root.add_model(current)
return root | [
"def",
"_get_root_object",
"(",
"models",
")",
":",
"root",
"=",
"napalm_yang",
".",
"base",
".",
"Root",
"(",
")",
"for",
"model",
"in",
"models",
":",
"current",
"=",
"napalm_yang",
"for",
"part",
"in",
"model",
".",
"split",
"(",
"'.'",
")",
":",
... | Read list of models and returns a Root object with the proper models added. | [
"Read",
"list",
"of",
"models",
"and",
"returns",
"a",
"Root",
"object",
"with",
"the",
"proper",
"models",
"added",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_yang_mod.py#L55-L65 | train |
saltstack/salt | salt/modules/napalm_yang_mod.py | diff | def diff(candidate, running, *models):
'''
Returns the difference between two configuration entities structured
according to the YANG model.
.. note::
This function is recommended to be used mostly as a state helper.
candidate
First model to compare.
running
Second model to compare.
models
A list of models to be used when comparing.
CLI Example:
.. code-block:: bash
salt '*' napalm_yang.diff {} {} models.openconfig_interfaces
Output Example:
.. code-block:: python
{
"interfaces": {
"interface": {
"both": {
"Port-Channel1": {
"config": {
"mtu": {
"first": "0",
"second": "9000"
}
}
}
},
"first_only": [
"Loopback0"
],
"second_only": [
"Loopback1"
]
}
}
}
'''
if isinstance(models, tuple) and isinstance(models[0], list):
models = models[0]
first = _get_root_object(models)
first.load_dict(candidate)
second = _get_root_object(models)
second.load_dict(running)
return napalm_yang.utils.diff(first, second) | python | def diff(candidate, running, *models):
'''
Returns the difference between two configuration entities structured
according to the YANG model.
.. note::
This function is recommended to be used mostly as a state helper.
candidate
First model to compare.
running
Second model to compare.
models
A list of models to be used when comparing.
CLI Example:
.. code-block:: bash
salt '*' napalm_yang.diff {} {} models.openconfig_interfaces
Output Example:
.. code-block:: python
{
"interfaces": {
"interface": {
"both": {
"Port-Channel1": {
"config": {
"mtu": {
"first": "0",
"second": "9000"
}
}
}
},
"first_only": [
"Loopback0"
],
"second_only": [
"Loopback1"
]
}
}
}
'''
if isinstance(models, tuple) and isinstance(models[0], list):
models = models[0]
first = _get_root_object(models)
first.load_dict(candidate)
second = _get_root_object(models)
second.load_dict(running)
return napalm_yang.utils.diff(first, second) | [
"def",
"diff",
"(",
"candidate",
",",
"running",
",",
"*",
"models",
")",
":",
"if",
"isinstance",
"(",
"models",
",",
"tuple",
")",
"and",
"isinstance",
"(",
"models",
"[",
"0",
"]",
",",
"list",
")",
":",
"models",
"=",
"models",
"[",
"0",
"]",
... | Returns the difference between two configuration entities structured
according to the YANG model.
.. note::
This function is recommended to be used mostly as a state helper.
candidate
First model to compare.
running
Second model to compare.
models
A list of models to be used when comparing.
CLI Example:
.. code-block:: bash
salt '*' napalm_yang.diff {} {} models.openconfig_interfaces
Output Example:
.. code-block:: python
{
"interfaces": {
"interface": {
"both": {
"Port-Channel1": {
"config": {
"mtu": {
"first": "0",
"second": "9000"
}
}
}
},
"first_only": [
"Loopback0"
],
"second_only": [
"Loopback1"
]
}
}
} | [
"Returns",
"the",
"difference",
"between",
"two",
"configuration",
"entities",
"structured",
"according",
"to",
"the",
"YANG",
"model",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_yang_mod.py#L72-L129 | train |
saltstack/salt | salt/modules/napalm_yang_mod.py | parse | def parse(*models, **kwargs):
'''
Parse configuration from the device.
models
A list of models to be used when parsing.
config: ``False``
Parse config.
state: ``False``
Parse state.
profiles: ``None``
Use certain profiles to parse. If not specified, will use the device
default profile(s).
CLI Example:
.. code-block:: bash
salt '*' napalm_yang.parse models.openconfig_interfaces
Output Example:
.. code-block:: python
{
"interfaces": {
"interface": {
".local.": {
"name": ".local.",
"state": {
"admin-status": "UP",
"counters": {
"in-discards": 0,
"in-errors": 0,
"out-errors": 0
},
"enabled": True,
"ifindex": 0,
"last-change": 0,
"oper-status": "UP",
"type": "softwareLoopback"
},
"subinterfaces": {
"subinterface": {
".local..0": {
"index": ".local..0",
"state": {
"ifindex": 0,
"name": ".local..0"
}
}
}
}
},
"ae0": {
"name": "ae0",
"state": {
"admin-status": "UP",
"counters": {
"in-discards": 0,
"in-errors": 0,
"out-errors": 0
},
"enabled": True,
"ifindex": 531,
"last-change": 255203,
"mtu": 1518,
"oper-status": "DOWN"
},
"subinterfaces": {
"subinterface": {
"ae0.0": {
"index": "ae0.0",
"state": {
"description": "ASDASDASD",
"ifindex": 532,
"name": "ae0.0"
}
}
"ae0.32767": {
"index": "ae0.32767",
"state": {
"ifindex": 535,
"name": "ae0.32767"
}
}
}
}
},
"dsc": {
"name": "dsc",
"state": {
"admin-status": "UP",
"counters": {
"in-discards": 0,
"in-errors": 0,
"out-errors": 0
},
"enabled": True,
"ifindex": 5,
"last-change": 0,
"oper-status": "UP"
}
},
"ge-0/0/0": {
"name": "ge-0/0/0",
"state": {
"admin-status": "UP",
"counters": {
"in-broadcast-pkts": 0,
"in-discards": 0,
"in-errors": 0,
"in-multicast-pkts": 0,
"in-unicast-pkts": 16877,
"out-broadcast-pkts": 0,
"out-errors": 0,
"out-multicast-pkts": 0,
"out-unicast-pkts": 15742
},
"description": "management interface",
"enabled": True,
"ifindex": 507,
"last-change": 258467,
"mtu": 1400,
"oper-status": "UP"
},
"subinterfaces": {
"subinterface": {
"ge-0/0/0.0": {
"index": "ge-0/0/0.0",
"state": {
"description": "ge-0/0/0.0",
"ifindex": 521,
"name": "ge-0/0/0.0"
}
}
}
}
}
"irb": {
"name": "irb",
"state": {
"admin-status": "UP",
"counters": {
"in-discards": 0,
"in-errors": 0,
"out-errors": 0
},
"enabled": True,
"ifindex": 502,
"last-change": 0,
"mtu": 1514,
"oper-status": "UP",
"type": "ethernetCsmacd"
}
},
"lo0": {
"name": "lo0",
"state": {
"admin-status": "UP",
"counters": {
"in-discards": 0,
"in-errors": 0,
"out-errors": 0
},
"description": "lo0",
"enabled": True,
"ifindex": 6,
"last-change": 0,
"oper-status": "UP",
"type": "softwareLoopback"
},
"subinterfaces": {
"subinterface": {
"lo0.0": {
"index": "lo0.0",
"state": {
"description": "lo0.0",
"ifindex": 16,
"name": "lo0.0"
}
},
"lo0.16384": {
"index": "lo0.16384",
"state": {
"ifindex": 21,
"name": "lo0.16384"
}
},
"lo0.16385": {
"index": "lo0.16385",
"state": {
"ifindex": 22,
"name": "lo0.16385"
}
},
"lo0.32768": {
"index": "lo0.32768",
"state": {
"ifindex": 248,
"name": "lo0.32768"
}
}
}
}
}
}
}
}
'''
if isinstance(models, tuple) and isinstance(models[0], list):
models = models[0]
config = kwargs.pop('config', False)
state = kwargs.pop('state', False)
profiles = kwargs.pop('profiles', [])
if not profiles and hasattr(napalm_device, 'profile'): # pylint: disable=undefined-variable
profiles = napalm_device.profile # pylint: disable=undefined-variable
if not profiles:
profiles = [__grains__.get('os')]
root = _get_root_object(models)
parser_kwargs = {
'device': napalm_device.get('DRIVER'), # pylint: disable=undefined-variable
'profile': profiles
}
if config:
root.parse_config(**parser_kwargs)
if state:
root.parse_state(**parser_kwargs)
return root.to_dict(filter=True) | python | def parse(*models, **kwargs):
'''
Parse configuration from the device.
models
A list of models to be used when parsing.
config: ``False``
Parse config.
state: ``False``
Parse state.
profiles: ``None``
Use certain profiles to parse. If not specified, will use the device
default profile(s).
CLI Example:
.. code-block:: bash
salt '*' napalm_yang.parse models.openconfig_interfaces
Output Example:
.. code-block:: python
{
"interfaces": {
"interface": {
".local.": {
"name": ".local.",
"state": {
"admin-status": "UP",
"counters": {
"in-discards": 0,
"in-errors": 0,
"out-errors": 0
},
"enabled": True,
"ifindex": 0,
"last-change": 0,
"oper-status": "UP",
"type": "softwareLoopback"
},
"subinterfaces": {
"subinterface": {
".local..0": {
"index": ".local..0",
"state": {
"ifindex": 0,
"name": ".local..0"
}
}
}
}
},
"ae0": {
"name": "ae0",
"state": {
"admin-status": "UP",
"counters": {
"in-discards": 0,
"in-errors": 0,
"out-errors": 0
},
"enabled": True,
"ifindex": 531,
"last-change": 255203,
"mtu": 1518,
"oper-status": "DOWN"
},
"subinterfaces": {
"subinterface": {
"ae0.0": {
"index": "ae0.0",
"state": {
"description": "ASDASDASD",
"ifindex": 532,
"name": "ae0.0"
}
}
"ae0.32767": {
"index": "ae0.32767",
"state": {
"ifindex": 535,
"name": "ae0.32767"
}
}
}
}
},
"dsc": {
"name": "dsc",
"state": {
"admin-status": "UP",
"counters": {
"in-discards": 0,
"in-errors": 0,
"out-errors": 0
},
"enabled": True,
"ifindex": 5,
"last-change": 0,
"oper-status": "UP"
}
},
"ge-0/0/0": {
"name": "ge-0/0/0",
"state": {
"admin-status": "UP",
"counters": {
"in-broadcast-pkts": 0,
"in-discards": 0,
"in-errors": 0,
"in-multicast-pkts": 0,
"in-unicast-pkts": 16877,
"out-broadcast-pkts": 0,
"out-errors": 0,
"out-multicast-pkts": 0,
"out-unicast-pkts": 15742
},
"description": "management interface",
"enabled": True,
"ifindex": 507,
"last-change": 258467,
"mtu": 1400,
"oper-status": "UP"
},
"subinterfaces": {
"subinterface": {
"ge-0/0/0.0": {
"index": "ge-0/0/0.0",
"state": {
"description": "ge-0/0/0.0",
"ifindex": 521,
"name": "ge-0/0/0.0"
}
}
}
}
}
"irb": {
"name": "irb",
"state": {
"admin-status": "UP",
"counters": {
"in-discards": 0,
"in-errors": 0,
"out-errors": 0
},
"enabled": True,
"ifindex": 502,
"last-change": 0,
"mtu": 1514,
"oper-status": "UP",
"type": "ethernetCsmacd"
}
},
"lo0": {
"name": "lo0",
"state": {
"admin-status": "UP",
"counters": {
"in-discards": 0,
"in-errors": 0,
"out-errors": 0
},
"description": "lo0",
"enabled": True,
"ifindex": 6,
"last-change": 0,
"oper-status": "UP",
"type": "softwareLoopback"
},
"subinterfaces": {
"subinterface": {
"lo0.0": {
"index": "lo0.0",
"state": {
"description": "lo0.0",
"ifindex": 16,
"name": "lo0.0"
}
},
"lo0.16384": {
"index": "lo0.16384",
"state": {
"ifindex": 21,
"name": "lo0.16384"
}
},
"lo0.16385": {
"index": "lo0.16385",
"state": {
"ifindex": 22,
"name": "lo0.16385"
}
},
"lo0.32768": {
"index": "lo0.32768",
"state": {
"ifindex": 248,
"name": "lo0.32768"
}
}
}
}
}
}
}
}
'''
if isinstance(models, tuple) and isinstance(models[0], list):
models = models[0]
config = kwargs.pop('config', False)
state = kwargs.pop('state', False)
profiles = kwargs.pop('profiles', [])
if not profiles and hasattr(napalm_device, 'profile'): # pylint: disable=undefined-variable
profiles = napalm_device.profile # pylint: disable=undefined-variable
if not profiles:
profiles = [__grains__.get('os')]
root = _get_root_object(models)
parser_kwargs = {
'device': napalm_device.get('DRIVER'), # pylint: disable=undefined-variable
'profile': profiles
}
if config:
root.parse_config(**parser_kwargs)
if state:
root.parse_state(**parser_kwargs)
return root.to_dict(filter=True) | [
"def",
"parse",
"(",
"*",
"models",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"models",
",",
"tuple",
")",
"and",
"isinstance",
"(",
"models",
"[",
"0",
"]",
",",
"list",
")",
":",
"models",
"=",
"models",
"[",
"0",
"]",
"config... | Parse configuration from the device.
models
A list of models to be used when parsing.
config: ``False``
Parse config.
state: ``False``
Parse state.
profiles: ``None``
Use certain profiles to parse. If not specified, will use the device
default profile(s).
CLI Example:
.. code-block:: bash
salt '*' napalm_yang.parse models.openconfig_interfaces
Output Example:
.. code-block:: python
{
"interfaces": {
"interface": {
".local.": {
"name": ".local.",
"state": {
"admin-status": "UP",
"counters": {
"in-discards": 0,
"in-errors": 0,
"out-errors": 0
},
"enabled": True,
"ifindex": 0,
"last-change": 0,
"oper-status": "UP",
"type": "softwareLoopback"
},
"subinterfaces": {
"subinterface": {
".local..0": {
"index": ".local..0",
"state": {
"ifindex": 0,
"name": ".local..0"
}
}
}
}
},
"ae0": {
"name": "ae0",
"state": {
"admin-status": "UP",
"counters": {
"in-discards": 0,
"in-errors": 0,
"out-errors": 0
},
"enabled": True,
"ifindex": 531,
"last-change": 255203,
"mtu": 1518,
"oper-status": "DOWN"
},
"subinterfaces": {
"subinterface": {
"ae0.0": {
"index": "ae0.0",
"state": {
"description": "ASDASDASD",
"ifindex": 532,
"name": "ae0.0"
}
}
"ae0.32767": {
"index": "ae0.32767",
"state": {
"ifindex": 535,
"name": "ae0.32767"
}
}
}
}
},
"dsc": {
"name": "dsc",
"state": {
"admin-status": "UP",
"counters": {
"in-discards": 0,
"in-errors": 0,
"out-errors": 0
},
"enabled": True,
"ifindex": 5,
"last-change": 0,
"oper-status": "UP"
}
},
"ge-0/0/0": {
"name": "ge-0/0/0",
"state": {
"admin-status": "UP",
"counters": {
"in-broadcast-pkts": 0,
"in-discards": 0,
"in-errors": 0,
"in-multicast-pkts": 0,
"in-unicast-pkts": 16877,
"out-broadcast-pkts": 0,
"out-errors": 0,
"out-multicast-pkts": 0,
"out-unicast-pkts": 15742
},
"description": "management interface",
"enabled": True,
"ifindex": 507,
"last-change": 258467,
"mtu": 1400,
"oper-status": "UP"
},
"subinterfaces": {
"subinterface": {
"ge-0/0/0.0": {
"index": "ge-0/0/0.0",
"state": {
"description": "ge-0/0/0.0",
"ifindex": 521,
"name": "ge-0/0/0.0"
}
}
}
}
}
"irb": {
"name": "irb",
"state": {
"admin-status": "UP",
"counters": {
"in-discards": 0,
"in-errors": 0,
"out-errors": 0
},
"enabled": True,
"ifindex": 502,
"last-change": 0,
"mtu": 1514,
"oper-status": "UP",
"type": "ethernetCsmacd"
}
},
"lo0": {
"name": "lo0",
"state": {
"admin-status": "UP",
"counters": {
"in-discards": 0,
"in-errors": 0,
"out-errors": 0
},
"description": "lo0",
"enabled": True,
"ifindex": 6,
"last-change": 0,
"oper-status": "UP",
"type": "softwareLoopback"
},
"subinterfaces": {
"subinterface": {
"lo0.0": {
"index": "lo0.0",
"state": {
"description": "lo0.0",
"ifindex": 16,
"name": "lo0.0"
}
},
"lo0.16384": {
"index": "lo0.16384",
"state": {
"ifindex": 21,
"name": "lo0.16384"
}
},
"lo0.16385": {
"index": "lo0.16385",
"state": {
"ifindex": 22,
"name": "lo0.16385"
}
},
"lo0.32768": {
"index": "lo0.32768",
"state": {
"ifindex": 248,
"name": "lo0.32768"
}
}
}
}
}
}
}
} | [
"Parse",
"configuration",
"from",
"the",
"device",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_yang_mod.py#L133-L364 | train |
saltstack/salt | salt/modules/napalm_yang_mod.py | get_config | def get_config(data, *models, **kwargs):
'''
Return the native config.
data
Dictionary structured with respect to the models referenced.
models
A list of models to be used when generating the config.
profiles: ``None``
Use certain profiles to generate the config.
If not specified, will use the platform default profile(s).
CLI Example:
.. code-block:: bash
salt '*' napalm_yang.get_config {} models.openconfig_interfaces
Output Example:
.. code-block:: text
interface et1
ip address 192.168.1.1/24
description Uplink1
mtu 9000
interface et2
ip address 192.168.2.1/24
description Uplink2
mtu 9000
'''
if isinstance(models, tuple) and isinstance(models[0], list):
models = models[0]
profiles = kwargs.pop('profiles', [])
if not profiles and hasattr(napalm_device, 'profile'): # pylint: disable=undefined-variable
profiles = napalm_device.profile # pylint: disable=undefined-variable
if not profiles:
profiles = [__grains__.get('os')]
parser_kwargs = {
'profile': profiles
}
root = _get_root_object(models)
root.load_dict(data)
native_config = root.translate_config(**parser_kwargs)
log.debug('Generated config')
log.debug(native_config)
return native_config | python | def get_config(data, *models, **kwargs):
'''
Return the native config.
data
Dictionary structured with respect to the models referenced.
models
A list of models to be used when generating the config.
profiles: ``None``
Use certain profiles to generate the config.
If not specified, will use the platform default profile(s).
CLI Example:
.. code-block:: bash
salt '*' napalm_yang.get_config {} models.openconfig_interfaces
Output Example:
.. code-block:: text
interface et1
ip address 192.168.1.1/24
description Uplink1
mtu 9000
interface et2
ip address 192.168.2.1/24
description Uplink2
mtu 9000
'''
if isinstance(models, tuple) and isinstance(models[0], list):
models = models[0]
profiles = kwargs.pop('profiles', [])
if not profiles and hasattr(napalm_device, 'profile'): # pylint: disable=undefined-variable
profiles = napalm_device.profile # pylint: disable=undefined-variable
if not profiles:
profiles = [__grains__.get('os')]
parser_kwargs = {
'profile': profiles
}
root = _get_root_object(models)
root.load_dict(data)
native_config = root.translate_config(**parser_kwargs)
log.debug('Generated config')
log.debug(native_config)
return native_config | [
"def",
"get_config",
"(",
"data",
",",
"*",
"models",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"models",
",",
"tuple",
")",
"and",
"isinstance",
"(",
"models",
"[",
"0",
"]",
",",
"list",
")",
":",
"models",
"=",
"models",
"[",
... | Return the native config.
data
Dictionary structured with respect to the models referenced.
models
A list of models to be used when generating the config.
profiles: ``None``
Use certain profiles to generate the config.
If not specified, will use the platform default profile(s).
CLI Example:
.. code-block:: bash
salt '*' napalm_yang.get_config {} models.openconfig_interfaces
Output Example:
.. code-block:: text
interface et1
ip address 192.168.1.1/24
description Uplink1
mtu 9000
interface et2
ip address 192.168.2.1/24
description Uplink2
mtu 9000 | [
"Return",
"the",
"native",
"config",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_yang_mod.py#L368-L416 | train |
saltstack/salt | salt/modules/napalm_yang_mod.py | load_config | def load_config(data, *models, **kwargs):
'''
Generate and load the config on the device using the OpenConfig or IETF
models and device profiles.
data
Dictionary structured with respect to the models referenced.
models
A list of models to be used when generating the config.
profiles: ``None``
Use certain profiles to generate the config.
If not specified, will use the platform default profile(s).
test: ``False``
Dry run? If set as ``True``, will apply the config, discard
and return the changes. Default: ``False`` and will commit
the changes on the device.
commit: ``True``
Commit? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key under the output dictionary,
as ``loaded_config`` containing the raw configuration loaded on the device.
replace: ``False``
Should replace the config with the new generate one?
CLI Example:
.. code-block:: bash
salt '*' napalm_yang.load_config {} models.openconfig_interfaces test=True debug=True
Output Example:
.. code-block:: jinja
device1:
----------
already_configured:
False
comment:
diff:
[edit interfaces ge-0/0/0]
- mtu 1400;
[edit interfaces ge-0/0/0 unit 0 family inet]
- dhcp;
[edit interfaces lo0]
- unit 0 {
- description lo0.0;
- }
+ unit 1 {
+ description "new loopback";
+ }
loaded_config:
<configuration>
<interfaces replace="replace">
<interface>
<name>ge-0/0/0</name>
<unit>
<name>0</name>
<family>
<inet/>
</family>
<description>ge-0/0/0.0</description>
</unit>
<description>management interface</description>
</interface>
<interface>
<name>ge-0/0/1</name>
<disable/>
<description>ge-0/0/1</description>
</interface>
<interface>
<name>ae0</name>
<unit>
<name>0</name>
<vlan-id>100</vlan-id>
<family>
<inet>
<address>
<name>192.168.100.1/24</name>
</address>
<address>
<name>172.20.100.1/24</name>
</address>
</inet>
</family>
<description>a description</description>
</unit>
<vlan-tagging/>
<unit>
<name>1</name>
<vlan-id>1</vlan-id>
<family>
<inet>
<address>
<name>192.168.101.1/24</name>
</address>
</inet>
</family>
<disable/>
<description>ae0.1</description>
</unit>
<vlan-tagging/>
<unit>
<name>2</name>
<vlan-id>2</vlan-id>
<family>
<inet>
<address>
<name>192.168.102.1/24</name>
</address>
</inet>
</family>
<description>ae0.2</description>
</unit>
<vlan-tagging/>
</interface>
<interface>
<name>lo0</name>
<unit>
<name>1</name>
<description>new loopback</description>
</unit>
<description>lo0</description>
</interface>
</interfaces>
</configuration>
result:
True
'''
if isinstance(models, tuple) and isinstance(models[0], list):
models = models[0]
config = get_config(data, *models, **kwargs)
test = kwargs.pop('test', False)
debug = kwargs.pop('debug', False)
commit = kwargs.pop('commit', True)
replace = kwargs.pop('replace', False)
return __salt__['net.load_config'](text=config,
test=test,
debug=debug,
commit=commit,
replace=replace,
inherit_napalm_device=napalm_device) | python | def load_config(data, *models, **kwargs):
'''
Generate and load the config on the device using the OpenConfig or IETF
models and device profiles.
data
Dictionary structured with respect to the models referenced.
models
A list of models to be used when generating the config.
profiles: ``None``
Use certain profiles to generate the config.
If not specified, will use the platform default profile(s).
test: ``False``
Dry run? If set as ``True``, will apply the config, discard
and return the changes. Default: ``False`` and will commit
the changes on the device.
commit: ``True``
Commit? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key under the output dictionary,
as ``loaded_config`` containing the raw configuration loaded on the device.
replace: ``False``
Should replace the config with the new generate one?
CLI Example:
.. code-block:: bash
salt '*' napalm_yang.load_config {} models.openconfig_interfaces test=True debug=True
Output Example:
.. code-block:: jinja
device1:
----------
already_configured:
False
comment:
diff:
[edit interfaces ge-0/0/0]
- mtu 1400;
[edit interfaces ge-0/0/0 unit 0 family inet]
- dhcp;
[edit interfaces lo0]
- unit 0 {
- description lo0.0;
- }
+ unit 1 {
+ description "new loopback";
+ }
loaded_config:
<configuration>
<interfaces replace="replace">
<interface>
<name>ge-0/0/0</name>
<unit>
<name>0</name>
<family>
<inet/>
</family>
<description>ge-0/0/0.0</description>
</unit>
<description>management interface</description>
</interface>
<interface>
<name>ge-0/0/1</name>
<disable/>
<description>ge-0/0/1</description>
</interface>
<interface>
<name>ae0</name>
<unit>
<name>0</name>
<vlan-id>100</vlan-id>
<family>
<inet>
<address>
<name>192.168.100.1/24</name>
</address>
<address>
<name>172.20.100.1/24</name>
</address>
</inet>
</family>
<description>a description</description>
</unit>
<vlan-tagging/>
<unit>
<name>1</name>
<vlan-id>1</vlan-id>
<family>
<inet>
<address>
<name>192.168.101.1/24</name>
</address>
</inet>
</family>
<disable/>
<description>ae0.1</description>
</unit>
<vlan-tagging/>
<unit>
<name>2</name>
<vlan-id>2</vlan-id>
<family>
<inet>
<address>
<name>192.168.102.1/24</name>
</address>
</inet>
</family>
<description>ae0.2</description>
</unit>
<vlan-tagging/>
</interface>
<interface>
<name>lo0</name>
<unit>
<name>1</name>
<description>new loopback</description>
</unit>
<description>lo0</description>
</interface>
</interfaces>
</configuration>
result:
True
'''
if isinstance(models, tuple) and isinstance(models[0], list):
models = models[0]
config = get_config(data, *models, **kwargs)
test = kwargs.pop('test', False)
debug = kwargs.pop('debug', False)
commit = kwargs.pop('commit', True)
replace = kwargs.pop('replace', False)
return __salt__['net.load_config'](text=config,
test=test,
debug=debug,
commit=commit,
replace=replace,
inherit_napalm_device=napalm_device) | [
"def",
"load_config",
"(",
"data",
",",
"*",
"models",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"models",
",",
"tuple",
")",
"and",
"isinstance",
"(",
"models",
"[",
"0",
"]",
",",
"list",
")",
":",
"models",
"=",
"models",
"[",
... | Generate and load the config on the device using the OpenConfig or IETF
models and device profiles.
data
Dictionary structured with respect to the models referenced.
models
A list of models to be used when generating the config.
profiles: ``None``
Use certain profiles to generate the config.
If not specified, will use the platform default profile(s).
test: ``False``
Dry run? If set as ``True``, will apply the config, discard
and return the changes. Default: ``False`` and will commit
the changes on the device.
commit: ``True``
Commit? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key under the output dictionary,
as ``loaded_config`` containing the raw configuration loaded on the device.
replace: ``False``
Should replace the config with the new generate one?
CLI Example:
.. code-block:: bash
salt '*' napalm_yang.load_config {} models.openconfig_interfaces test=True debug=True
Output Example:
.. code-block:: jinja
device1:
----------
already_configured:
False
comment:
diff:
[edit interfaces ge-0/0/0]
- mtu 1400;
[edit interfaces ge-0/0/0 unit 0 family inet]
- dhcp;
[edit interfaces lo0]
- unit 0 {
- description lo0.0;
- }
+ unit 1 {
+ description "new loopback";
+ }
loaded_config:
<configuration>
<interfaces replace="replace">
<interface>
<name>ge-0/0/0</name>
<unit>
<name>0</name>
<family>
<inet/>
</family>
<description>ge-0/0/0.0</description>
</unit>
<description>management interface</description>
</interface>
<interface>
<name>ge-0/0/1</name>
<disable/>
<description>ge-0/0/1</description>
</interface>
<interface>
<name>ae0</name>
<unit>
<name>0</name>
<vlan-id>100</vlan-id>
<family>
<inet>
<address>
<name>192.168.100.1/24</name>
</address>
<address>
<name>172.20.100.1/24</name>
</address>
</inet>
</family>
<description>a description</description>
</unit>
<vlan-tagging/>
<unit>
<name>1</name>
<vlan-id>1</vlan-id>
<family>
<inet>
<address>
<name>192.168.101.1/24</name>
</address>
</inet>
</family>
<disable/>
<description>ae0.1</description>
</unit>
<vlan-tagging/>
<unit>
<name>2</name>
<vlan-id>2</vlan-id>
<family>
<inet>
<address>
<name>192.168.102.1/24</name>
</address>
</inet>
</family>
<description>ae0.2</description>
</unit>
<vlan-tagging/>
</interface>
<interface>
<name>lo0</name>
<unit>
<name>1</name>
<description>new loopback</description>
</unit>
<description>lo0</description>
</interface>
</interfaces>
</configuration>
result:
True | [
"Generate",
"and",
"load",
"the",
"config",
"on",
"the",
"device",
"using",
"the",
"OpenConfig",
"or",
"IETF",
"models",
"and",
"device",
"profiles",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_yang_mod.py#L420-L567 | train |
saltstack/salt | salt/modules/napalm_yang_mod.py | compliance_report | def compliance_report(data, *models, **kwargs):
'''
Return the compliance report using YANG objects.
data
Dictionary structured with respect to the models referenced.
models
A list of models to be used when generating the config.
filepath
The absolute path to the validation file.
CLI Example:
.. code-block:: bash
salt '*' napalm_yang.compliance_report {} models.openconfig_interfaces filepath=~/validate.yml
Output Example:
.. code-block:: json
{
"skipped": [],
"complies": true,
"get_interfaces_ip": {
"missing": [],
"complies": true,
"present": {
"ge-0/0/0.0": {
"complies": true,
"nested": true
}
},
"extra": []
}
}
'''
if isinstance(models, tuple) and isinstance(models[0], list):
models = models[0]
filepath = kwargs.pop('filepath', '')
root = _get_root_object(models)
root.load_dict(data)
return root.compliance_report(filepath) | python | def compliance_report(data, *models, **kwargs):
'''
Return the compliance report using YANG objects.
data
Dictionary structured with respect to the models referenced.
models
A list of models to be used when generating the config.
filepath
The absolute path to the validation file.
CLI Example:
.. code-block:: bash
salt '*' napalm_yang.compliance_report {} models.openconfig_interfaces filepath=~/validate.yml
Output Example:
.. code-block:: json
{
"skipped": [],
"complies": true,
"get_interfaces_ip": {
"missing": [],
"complies": true,
"present": {
"ge-0/0/0.0": {
"complies": true,
"nested": true
}
},
"extra": []
}
}
'''
if isinstance(models, tuple) and isinstance(models[0], list):
models = models[0]
filepath = kwargs.pop('filepath', '')
root = _get_root_object(models)
root.load_dict(data)
return root.compliance_report(filepath) | [
"def",
"compliance_report",
"(",
"data",
",",
"*",
"models",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"models",
",",
"tuple",
")",
"and",
"isinstance",
"(",
"models",
"[",
"0",
"]",
",",
"list",
")",
":",
"models",
"=",
"models",
... | Return the compliance report using YANG objects.
data
Dictionary structured with respect to the models referenced.
models
A list of models to be used when generating the config.
filepath
The absolute path to the validation file.
CLI Example:
.. code-block:: bash
salt '*' napalm_yang.compliance_report {} models.openconfig_interfaces filepath=~/validate.yml
Output Example:
.. code-block:: json
{
"skipped": [],
"complies": true,
"get_interfaces_ip": {
"missing": [],
"complies": true,
"present": {
"ge-0/0/0.0": {
"complies": true,
"nested": true
}
},
"extra": []
}
} | [
"Return",
"the",
"compliance",
"report",
"using",
"YANG",
"objects",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_yang_mod.py#L571-L615 | train |
saltstack/salt | salt/states/cisconso.py | value_present | def value_present(name, datastore, path, config):
'''
Ensure a specific value exists at a given path
:param name: The name for this rule
:type name: ``str``
:param datastore: The datastore, e.g. running, operational.
One of the NETCONF store IETF types
:type datastore: :class:`DatastoreType` (``str`` enum).
:param path: The device path to set the value at,
a list of element names in order, / separated
:type path: ``list``, ``str`` OR ``tuple``
:param config: The new value at the given path
:type config: ``dict``
Examples:
.. code-block:: yaml
enable pap auth:
cisconso.config_present:
- name: enable_pap_auth
- datastore: running
- path: devices/device/ex0/config/sys/interfaces/serial/ppp0/authentication
- config:
authentication:
method: pap
"list-name": foobar
'''
ret = {'name': name,
'result': False,
'changes': {},
'comment': ''}
existing = __salt__['cisconso.get_data'](datastore, path)
if salt.utils.compat.cmp(existing, config):
ret['result'] = True
ret['comment'] = 'Config is already set'
elif __opts__['test'] is True:
ret['result'] = None
ret['comment'] = 'Config will be added'
diff = _DictDiffer(existing, config)
ret['changes']['new'] = diff.added()
ret['changes']['removed'] = diff.removed()
ret['changes']['changed'] = diff.changed()
else:
__salt__['cisconso.set_data_value'](datastore, path, config)
ret['result'] = True
ret['comment'] = 'Successfully added config'
diff = _DictDiffer(existing, config)
ret['changes']['new'] = diff.added()
ret['changes']['removed'] = diff.removed()
ret['changes']['changed'] = diff.changed()
return ret | python | def value_present(name, datastore, path, config):
'''
Ensure a specific value exists at a given path
:param name: The name for this rule
:type name: ``str``
:param datastore: The datastore, e.g. running, operational.
One of the NETCONF store IETF types
:type datastore: :class:`DatastoreType` (``str`` enum).
:param path: The device path to set the value at,
a list of element names in order, / separated
:type path: ``list``, ``str`` OR ``tuple``
:param config: The new value at the given path
:type config: ``dict``
Examples:
.. code-block:: yaml
enable pap auth:
cisconso.config_present:
- name: enable_pap_auth
- datastore: running
- path: devices/device/ex0/config/sys/interfaces/serial/ppp0/authentication
- config:
authentication:
method: pap
"list-name": foobar
'''
ret = {'name': name,
'result': False,
'changes': {},
'comment': ''}
existing = __salt__['cisconso.get_data'](datastore, path)
if salt.utils.compat.cmp(existing, config):
ret['result'] = True
ret['comment'] = 'Config is already set'
elif __opts__['test'] is True:
ret['result'] = None
ret['comment'] = 'Config will be added'
diff = _DictDiffer(existing, config)
ret['changes']['new'] = diff.added()
ret['changes']['removed'] = diff.removed()
ret['changes']['changed'] = diff.changed()
else:
__salt__['cisconso.set_data_value'](datastore, path, config)
ret['result'] = True
ret['comment'] = 'Successfully added config'
diff = _DictDiffer(existing, config)
ret['changes']['new'] = diff.added()
ret['changes']['removed'] = diff.removed()
ret['changes']['changed'] = diff.changed()
return ret | [
"def",
"value_present",
"(",
"name",
",",
"datastore",
",",
"path",
",",
"config",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"False",
",",
"'changes'",
":",
"{",
"}",
",",
"'comment'",
":",
"''",
"}",
"existing",
"=",
... | Ensure a specific value exists at a given path
:param name: The name for this rule
:type name: ``str``
:param datastore: The datastore, e.g. running, operational.
One of the NETCONF store IETF types
:type datastore: :class:`DatastoreType` (``str`` enum).
:param path: The device path to set the value at,
a list of element names in order, / separated
:type path: ``list``, ``str`` OR ``tuple``
:param config: The new value at the given path
:type config: ``dict``
Examples:
.. code-block:: yaml
enable pap auth:
cisconso.config_present:
- name: enable_pap_auth
- datastore: running
- path: devices/device/ex0/config/sys/interfaces/serial/ppp0/authentication
- config:
authentication:
method: pap
"list-name": foobar | [
"Ensure",
"a",
"specific",
"value",
"exists",
"at",
"a",
"given",
"path"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/cisconso.py#L22-L83 | train |
saltstack/salt | salt/states/rbac_solaris.py | managed | def managed(name, roles=None, profiles=None, authorizations=None):
'''
Manage RBAC properties for user
name : string
username
roles : list
list of roles for user
profiles : list
list of profiles for user
authorizations : list
list of authorizations for user
.. warning::
All existing roles, profiles and authorizations will be replaced!
An empty list will remove everything.
Set the property to `None` to not manage it.
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
## check properties
if name not in __salt__['user.list_users']():
ret['result'] = False
ret['comment'] = 'User {0} does not exist!'.format(name)
return ret
if roles and not isinstance(roles, (list)):
ret['result'] = False
ret['comment'] = 'Property roles is not None or list!'
return ret
if profiles and not isinstance(profiles, (list)):
ret['result'] = False
ret['comment'] = 'Property profiles is not None or list!'
return ret
if authorizations and not isinstance(authorizations, (list)):
ret['result'] = False
ret['comment'] = 'Property authorizations is not None or list!'
return ret
log.debug('rbac.managed - roles=%s, profiles=%s, authorizations=%s',
roles, profiles, authorizations
)
## update roles
if isinstance(roles, (list)):
# compute changed
roles_current = __salt__['rbac.role_get'](name)
roles_add = [r for r in roles if r not in roles_current]
roles_rm = [r for r in roles_current if r not in roles]
# execute and verify changes
if roles_add:
res_roles_add = __salt__['rbac.role_add'](name, ','.join(roles_add).strip())
roles_current = __salt__['rbac.role_get'](name)
for role in roles_add:
if 'roles' not in ret['changes']:
ret['changes']['roles'] = {}
ret['changes']['roles'][role] = 'Added' if role in roles_current else 'Failed'
if ret['changes']['roles'][role] == 'Failed':
ret['result'] = False
if roles_rm:
res_roles_rm = __salt__['rbac.role_rm'](name, ','.join(roles_rm).strip())
roles_current = __salt__['rbac.role_get'](name)
for role in roles_rm:
if 'roles' not in ret['changes']:
ret['changes']['roles'] = {}
ret['changes']['roles'][role] = 'Removed' if role not in roles_current else 'Failed'
if ret['changes']['roles'][role] == 'Failed':
ret['result'] = False
## update profiles
if isinstance(profiles, (list)):
# compute changed
profiles_current = __salt__['rbac.profile_get'](name)
profiles_add = [r for r in profiles if r not in profiles_current]
profiles_rm = [r for r in profiles_current if r not in profiles]
# execute and verify changes
if profiles_add:
res_profiles_add = __salt__['rbac.profile_add'](name, ','.join(profiles_add).strip())
profiles_current = __salt__['rbac.profile_get'](name)
for profile in profiles_add:
if 'profiles' not in ret['changes']:
ret['changes']['profiles'] = {}
ret['changes']['profiles'][profile] = 'Added' if profile in profiles_current else 'Failed'
if ret['changes']['profiles'][profile] == 'Failed':
ret['result'] = False
if profiles_rm:
res_profiles_rm = __salt__['rbac.profile_rm'](name, ','.join(profiles_rm).strip())
profiles_current = __salt__['rbac.profile_get'](name)
for profile in profiles_rm:
if 'profiles' not in ret['changes']:
ret['changes']['profiles'] = {}
ret['changes']['profiles'][profile] = 'Removed' if profile not in profiles_current else 'Failed'
if ret['changes']['profiles'][profile] == 'Failed':
ret['result'] = False
## update auths
if isinstance(authorizations, (list)):
# compute changed
auths_current = __salt__['rbac.auth_get'](name, False)
auths_add = [r for r in authorizations if r not in auths_current]
auths_rm = [r for r in auths_current if r not in authorizations]
# execute and verify changes
if auths_add:
res_auths_add = __salt__['rbac.auth_add'](name, ','.join(auths_add).strip())
auths_current = __salt__['rbac.auth_get'](name)
for auth in auths_add:
if 'authorizations' not in ret['changes']:
ret['changes']['authorizations'] = {}
ret['changes']['authorizations'][auth] = 'Added' if auth in auths_current else 'Failed'
if ret['changes']['authorizations'][auth] == 'Failed':
ret['result'] = False
if auths_rm:
res_auths_rm = __salt__['rbac.auth_rm'](name, ','.join(auths_rm).strip())
auths_current = __salt__['rbac.auth_get'](name)
for auth in auths_rm:
if 'authorizations' not in ret['changes']:
ret['changes']['authorizations'] = {}
ret['changes']['authorizations'][auth] = 'Removed' if auth not in auths_current else 'Failed'
if ret['changes']['authorizations'][auth] == 'Failed':
ret['result'] = False
return ret | python | def managed(name, roles=None, profiles=None, authorizations=None):
'''
Manage RBAC properties for user
name : string
username
roles : list
list of roles for user
profiles : list
list of profiles for user
authorizations : list
list of authorizations for user
.. warning::
All existing roles, profiles and authorizations will be replaced!
An empty list will remove everything.
Set the property to `None` to not manage it.
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
## check properties
if name not in __salt__['user.list_users']():
ret['result'] = False
ret['comment'] = 'User {0} does not exist!'.format(name)
return ret
if roles and not isinstance(roles, (list)):
ret['result'] = False
ret['comment'] = 'Property roles is not None or list!'
return ret
if profiles and not isinstance(profiles, (list)):
ret['result'] = False
ret['comment'] = 'Property profiles is not None or list!'
return ret
if authorizations and not isinstance(authorizations, (list)):
ret['result'] = False
ret['comment'] = 'Property authorizations is not None or list!'
return ret
log.debug('rbac.managed - roles=%s, profiles=%s, authorizations=%s',
roles, profiles, authorizations
)
## update roles
if isinstance(roles, (list)):
# compute changed
roles_current = __salt__['rbac.role_get'](name)
roles_add = [r for r in roles if r not in roles_current]
roles_rm = [r for r in roles_current if r not in roles]
# execute and verify changes
if roles_add:
res_roles_add = __salt__['rbac.role_add'](name, ','.join(roles_add).strip())
roles_current = __salt__['rbac.role_get'](name)
for role in roles_add:
if 'roles' not in ret['changes']:
ret['changes']['roles'] = {}
ret['changes']['roles'][role] = 'Added' if role in roles_current else 'Failed'
if ret['changes']['roles'][role] == 'Failed':
ret['result'] = False
if roles_rm:
res_roles_rm = __salt__['rbac.role_rm'](name, ','.join(roles_rm).strip())
roles_current = __salt__['rbac.role_get'](name)
for role in roles_rm:
if 'roles' not in ret['changes']:
ret['changes']['roles'] = {}
ret['changes']['roles'][role] = 'Removed' if role not in roles_current else 'Failed'
if ret['changes']['roles'][role] == 'Failed':
ret['result'] = False
## update profiles
if isinstance(profiles, (list)):
# compute changed
profiles_current = __salt__['rbac.profile_get'](name)
profiles_add = [r for r in profiles if r not in profiles_current]
profiles_rm = [r for r in profiles_current if r not in profiles]
# execute and verify changes
if profiles_add:
res_profiles_add = __salt__['rbac.profile_add'](name, ','.join(profiles_add).strip())
profiles_current = __salt__['rbac.profile_get'](name)
for profile in profiles_add:
if 'profiles' not in ret['changes']:
ret['changes']['profiles'] = {}
ret['changes']['profiles'][profile] = 'Added' if profile in profiles_current else 'Failed'
if ret['changes']['profiles'][profile] == 'Failed':
ret['result'] = False
if profiles_rm:
res_profiles_rm = __salt__['rbac.profile_rm'](name, ','.join(profiles_rm).strip())
profiles_current = __salt__['rbac.profile_get'](name)
for profile in profiles_rm:
if 'profiles' not in ret['changes']:
ret['changes']['profiles'] = {}
ret['changes']['profiles'][profile] = 'Removed' if profile not in profiles_current else 'Failed'
if ret['changes']['profiles'][profile] == 'Failed':
ret['result'] = False
## update auths
if isinstance(authorizations, (list)):
# compute changed
auths_current = __salt__['rbac.auth_get'](name, False)
auths_add = [r for r in authorizations if r not in auths_current]
auths_rm = [r for r in auths_current if r not in authorizations]
# execute and verify changes
if auths_add:
res_auths_add = __salt__['rbac.auth_add'](name, ','.join(auths_add).strip())
auths_current = __salt__['rbac.auth_get'](name)
for auth in auths_add:
if 'authorizations' not in ret['changes']:
ret['changes']['authorizations'] = {}
ret['changes']['authorizations'][auth] = 'Added' if auth in auths_current else 'Failed'
if ret['changes']['authorizations'][auth] == 'Failed':
ret['result'] = False
if auths_rm:
res_auths_rm = __salt__['rbac.auth_rm'](name, ','.join(auths_rm).strip())
auths_current = __salt__['rbac.auth_get'](name)
for auth in auths_rm:
if 'authorizations' not in ret['changes']:
ret['changes']['authorizations'] = {}
ret['changes']['authorizations'][auth] = 'Removed' if auth not in auths_current else 'Failed'
if ret['changes']['authorizations'][auth] == 'Failed':
ret['result'] = False
return ret | [
"def",
"managed",
"(",
"name",
",",
"roles",
"=",
"None",
",",
"profiles",
"=",
"None",
",",
"authorizations",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"True",
",",
"'comm... | Manage RBAC properties for user
name : string
username
roles : list
list of roles for user
profiles : list
list of profiles for user
authorizations : list
list of authorizations for user
.. warning::
All existing roles, profiles and authorizations will be replaced!
An empty list will remove everything.
Set the property to `None` to not manage it. | [
"Manage",
"RBAC",
"properties",
"for",
"user"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/rbac_solaris.py#L51-L184 | train |
saltstack/salt | salt/modules/match.py | pillar | def pillar(tgt, delimiter=DEFAULT_TARGET_DELIM):
'''
Return True if the minion matches the given pillar target. The
``delimiter`` argument can be used to specify a different delimiter.
CLI Example:
.. code-block:: bash
salt '*' match.pillar 'cheese:foo'
salt '*' match.pillar 'clone_url|https://github.com/saltstack/salt.git' delimiter='|'
delimiter
Specify an alternate delimiter to use when traversing a nested dict
.. versionadded:: 2014.7.0
delim
Specify an alternate delimiter to use when traversing a nested dict
.. versionadded:: 0.16.4
.. deprecated:: 2015.8.0
'''
matchers = salt.loader.matchers(__opts__)
try:
return matchers['pillar_match.match'](tgt, delimiter=delimiter, opts=__opts__)
except Exception as exc:
log.exception(exc)
return False | python | def pillar(tgt, delimiter=DEFAULT_TARGET_DELIM):
'''
Return True if the minion matches the given pillar target. The
``delimiter`` argument can be used to specify a different delimiter.
CLI Example:
.. code-block:: bash
salt '*' match.pillar 'cheese:foo'
salt '*' match.pillar 'clone_url|https://github.com/saltstack/salt.git' delimiter='|'
delimiter
Specify an alternate delimiter to use when traversing a nested dict
.. versionadded:: 2014.7.0
delim
Specify an alternate delimiter to use when traversing a nested dict
.. versionadded:: 0.16.4
.. deprecated:: 2015.8.0
'''
matchers = salt.loader.matchers(__opts__)
try:
return matchers['pillar_match.match'](tgt, delimiter=delimiter, opts=__opts__)
except Exception as exc:
log.exception(exc)
return False | [
"def",
"pillar",
"(",
"tgt",
",",
"delimiter",
"=",
"DEFAULT_TARGET_DELIM",
")",
":",
"matchers",
"=",
"salt",
".",
"loader",
".",
"matchers",
"(",
"__opts__",
")",
"try",
":",
"return",
"matchers",
"[",
"'pillar_match.match'",
"]",
"(",
"tgt",
",",
"delim... | Return True if the minion matches the given pillar target. The
``delimiter`` argument can be used to specify a different delimiter.
CLI Example:
.. code-block:: bash
salt '*' match.pillar 'cheese:foo'
salt '*' match.pillar 'clone_url|https://github.com/saltstack/salt.git' delimiter='|'
delimiter
Specify an alternate delimiter to use when traversing a nested dict
.. versionadded:: 2014.7.0
delim
Specify an alternate delimiter to use when traversing a nested dict
.. versionadded:: 0.16.4
.. deprecated:: 2015.8.0 | [
"Return",
"True",
"if",
"the",
"minion",
"matches",
"the",
"given",
"pillar",
"target",
".",
"The",
"delimiter",
"argument",
"can",
"be",
"used",
"to",
"specify",
"a",
"different",
"delimiter",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/match.py#L117-L145 | train |
saltstack/salt | salt/modules/match.py | data | def data(tgt):
'''
Return True if the minion matches the given data target
CLI Example:
.. code-block:: bash
salt '*' match.data 'spam:eggs'
'''
matchers = salt.loader.matchers(__opts__)
try:
return matchers['data_match.match'](tgt, opts=__opts__)
except Exception as exc:
log.exception(exc)
return False | python | def data(tgt):
'''
Return True if the minion matches the given data target
CLI Example:
.. code-block:: bash
salt '*' match.data 'spam:eggs'
'''
matchers = salt.loader.matchers(__opts__)
try:
return matchers['data_match.match'](tgt, opts=__opts__)
except Exception as exc:
log.exception(exc)
return False | [
"def",
"data",
"(",
"tgt",
")",
":",
"matchers",
"=",
"salt",
".",
"loader",
".",
"matchers",
"(",
"__opts__",
")",
"try",
":",
"return",
"matchers",
"[",
"'data_match.match'",
"]",
"(",
"tgt",
",",
"opts",
"=",
"__opts__",
")",
"except",
"Exception",
... | Return True if the minion matches the given data target
CLI Example:
.. code-block:: bash
salt '*' match.data 'spam:eggs' | [
"Return",
"True",
"if",
"the",
"minion",
"matches",
"the",
"given",
"data",
"target"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/match.py#L148-L163 | train |
saltstack/salt | salt/modules/match.py | pcre | def pcre(tgt, minion_id=None):
'''
Return True if the minion ID matches the given pcre target
minion_id
Specify the minion ID to match against the target expression
.. versionadded:: 2014.7.0
CLI Example:
.. code-block:: bash
salt '*' match.pcre '.*'
'''
if minion_id is not None:
opts = copy.copy(__opts__)
if not isinstance(minion_id, six.string_types):
minion_id = six.text_type(minion_id)
opts['id'] = minion_id
else:
opts = __opts__
matchers = salt.loader.matchers(opts)
try:
return matchers['pcre_match.match'](tgt, opts=__opts__)
except Exception as exc:
log.exception(exc)
return False | python | def pcre(tgt, minion_id=None):
'''
Return True if the minion ID matches the given pcre target
minion_id
Specify the minion ID to match against the target expression
.. versionadded:: 2014.7.0
CLI Example:
.. code-block:: bash
salt '*' match.pcre '.*'
'''
if minion_id is not None:
opts = copy.copy(__opts__)
if not isinstance(minion_id, six.string_types):
minion_id = six.text_type(minion_id)
opts['id'] = minion_id
else:
opts = __opts__
matchers = salt.loader.matchers(opts)
try:
return matchers['pcre_match.match'](tgt, opts=__opts__)
except Exception as exc:
log.exception(exc)
return False | [
"def",
"pcre",
"(",
"tgt",
",",
"minion_id",
"=",
"None",
")",
":",
"if",
"minion_id",
"is",
"not",
"None",
":",
"opts",
"=",
"copy",
".",
"copy",
"(",
"__opts__",
")",
"if",
"not",
"isinstance",
"(",
"minion_id",
",",
"six",
".",
"string_types",
")"... | Return True if the minion ID matches the given pcre target
minion_id
Specify the minion ID to match against the target expression
.. versionadded:: 2014.7.0
CLI Example:
.. code-block:: bash
salt '*' match.pcre '.*' | [
"Return",
"True",
"if",
"the",
"minion",
"ID",
"matches",
"the",
"given",
"pcre",
"target"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/match.py#L258-L285 | train |
saltstack/salt | salt/modules/match.py | filter_by | def filter_by(lookup,
tgt_type='compound',
minion_id=None,
merge=None,
merge_lists=False,
default='default'):
'''
Return the first match in a dictionary of target patterns
.. versionadded:: 2014.7.0
CLI Example:
.. code-block:: bash
salt '*' match.filter_by '{foo*: Foo!, bar*: Bar!}' minion_id=bar03
Pillar Example:
.. code-block:: jinja
# Filter the data for the current minion into a variable:
{% set roles = salt['match.filter_by']({
'web*': ['app', 'caching'],
'db*': ['db'],
}, default='web*') %}
# Make the filtered data available to Pillar:
roles: {{ roles | yaml() }}
'''
expr_funcs = dict(inspect.getmembers(sys.modules[__name__],
predicate=inspect.isfunction))
for key in lookup:
params = (key, minion_id) if minion_id else (key, )
if expr_funcs[tgt_type](*params):
if merge:
if not isinstance(merge, collections.Mapping):
raise SaltException(
'filter_by merge argument must be a dictionary.')
if lookup[key] is None:
return merge
else:
salt.utils.dictupdate.update(lookup[key], copy.deepcopy(merge), merge_lists=merge_lists)
return lookup[key]
return lookup.get(default, None) | python | def filter_by(lookup,
tgt_type='compound',
minion_id=None,
merge=None,
merge_lists=False,
default='default'):
'''
Return the first match in a dictionary of target patterns
.. versionadded:: 2014.7.0
CLI Example:
.. code-block:: bash
salt '*' match.filter_by '{foo*: Foo!, bar*: Bar!}' minion_id=bar03
Pillar Example:
.. code-block:: jinja
# Filter the data for the current minion into a variable:
{% set roles = salt['match.filter_by']({
'web*': ['app', 'caching'],
'db*': ['db'],
}, default='web*') %}
# Make the filtered data available to Pillar:
roles: {{ roles | yaml() }}
'''
expr_funcs = dict(inspect.getmembers(sys.modules[__name__],
predicate=inspect.isfunction))
for key in lookup:
params = (key, minion_id) if minion_id else (key, )
if expr_funcs[tgt_type](*params):
if merge:
if not isinstance(merge, collections.Mapping):
raise SaltException(
'filter_by merge argument must be a dictionary.')
if lookup[key] is None:
return merge
else:
salt.utils.dictupdate.update(lookup[key], copy.deepcopy(merge), merge_lists=merge_lists)
return lookup[key]
return lookup.get(default, None) | [
"def",
"filter_by",
"(",
"lookup",
",",
"tgt_type",
"=",
"'compound'",
",",
"minion_id",
"=",
"None",
",",
"merge",
"=",
"None",
",",
"merge_lists",
"=",
"False",
",",
"default",
"=",
"'default'",
")",
":",
"expr_funcs",
"=",
"dict",
"(",
"inspect",
".",... | Return the first match in a dictionary of target patterns
.. versionadded:: 2014.7.0
CLI Example:
.. code-block:: bash
salt '*' match.filter_by '{foo*: Foo!, bar*: Bar!}' minion_id=bar03
Pillar Example:
.. code-block:: jinja
# Filter the data for the current minion into a variable:
{% set roles = salt['match.filter_by']({
'web*': ['app', 'caching'],
'db*': ['db'],
}, default='web*') %}
# Make the filtered data available to Pillar:
roles: {{ roles | yaml() }} | [
"Return",
"the",
"first",
"match",
"in",
"a",
"dictionary",
"of",
"target",
"patterns"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/match.py#L319-L367 | train |
saltstack/salt | salt/modules/match.py | search_by | def search_by(lookup, tgt_type='compound', minion_id=None):
'''
Search a dictionary of target strings for matching targets
This is the inverse of :py:func:`match.filter_by
<salt.modules.match.filter_by>` and allows matching values instead of
matching keys. A minion can be matched by multiple entries.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' match.search_by '{web: [node1, node2], db: [node2, node]}'
Pillar Example:
.. code-block:: jinja
{% set roles = salt.match.search_by({
'web': ['G@os_family:Debian not nodeX'],
'db': ['L@node2,node3 and G@datacenter:west'],
'caching': ['node3', 'node4'],
}) %}
# Make the filtered data available to Pillar:
roles: {{ roles | yaml() }}
'''
expr_funcs = dict(inspect.getmembers(sys.modules[__name__],
predicate=inspect.isfunction))
matches = []
for key, target_list in lookup.items():
for target in target_list:
params = (target, minion_id) if minion_id else (target, )
if expr_funcs[tgt_type](*params):
matches.append(key)
return matches or None | python | def search_by(lookup, tgt_type='compound', minion_id=None):
'''
Search a dictionary of target strings for matching targets
This is the inverse of :py:func:`match.filter_by
<salt.modules.match.filter_by>` and allows matching values instead of
matching keys. A minion can be matched by multiple entries.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' match.search_by '{web: [node1, node2], db: [node2, node]}'
Pillar Example:
.. code-block:: jinja
{% set roles = salt.match.search_by({
'web': ['G@os_family:Debian not nodeX'],
'db': ['L@node2,node3 and G@datacenter:west'],
'caching': ['node3', 'node4'],
}) %}
# Make the filtered data available to Pillar:
roles: {{ roles | yaml() }}
'''
expr_funcs = dict(inspect.getmembers(sys.modules[__name__],
predicate=inspect.isfunction))
matches = []
for key, target_list in lookup.items():
for target in target_list:
params = (target, minion_id) if minion_id else (target, )
if expr_funcs[tgt_type](*params):
matches.append(key)
return matches or None | [
"def",
"search_by",
"(",
"lookup",
",",
"tgt_type",
"=",
"'compound'",
",",
"minion_id",
"=",
"None",
")",
":",
"expr_funcs",
"=",
"dict",
"(",
"inspect",
".",
"getmembers",
"(",
"sys",
".",
"modules",
"[",
"__name__",
"]",
",",
"predicate",
"=",
"inspec... | Search a dictionary of target strings for matching targets
This is the inverse of :py:func:`match.filter_by
<salt.modules.match.filter_by>` and allows matching values instead of
matching keys. A minion can be matched by multiple entries.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' match.search_by '{web: [node1, node2], db: [node2, node]}'
Pillar Example:
.. code-block:: jinja
{% set roles = salt.match.search_by({
'web': ['G@os_family:Debian not nodeX'],
'db': ['L@node2,node3 and G@datacenter:west'],
'caching': ['node3', 'node4'],
}) %}
# Make the filtered data available to Pillar:
roles: {{ roles | yaml() }} | [
"Search",
"a",
"dictionary",
"of",
"target",
"strings",
"for",
"matching",
"targets"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/match.py#L370-L409 | train |
saltstack/salt | salt/modules/varnish.py | _run_varnishadm | def _run_varnishadm(cmd, params=(), **kwargs):
'''
Execute varnishadm command
return the output of the command
cmd
The command to run in varnishadm
params
Any additional args to add to the command line
kwargs
Additional options to pass to the salt cmd.run_all function
'''
cmd = ['varnishadm', cmd]
cmd.extend([param for param in params if param is not None])
log.debug('Executing: %s', ' '.join(cmd))
return __salt__['cmd.run_all'](cmd, python_shell=False, **kwargs) | python | def _run_varnishadm(cmd, params=(), **kwargs):
'''
Execute varnishadm command
return the output of the command
cmd
The command to run in varnishadm
params
Any additional args to add to the command line
kwargs
Additional options to pass to the salt cmd.run_all function
'''
cmd = ['varnishadm', cmd]
cmd.extend([param for param in params if param is not None])
log.debug('Executing: %s', ' '.join(cmd))
return __salt__['cmd.run_all'](cmd, python_shell=False, **kwargs) | [
"def",
"_run_varnishadm",
"(",
"cmd",
",",
"params",
"=",
"(",
")",
",",
"*",
"*",
"kwargs",
")",
":",
"cmd",
"=",
"[",
"'varnishadm'",
",",
"cmd",
"]",
"cmd",
".",
"extend",
"(",
"[",
"param",
"for",
"param",
"in",
"params",
"if",
"param",
"is",
... | Execute varnishadm command
return the output of the command
cmd
The command to run in varnishadm
params
Any additional args to add to the command line
kwargs
Additional options to pass to the salt cmd.run_all function | [
"Execute",
"varnishadm",
"command",
"return",
"the",
"output",
"of",
"the",
"command"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/varnish.py#L37-L54 | train |
saltstack/salt | salt/modules/varnish.py | version | def version():
'''
Return server version from varnishd -V
CLI Example:
.. code-block:: bash
salt '*' varnish.version
'''
cmd = ['varnishd', '-V']
out = __salt__['cmd.run'](cmd, python_shell=False)
ret = re.search(r'\(varnish-([^\)]+)\)', out).group(1)
return ret | python | def version():
'''
Return server version from varnishd -V
CLI Example:
.. code-block:: bash
salt '*' varnish.version
'''
cmd = ['varnishd', '-V']
out = __salt__['cmd.run'](cmd, python_shell=False)
ret = re.search(r'\(varnish-([^\)]+)\)', out).group(1)
return ret | [
"def",
"version",
"(",
")",
":",
"cmd",
"=",
"[",
"'varnishd'",
",",
"'-V'",
"]",
"out",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"cmd",
",",
"python_shell",
"=",
"False",
")",
"ret",
"=",
"re",
".",
"search",
"(",
"r'\\(varnish-([^\\)]+)\\)'",
","... | Return server version from varnishd -V
CLI Example:
.. code-block:: bash
salt '*' varnish.version | [
"Return",
"server",
"version",
"from",
"varnishd",
"-",
"V"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/varnish.py#L57-L70 | train |
saltstack/salt | salt/modules/varnish.py | param_show | def param_show(param=None):
'''
Show params of varnish cache
CLI Example:
.. code-block:: bash
salt '*' varnish.param_show param
'''
ret = _run_varnishadm('param.show', [param])
if ret['retcode']:
return False
else:
result = {}
for line in ret['stdout'].split('\n'):
m = re.search(r'^(\w+)\s+(.*)$', line)
result[m.group(1)] = m.group(2)
if param:
# When we ask to varnishadm for a specific param, it gives full
# info on what that parameter is, so we just process the first
# line and we get out of the loop
break
return result | python | def param_show(param=None):
'''
Show params of varnish cache
CLI Example:
.. code-block:: bash
salt '*' varnish.param_show param
'''
ret = _run_varnishadm('param.show', [param])
if ret['retcode']:
return False
else:
result = {}
for line in ret['stdout'].split('\n'):
m = re.search(r'^(\w+)\s+(.*)$', line)
result[m.group(1)] = m.group(2)
if param:
# When we ask to varnishadm for a specific param, it gives full
# info on what that parameter is, so we just process the first
# line and we get out of the loop
break
return result | [
"def",
"param_show",
"(",
"param",
"=",
"None",
")",
":",
"ret",
"=",
"_run_varnishadm",
"(",
"'param.show'",
",",
"[",
"param",
"]",
")",
"if",
"ret",
"[",
"'retcode'",
"]",
":",
"return",
"False",
"else",
":",
"result",
"=",
"{",
"}",
"for",
"line"... | Show params of varnish cache
CLI Example:
.. code-block:: bash
salt '*' varnish.param_show param | [
"Show",
"params",
"of",
"varnish",
"cache"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/varnish.py#L129-L152 | train |
saltstack/salt | salt/proxy/panos.py | _strip_dirty | def _strip_dirty(xmltree):
'''
Removes dirtyID tags from the candidate config result. Palo Alto devices will make the candidate configuration with
a dirty ID after a change. This can cause unexpected results when parsing.
'''
dirty = xmltree.attrib.pop('dirtyId', None)
if dirty:
xmltree.attrib.pop('admin', None)
xmltree.attrib.pop('time', None)
for child in xmltree:
child = _strip_dirty(child)
return xmltree | python | def _strip_dirty(xmltree):
'''
Removes dirtyID tags from the candidate config result. Palo Alto devices will make the candidate configuration with
a dirty ID after a change. This can cause unexpected results when parsing.
'''
dirty = xmltree.attrib.pop('dirtyId', None)
if dirty:
xmltree.attrib.pop('admin', None)
xmltree.attrib.pop('time', None)
for child in xmltree:
child = _strip_dirty(child)
return xmltree | [
"def",
"_strip_dirty",
"(",
"xmltree",
")",
":",
"dirty",
"=",
"xmltree",
".",
"attrib",
".",
"pop",
"(",
"'dirtyId'",
",",
"None",
")",
"if",
"dirty",
":",
"xmltree",
".",
"attrib",
".",
"pop",
"(",
"'admin'",
",",
"None",
")",
"xmltree",
".",
"attr... | Removes dirtyID tags from the candidate config result. Palo Alto devices will make the candidate configuration with
a dirty ID after a change. This can cause unexpected results when parsing. | [
"Removes",
"dirtyID",
"tags",
"from",
"the",
"candidate",
"config",
"result",
".",
"Palo",
"Alto",
"devices",
"will",
"make",
"the",
"candidate",
"configuration",
"with",
"a",
"dirty",
"ID",
"after",
"a",
"change",
".",
"This",
"can",
"cause",
"unexpected",
... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/panos.py#L238-L251 | train |
saltstack/salt | salt/proxy/panos.py | init | def init(opts):
'''
This function gets called when the proxy starts up. For
panos devices, a determination is made on the connection type
and the appropriate connection details that must be cached.
'''
if 'host' not in opts['proxy']:
log.critical('No \'host\' key found in pillar for this proxy.')
return False
if 'apikey' not in opts['proxy']:
# If we do not have an apikey, we must have both a username and password
if 'username' not in opts['proxy']:
log.critical('No \'username\' key found in pillar for this proxy.')
return False
if 'password' not in opts['proxy']:
log.critical('No \'passwords\' key found in pillar for this proxy.')
return False
DETAILS['url'] = 'https://{0}/api/'.format(opts['proxy']['host'])
# Set configuration details
DETAILS['host'] = opts['proxy']['host']
if 'serial' in opts['proxy']:
DETAILS['serial'] = opts['proxy'].get('serial')
if 'apikey' in opts['proxy']:
log.debug("Selected pan_key method for panos proxy module.")
DETAILS['method'] = 'pan_key'
DETAILS['apikey'] = opts['proxy'].get('apikey')
else:
log.debug("Selected pan_pass method for panos proxy module.")
DETAILS['method'] = 'pan_pass'
DETAILS['username'] = opts['proxy'].get('username')
DETAILS['password'] = opts['proxy'].get('password')
else:
if 'apikey' in opts['proxy']:
log.debug("Selected dev_key method for panos proxy module.")
DETAILS['method'] = 'dev_key'
DETAILS['apikey'] = opts['proxy'].get('apikey')
else:
log.debug("Selected dev_pass method for panos proxy module.")
DETAILS['method'] = 'dev_pass'
DETAILS['username'] = opts['proxy'].get('username')
DETAILS['password'] = opts['proxy'].get('password')
# Ensure connectivity to the device
log.debug("Attempting to connect to panos proxy host.")
query = {'type': 'op', 'cmd': '<show><system><info></info></system></show>'}
call(query)
log.debug("Successfully connected to panos proxy host.")
DETAILS['initialized'] = True | python | def init(opts):
'''
This function gets called when the proxy starts up. For
panos devices, a determination is made on the connection type
and the appropriate connection details that must be cached.
'''
if 'host' not in opts['proxy']:
log.critical('No \'host\' key found in pillar for this proxy.')
return False
if 'apikey' not in opts['proxy']:
# If we do not have an apikey, we must have both a username and password
if 'username' not in opts['proxy']:
log.critical('No \'username\' key found in pillar for this proxy.')
return False
if 'password' not in opts['proxy']:
log.critical('No \'passwords\' key found in pillar for this proxy.')
return False
DETAILS['url'] = 'https://{0}/api/'.format(opts['proxy']['host'])
# Set configuration details
DETAILS['host'] = opts['proxy']['host']
if 'serial' in opts['proxy']:
DETAILS['serial'] = opts['proxy'].get('serial')
if 'apikey' in opts['proxy']:
log.debug("Selected pan_key method for panos proxy module.")
DETAILS['method'] = 'pan_key'
DETAILS['apikey'] = opts['proxy'].get('apikey')
else:
log.debug("Selected pan_pass method for panos proxy module.")
DETAILS['method'] = 'pan_pass'
DETAILS['username'] = opts['proxy'].get('username')
DETAILS['password'] = opts['proxy'].get('password')
else:
if 'apikey' in opts['proxy']:
log.debug("Selected dev_key method for panos proxy module.")
DETAILS['method'] = 'dev_key'
DETAILS['apikey'] = opts['proxy'].get('apikey')
else:
log.debug("Selected dev_pass method for panos proxy module.")
DETAILS['method'] = 'dev_pass'
DETAILS['username'] = opts['proxy'].get('username')
DETAILS['password'] = opts['proxy'].get('password')
# Ensure connectivity to the device
log.debug("Attempting to connect to panos proxy host.")
query = {'type': 'op', 'cmd': '<show><system><info></info></system></show>'}
call(query)
log.debug("Successfully connected to panos proxy host.")
DETAILS['initialized'] = True | [
"def",
"init",
"(",
"opts",
")",
":",
"if",
"'host'",
"not",
"in",
"opts",
"[",
"'proxy'",
"]",
":",
"log",
".",
"critical",
"(",
"'No \\'host\\' key found in pillar for this proxy.'",
")",
"return",
"False",
"if",
"'apikey'",
"not",
"in",
"opts",
"[",
"'pro... | This function gets called when the proxy starts up. For
panos devices, a determination is made on the connection type
and the appropriate connection details that must be cached. | [
"This",
"function",
"gets",
"called",
"when",
"the",
"proxy",
"starts",
"up",
".",
"For",
"panos",
"devices",
"a",
"determination",
"is",
"made",
"on",
"the",
"connection",
"type",
"and",
"the",
"appropriate",
"connection",
"details",
"that",
"must",
"be",
"... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/panos.py#L254-L304 | train |
saltstack/salt | salt/proxy/panos.py | call | def call(payload=None):
'''
This function captures the query string and sends it to the Palo Alto device.
'''
r = None
try:
if DETAILS['method'] == 'dev_key':
# Pass the api key without the target declaration
conditional_payload = {'key': DETAILS['apikey']}
payload.update(conditional_payload)
r = __utils__['http.query'](DETAILS['url'],
data=payload,
method='POST',
decode_type='plain',
decode=True,
verify_ssl=False,
status=True,
raise_error=True)
elif DETAILS['method'] == 'dev_pass':
# Pass credentials without the target declaration
r = __utils__['http.query'](DETAILS['url'],
username=DETAILS['username'],
password=DETAILS['password'],
data=payload,
method='POST',
decode_type='plain',
decode=True,
verify_ssl=False,
status=True,
raise_error=True)
elif DETAILS['method'] == 'pan_key':
# Pass the api key with the target declaration
conditional_payload = {'key': DETAILS['apikey'],
'target': DETAILS['serial']}
payload.update(conditional_payload)
r = __utils__['http.query'](DETAILS['url'],
data=payload,
method='POST',
decode_type='plain',
decode=True,
verify_ssl=False,
status=True,
raise_error=True)
elif DETAILS['method'] == 'pan_pass':
# Pass credentials with the target declaration
conditional_payload = {'target': DETAILS['serial']}
payload.update(conditional_payload)
r = __utils__['http.query'](DETAILS['url'],
username=DETAILS['username'],
password=DETAILS['password'],
data=payload,
method='POST',
decode_type='plain',
decode=True,
verify_ssl=False,
status=True,
raise_error=True)
except KeyError as err:
raise salt.exceptions.CommandExecutionError("Did not receive a valid response from host.")
if not r:
raise salt.exceptions.CommandExecutionError("Did not receive a valid response from host.")
if six.text_type(r['status']) not in ['200', '201', '204']:
if six.text_type(r['status']) == '400':
raise salt.exceptions.CommandExecutionError(
"The server cannot process the request due to a client error.")
elif six.text_type(r['status']) == '401':
raise salt.exceptions.CommandExecutionError(
"The server cannot process the request because it lacks valid authentication "
"credentials for the target resource.")
elif six.text_type(r['status']) == '403':
raise salt.exceptions.CommandExecutionError(
"The server refused to authorize the request.")
elif six.text_type(r['status']) == '404':
raise salt.exceptions.CommandExecutionError(
"The requested resource could not be found.")
else:
raise salt.exceptions.CommandExecutionError(
"Did not receive a valid response from host.")
xmldata = ET.fromstring(r['text'])
# If we are pulling the candidate configuration, we need to strip the dirtyId
if payload['type'] == 'config' and payload['action'] == 'get':
xmldata = (_strip_dirty(xmldata))
return xml.to_dict(xmldata, True) | python | def call(payload=None):
'''
This function captures the query string and sends it to the Palo Alto device.
'''
r = None
try:
if DETAILS['method'] == 'dev_key':
# Pass the api key without the target declaration
conditional_payload = {'key': DETAILS['apikey']}
payload.update(conditional_payload)
r = __utils__['http.query'](DETAILS['url'],
data=payload,
method='POST',
decode_type='plain',
decode=True,
verify_ssl=False,
status=True,
raise_error=True)
elif DETAILS['method'] == 'dev_pass':
# Pass credentials without the target declaration
r = __utils__['http.query'](DETAILS['url'],
username=DETAILS['username'],
password=DETAILS['password'],
data=payload,
method='POST',
decode_type='plain',
decode=True,
verify_ssl=False,
status=True,
raise_error=True)
elif DETAILS['method'] == 'pan_key':
# Pass the api key with the target declaration
conditional_payload = {'key': DETAILS['apikey'],
'target': DETAILS['serial']}
payload.update(conditional_payload)
r = __utils__['http.query'](DETAILS['url'],
data=payload,
method='POST',
decode_type='plain',
decode=True,
verify_ssl=False,
status=True,
raise_error=True)
elif DETAILS['method'] == 'pan_pass':
# Pass credentials with the target declaration
conditional_payload = {'target': DETAILS['serial']}
payload.update(conditional_payload)
r = __utils__['http.query'](DETAILS['url'],
username=DETAILS['username'],
password=DETAILS['password'],
data=payload,
method='POST',
decode_type='plain',
decode=True,
verify_ssl=False,
status=True,
raise_error=True)
except KeyError as err:
raise salt.exceptions.CommandExecutionError("Did not receive a valid response from host.")
if not r:
raise salt.exceptions.CommandExecutionError("Did not receive a valid response from host.")
if six.text_type(r['status']) not in ['200', '201', '204']:
if six.text_type(r['status']) == '400':
raise salt.exceptions.CommandExecutionError(
"The server cannot process the request due to a client error.")
elif six.text_type(r['status']) == '401':
raise salt.exceptions.CommandExecutionError(
"The server cannot process the request because it lacks valid authentication "
"credentials for the target resource.")
elif six.text_type(r['status']) == '403':
raise salt.exceptions.CommandExecutionError(
"The server refused to authorize the request.")
elif six.text_type(r['status']) == '404':
raise salt.exceptions.CommandExecutionError(
"The requested resource could not be found.")
else:
raise salt.exceptions.CommandExecutionError(
"Did not receive a valid response from host.")
xmldata = ET.fromstring(r['text'])
# If we are pulling the candidate configuration, we need to strip the dirtyId
if payload['type'] == 'config' and payload['action'] == 'get':
xmldata = (_strip_dirty(xmldata))
return xml.to_dict(xmldata, True) | [
"def",
"call",
"(",
"payload",
"=",
"None",
")",
":",
"r",
"=",
"None",
"try",
":",
"if",
"DETAILS",
"[",
"'method'",
"]",
"==",
"'dev_key'",
":",
"# Pass the api key without the target declaration",
"conditional_payload",
"=",
"{",
"'key'",
":",
"DETAILS",
"[... | This function captures the query string and sends it to the Palo Alto device. | [
"This",
"function",
"captures",
"the",
"query",
"string",
"and",
"sends",
"it",
"to",
"the",
"Palo",
"Alto",
"device",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/panos.py#L307-L394 | train |
saltstack/salt | salt/proxy/panos.py | is_required_version | def is_required_version(required_version='0.0.0'):
'''
Because different versions of Palo Alto support different command sets, this function
will return true if the current version of Palo Alto supports the required command.
'''
if 'sw-version' in DETAILS['grains_cache']:
current_version = DETAILS['grains_cache']['sw-version']
else:
# If we do not have the current sw-version cached, we cannot check version requirements.
return False
required_version_split = required_version.split(".")
current_version_split = current_version.split(".")
try:
if int(current_version_split[0]) > int(required_version_split[0]):
return True
elif int(current_version_split[0]) < int(required_version_split[0]):
return False
if int(current_version_split[1]) > int(required_version_split[1]):
return True
elif int(current_version_split[1]) < int(required_version_split[1]):
return False
if int(current_version_split[2]) > int(required_version_split[2]):
return True
elif int(current_version_split[2]) < int(required_version_split[2]):
return False
# We have an exact match
return True
except Exception as err:
return False | python | def is_required_version(required_version='0.0.0'):
'''
Because different versions of Palo Alto support different command sets, this function
will return true if the current version of Palo Alto supports the required command.
'''
if 'sw-version' in DETAILS['grains_cache']:
current_version = DETAILS['grains_cache']['sw-version']
else:
# If we do not have the current sw-version cached, we cannot check version requirements.
return False
required_version_split = required_version.split(".")
current_version_split = current_version.split(".")
try:
if int(current_version_split[0]) > int(required_version_split[0]):
return True
elif int(current_version_split[0]) < int(required_version_split[0]):
return False
if int(current_version_split[1]) > int(required_version_split[1]):
return True
elif int(current_version_split[1]) < int(required_version_split[1]):
return False
if int(current_version_split[2]) > int(required_version_split[2]):
return True
elif int(current_version_split[2]) < int(required_version_split[2]):
return False
# We have an exact match
return True
except Exception as err:
return False | [
"def",
"is_required_version",
"(",
"required_version",
"=",
"'0.0.0'",
")",
":",
"if",
"'sw-version'",
"in",
"DETAILS",
"[",
"'grains_cache'",
"]",
":",
"current_version",
"=",
"DETAILS",
"[",
"'grains_cache'",
"]",
"[",
"'sw-version'",
"]",
"else",
":",
"# If w... | Because different versions of Palo Alto support different command sets, this function
will return true if the current version of Palo Alto supports the required command. | [
"Because",
"different",
"versions",
"of",
"Palo",
"Alto",
"support",
"different",
"command",
"sets",
"this",
"function",
"will",
"return",
"true",
"if",
"the",
"current",
"version",
"of",
"Palo",
"Alto",
"supports",
"the",
"required",
"command",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/panos.py#L397-L430 | train |
saltstack/salt | salt/proxy/panos.py | grains | def grains():
'''
Get the grains from the proxied device
'''
if not DETAILS.get('grains_cache', {}):
DETAILS['grains_cache'] = GRAINS_CACHE
try:
query = {'type': 'op', 'cmd': '<show><system><info></info></system></show>'}
DETAILS['grains_cache'] = call(query)['result']['system']
except Exception as err:
pass
return DETAILS['grains_cache'] | python | def grains():
'''
Get the grains from the proxied device
'''
if not DETAILS.get('grains_cache', {}):
DETAILS['grains_cache'] = GRAINS_CACHE
try:
query = {'type': 'op', 'cmd': '<show><system><info></info></system></show>'}
DETAILS['grains_cache'] = call(query)['result']['system']
except Exception as err:
pass
return DETAILS['grains_cache'] | [
"def",
"grains",
"(",
")",
":",
"if",
"not",
"DETAILS",
".",
"get",
"(",
"'grains_cache'",
",",
"{",
"}",
")",
":",
"DETAILS",
"[",
"'grains_cache'",
"]",
"=",
"GRAINS_CACHE",
"try",
":",
"query",
"=",
"{",
"'type'",
":",
"'op'",
",",
"'cmd'",
":",
... | Get the grains from the proxied device | [
"Get",
"the",
"grains",
"from",
"the",
"proxied",
"device"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/panos.py#L442-L453 | train |
saltstack/salt | salt/states/kmod.py | _append_comment | def _append_comment(ret, comment):
'''
append ``comment`` to ``ret['comment']``
'''
if ret['comment']:
ret['comment'] = ret['comment'].rstrip() + '\n' + comment
else:
ret['comment'] = comment
return ret | python | def _append_comment(ret, comment):
'''
append ``comment`` to ``ret['comment']``
'''
if ret['comment']:
ret['comment'] = ret['comment'].rstrip() + '\n' + comment
else:
ret['comment'] = comment
return ret | [
"def",
"_append_comment",
"(",
"ret",
",",
"comment",
")",
":",
"if",
"ret",
"[",
"'comment'",
"]",
":",
"ret",
"[",
"'comment'",
"]",
"=",
"ret",
"[",
"'comment'",
"]",
".",
"rstrip",
"(",
")",
"+",
"'\\n'",
"+",
"comment",
"else",
":",
"ret",
"["... | append ``comment`` to ``ret['comment']`` | [
"append",
"comment",
"to",
"ret",
"[",
"comment",
"]"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/kmod.py#L43-L52 | train |
saltstack/salt | salt/states/kmod.py | present | def present(name, persist=False, mods=None):
'''
Ensure that the specified kernel module is loaded
name
The name of the kernel module to verify is loaded
persist
Also add module to ``/etc/modules``
mods
A list of modules to verify are loaded. If this argument is used, the
``name`` argument, although still required, is not used, and becomes a
placeholder
.. versionadded:: 2016.3.0
'''
if not isinstance(mods, (list, tuple)):
mods = [name]
ret = {'name': name,
'result': True,
'changes': {},
'comment': ''}
loaded_mods = __salt__['kmod.mod_list']()
if persist:
persist_mods = __salt__['kmod.mod_list'](True)
# Intersection of loaded modules and persistent modules
loaded_mods = list(set(loaded_mods) & set(persist_mods))
# Intersection of loaded and proposed modules
already_loaded = list(set(loaded_mods) & set(mods))
if len(already_loaded) == 1:
comment = 'Kernel module {0} is already present'.format(already_loaded[0])
_append_comment(ret, comment)
elif len(already_loaded) > 1:
comment = 'Kernel modules {0} are already present'.format(', '.join(already_loaded))
_append_comment(ret, comment)
if len(already_loaded) == len(mods):
return ret # all modules already loaded
# Complement of proposed modules and already loaded modules
not_loaded = list(set(mods) - set(already_loaded))
if __opts__['test']:
ret['result'] = None
if ret['comment']:
ret['comment'] += '\n'
if len(not_loaded) == 1:
comment = 'Kernel module {0} is set to be loaded'.format(not_loaded[0])
else:
comment = 'Kernel modules {0} are set to be loaded'.format(', '.join(not_loaded))
_append_comment(ret, comment)
return ret
# Complement of proposed, unloaded modules and available modules
unavailable = list(set(not_loaded) - set(__salt__['kmod.available']()))
if unavailable:
if len(unavailable) == 1:
comment = 'Kernel module {0} is unavailable'.format(unavailable[0])
else:
comment = 'Kernel modules {0} are unavailable'.format(', '.join(unavailable))
_append_comment(ret, comment)
ret['result'] = False
# The remaining modules are not loaded and are available for loading
available = list(set(not_loaded) - set(unavailable))
loaded = {'yes': [], 'no': [], 'failed': []}
loaded_by_dependency = []
for mod in available:
if mod in loaded_by_dependency:
loaded['yes'].append(mod)
continue
load_result = __salt__['kmod.load'](mod, persist)
if isinstance(load_result, (list, tuple)):
if load_result:
for module in load_result:
ret['changes'][module] = 'loaded'
if module != mod:
loaded_by_dependency.append(module)
loaded['yes'].append(mod)
else:
ret['result'] = False
loaded['no'].append(mod)
else:
ret['result'] = False
loaded['failed'].append([mod, load_result])
# Update comment with results
if len(loaded['yes']) == 1:
_append_comment(ret, 'Loaded kernel module {0}'.format(loaded['yes'][0]))
elif len(loaded['yes']) > 1:
_append_comment(ret, 'Loaded kernel modules {0}'.format(', '.join(loaded['yes'])))
if len(loaded['no']) == 1:
_append_comment(ret, 'Failed to load kernel module {0}'.format(loaded['no'][0]))
if len(loaded['no']) > 1:
_append_comment(ret, 'Failed to load kernel modules {0}'.format(', '.join(loaded['no'])))
if loaded['failed']:
for mod, msg in loaded['failed']:
_append_comment(ret, 'Failed to load kernel module {0}: {1}'.format(mod, msg))
return ret | python | def present(name, persist=False, mods=None):
'''
Ensure that the specified kernel module is loaded
name
The name of the kernel module to verify is loaded
persist
Also add module to ``/etc/modules``
mods
A list of modules to verify are loaded. If this argument is used, the
``name`` argument, although still required, is not used, and becomes a
placeholder
.. versionadded:: 2016.3.0
'''
if not isinstance(mods, (list, tuple)):
mods = [name]
ret = {'name': name,
'result': True,
'changes': {},
'comment': ''}
loaded_mods = __salt__['kmod.mod_list']()
if persist:
persist_mods = __salt__['kmod.mod_list'](True)
# Intersection of loaded modules and persistent modules
loaded_mods = list(set(loaded_mods) & set(persist_mods))
# Intersection of loaded and proposed modules
already_loaded = list(set(loaded_mods) & set(mods))
if len(already_loaded) == 1:
comment = 'Kernel module {0} is already present'.format(already_loaded[0])
_append_comment(ret, comment)
elif len(already_loaded) > 1:
comment = 'Kernel modules {0} are already present'.format(', '.join(already_loaded))
_append_comment(ret, comment)
if len(already_loaded) == len(mods):
return ret # all modules already loaded
# Complement of proposed modules and already loaded modules
not_loaded = list(set(mods) - set(already_loaded))
if __opts__['test']:
ret['result'] = None
if ret['comment']:
ret['comment'] += '\n'
if len(not_loaded) == 1:
comment = 'Kernel module {0} is set to be loaded'.format(not_loaded[0])
else:
comment = 'Kernel modules {0} are set to be loaded'.format(', '.join(not_loaded))
_append_comment(ret, comment)
return ret
# Complement of proposed, unloaded modules and available modules
unavailable = list(set(not_loaded) - set(__salt__['kmod.available']()))
if unavailable:
if len(unavailable) == 1:
comment = 'Kernel module {0} is unavailable'.format(unavailable[0])
else:
comment = 'Kernel modules {0} are unavailable'.format(', '.join(unavailable))
_append_comment(ret, comment)
ret['result'] = False
# The remaining modules are not loaded and are available for loading
available = list(set(not_loaded) - set(unavailable))
loaded = {'yes': [], 'no': [], 'failed': []}
loaded_by_dependency = []
for mod in available:
if mod in loaded_by_dependency:
loaded['yes'].append(mod)
continue
load_result = __salt__['kmod.load'](mod, persist)
if isinstance(load_result, (list, tuple)):
if load_result:
for module in load_result:
ret['changes'][module] = 'loaded'
if module != mod:
loaded_by_dependency.append(module)
loaded['yes'].append(mod)
else:
ret['result'] = False
loaded['no'].append(mod)
else:
ret['result'] = False
loaded['failed'].append([mod, load_result])
# Update comment with results
if len(loaded['yes']) == 1:
_append_comment(ret, 'Loaded kernel module {0}'.format(loaded['yes'][0]))
elif len(loaded['yes']) > 1:
_append_comment(ret, 'Loaded kernel modules {0}'.format(', '.join(loaded['yes'])))
if len(loaded['no']) == 1:
_append_comment(ret, 'Failed to load kernel module {0}'.format(loaded['no'][0]))
if len(loaded['no']) > 1:
_append_comment(ret, 'Failed to load kernel modules {0}'.format(', '.join(loaded['no'])))
if loaded['failed']:
for mod, msg in loaded['failed']:
_append_comment(ret, 'Failed to load kernel module {0}: {1}'.format(mod, msg))
return ret | [
"def",
"present",
"(",
"name",
",",
"persist",
"=",
"False",
",",
"mods",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"mods",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"mods",
"=",
"[",
"name",
"]",
"ret",
"=",
"{",
"'name'",
":... | Ensure that the specified kernel module is loaded
name
The name of the kernel module to verify is loaded
persist
Also add module to ``/etc/modules``
mods
A list of modules to verify are loaded. If this argument is used, the
``name`` argument, although still required, is not used, and becomes a
placeholder
.. versionadded:: 2016.3.0 | [
"Ensure",
"that",
"the",
"specified",
"kernel",
"module",
"is",
"loaded"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/kmod.py#L55-L159 | train |
saltstack/salt | salt/states/kmod.py | absent | def absent(name, persist=False, comment=True, mods=None):
'''
Verify that the named kernel module is not loaded
name
The name of the kernel module to verify is not loaded
persist
Remove module from ``/etc/modules``
comment
Comment out module in ``/etc/modules`` rather than remove it
mods
A list of modules to verify are unloaded. If this argument is used,
the ``name`` argument, although still required, is not used, and
becomes a placeholder
.. versionadded:: 2016.3.0
'''
if not isinstance(mods, (list, tuple)):
mods = [name]
ret = {'name': name,
'result': True,
'changes': {},
'comment': ''}
loaded_mods = __salt__['kmod.mod_list']()
if persist:
persist_mods = __salt__['kmod.mod_list'](True)
# Union of loaded modules and persistent modules
loaded_mods = list(set(loaded_mods) | set(persist_mods))
# Intersection of proposed modules and loaded modules
to_unload = list(set(mods) & set(loaded_mods))
if to_unload:
if __opts__['test']:
ret['result'] = None
if len(to_unload) == 1:
_append_comment(ret, 'Kernel module {0} is set to be removed'.format(to_unload[0]))
elif len(to_unload) > 1:
_append_comment(ret, 'Kernel modules {0} are set to be removed'.format(', '.join(to_unload)))
return ret
# Unload modules and collect results
unloaded = {'yes': [], 'no': [], 'failed': []}
for mod in to_unload:
unload_result = __salt__['kmod.remove'](mod, persist, comment)
if isinstance(unload_result, (list, tuple)):
if unload_result:
for module in unload_result:
ret['changes'][module] = 'removed'
unloaded['yes'].append(mod)
else:
ret['result'] = False
unloaded['no'].append(mod)
else:
ret['result'] = False
unloaded['failed'].append([mod, unload_result])
# Update comment with results
if len(unloaded['yes']) == 1:
_append_comment(ret, 'Removed kernel module {0}'.format(unloaded['yes'][0]))
elif len(unloaded['yes']) > 1:
_append_comment(ret, 'Removed kernel modules {0}'.format(', '.join(unloaded['yes'])))
if len(unloaded['no']) == 1:
_append_comment(ret, 'Failed to remove kernel module {0}'.format(unloaded['no'][0]))
if len(unloaded['no']) > 1:
_append_comment(ret, 'Failed to remove kernel modules {0}'.format(', '.join(unloaded['no'])))
if unloaded['failed']:
for mod, msg in unloaded['failed']:
_append_comment(ret, 'Failed to remove kernel module {0}: {1}'.format(mod, msg))
return ret
else:
if len(mods) == 1:
ret['comment'] = 'Kernel module {0} is already removed'.format(mods[0])
else:
ret['comment'] = 'Kernel modules {0} are already removed'.format(', '.join(mods))
return ret | python | def absent(name, persist=False, comment=True, mods=None):
'''
Verify that the named kernel module is not loaded
name
The name of the kernel module to verify is not loaded
persist
Remove module from ``/etc/modules``
comment
Comment out module in ``/etc/modules`` rather than remove it
mods
A list of modules to verify are unloaded. If this argument is used,
the ``name`` argument, although still required, is not used, and
becomes a placeholder
.. versionadded:: 2016.3.0
'''
if not isinstance(mods, (list, tuple)):
mods = [name]
ret = {'name': name,
'result': True,
'changes': {},
'comment': ''}
loaded_mods = __salt__['kmod.mod_list']()
if persist:
persist_mods = __salt__['kmod.mod_list'](True)
# Union of loaded modules and persistent modules
loaded_mods = list(set(loaded_mods) | set(persist_mods))
# Intersection of proposed modules and loaded modules
to_unload = list(set(mods) & set(loaded_mods))
if to_unload:
if __opts__['test']:
ret['result'] = None
if len(to_unload) == 1:
_append_comment(ret, 'Kernel module {0} is set to be removed'.format(to_unload[0]))
elif len(to_unload) > 1:
_append_comment(ret, 'Kernel modules {0} are set to be removed'.format(', '.join(to_unload)))
return ret
# Unload modules and collect results
unloaded = {'yes': [], 'no': [], 'failed': []}
for mod in to_unload:
unload_result = __salt__['kmod.remove'](mod, persist, comment)
if isinstance(unload_result, (list, tuple)):
if unload_result:
for module in unload_result:
ret['changes'][module] = 'removed'
unloaded['yes'].append(mod)
else:
ret['result'] = False
unloaded['no'].append(mod)
else:
ret['result'] = False
unloaded['failed'].append([mod, unload_result])
# Update comment with results
if len(unloaded['yes']) == 1:
_append_comment(ret, 'Removed kernel module {0}'.format(unloaded['yes'][0]))
elif len(unloaded['yes']) > 1:
_append_comment(ret, 'Removed kernel modules {0}'.format(', '.join(unloaded['yes'])))
if len(unloaded['no']) == 1:
_append_comment(ret, 'Failed to remove kernel module {0}'.format(unloaded['no'][0]))
if len(unloaded['no']) > 1:
_append_comment(ret, 'Failed to remove kernel modules {0}'.format(', '.join(unloaded['no'])))
if unloaded['failed']:
for mod, msg in unloaded['failed']:
_append_comment(ret, 'Failed to remove kernel module {0}: {1}'.format(mod, msg))
return ret
else:
if len(mods) == 1:
ret['comment'] = 'Kernel module {0} is already removed'.format(mods[0])
else:
ret['comment'] = 'Kernel modules {0} are already removed'.format(', '.join(mods))
return ret | [
"def",
"absent",
"(",
"name",
",",
"persist",
"=",
"False",
",",
"comment",
"=",
"True",
",",
"mods",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"mods",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"mods",
"=",
"[",
"name",
"]",
"... | Verify that the named kernel module is not loaded
name
The name of the kernel module to verify is not loaded
persist
Remove module from ``/etc/modules``
comment
Comment out module in ``/etc/modules`` rather than remove it
mods
A list of modules to verify are unloaded. If this argument is used,
the ``name`` argument, although still required, is not used, and
becomes a placeholder
.. versionadded:: 2016.3.0 | [
"Verify",
"that",
"the",
"named",
"kernel",
"module",
"is",
"not",
"loaded"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/kmod.py#L162-L245 | train |
saltstack/salt | salt/runners/lxc.py | _do | def _do(name, fun, path=None):
'''
Invoke a function in the lxc module with no args
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
'''
host = find_guest(name, quiet=True, path=path)
if not host:
return False
client = salt.client.get_local_client(__opts__['conf_file'])
cmd_ret = client.cmd_iter(
host,
'lxc.{0}'.format(fun),
[name],
kwarg={'path': path},
timeout=60)
data = next(cmd_ret)
data = data.get(host, {}).get('ret', None)
if data:
data = {host: data}
return data | python | def _do(name, fun, path=None):
'''
Invoke a function in the lxc module with no args
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
'''
host = find_guest(name, quiet=True, path=path)
if not host:
return False
client = salt.client.get_local_client(__opts__['conf_file'])
cmd_ret = client.cmd_iter(
host,
'lxc.{0}'.format(fun),
[name],
kwarg={'path': path},
timeout=60)
data = next(cmd_ret)
data = data.get(host, {}).get('ret', None)
if data:
data = {host: data}
return data | [
"def",
"_do",
"(",
"name",
",",
"fun",
",",
"path",
"=",
"None",
")",
":",
"host",
"=",
"find_guest",
"(",
"name",
",",
"quiet",
"=",
"True",
",",
"path",
"=",
"path",
")",
"if",
"not",
"host",
":",
"return",
"False",
"client",
"=",
"salt",
".",
... | Invoke a function in the lxc module with no args
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0 | [
"Invoke",
"a",
"function",
"in",
"the",
"lxc",
"module",
"with",
"no",
"args"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/lxc.py#L36-L61 | train |
saltstack/salt | salt/runners/lxc.py | _do_names | def _do_names(names, fun, path=None):
'''
Invoke a function in the lxc module with no args
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
'''
ret = {}
hosts = find_guests(names, path=path)
if not hosts:
return False
client = salt.client.get_local_client(__opts__['conf_file'])
for host, sub_names in six.iteritems(hosts):
cmds = []
for name in sub_names:
cmds.append(client.cmd_iter(
host,
'lxc.{0}'.format(fun),
[name],
kwarg={'path': path},
timeout=60))
for cmd in cmds:
data = next(cmd)
data = data.get(host, {}).get('ret', None)
if data:
ret.update({host: data})
return ret | python | def _do_names(names, fun, path=None):
'''
Invoke a function in the lxc module with no args
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
'''
ret = {}
hosts = find_guests(names, path=path)
if not hosts:
return False
client = salt.client.get_local_client(__opts__['conf_file'])
for host, sub_names in six.iteritems(hosts):
cmds = []
for name in sub_names:
cmds.append(client.cmd_iter(
host,
'lxc.{0}'.format(fun),
[name],
kwarg={'path': path},
timeout=60))
for cmd in cmds:
data = next(cmd)
data = data.get(host, {}).get('ret', None)
if data:
ret.update({host: data})
return ret | [
"def",
"_do_names",
"(",
"names",
",",
"fun",
",",
"path",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"}",
"hosts",
"=",
"find_guests",
"(",
"names",
",",
"path",
"=",
"path",
")",
"if",
"not",
"hosts",
":",
"return",
"False",
"client",
"=",
"salt",
... | Invoke a function in the lxc module with no args
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0 | [
"Invoke",
"a",
"function",
"in",
"the",
"lxc",
"module",
"with",
"no",
"args"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/lxc.py#L64-L94 | train |
saltstack/salt | salt/runners/lxc.py | find_guest | def find_guest(name, quiet=False, path=None):
'''
Returns the host for a container.
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
.. code-block:: bash
salt-run lxc.find_guest name
'''
if quiet:
log.warning("'quiet' argument is being deprecated."
' Please migrate to --quiet')
for data in _list_iter(path=path):
host, l = next(six.iteritems(data))
for x in 'running', 'frozen', 'stopped':
if name in l[x]:
if not quiet:
__jid_event__.fire_event(
{'data': host,
'outputter': 'lxc_find_host'},
'progress')
return host
return None | python | def find_guest(name, quiet=False, path=None):
'''
Returns the host for a container.
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
.. code-block:: bash
salt-run lxc.find_guest name
'''
if quiet:
log.warning("'quiet' argument is being deprecated."
' Please migrate to --quiet')
for data in _list_iter(path=path):
host, l = next(six.iteritems(data))
for x in 'running', 'frozen', 'stopped':
if name in l[x]:
if not quiet:
__jid_event__.fire_event(
{'data': host,
'outputter': 'lxc_find_host'},
'progress')
return host
return None | [
"def",
"find_guest",
"(",
"name",
",",
"quiet",
"=",
"False",
",",
"path",
"=",
"None",
")",
":",
"if",
"quiet",
":",
"log",
".",
"warning",
"(",
"\"'quiet' argument is being deprecated.\"",
"' Please migrate to --quiet'",
")",
"for",
"data",
"in",
"_list_iter",... | Returns the host for a container.
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
.. code-block:: bash
salt-run lxc.find_guest name | [
"Returns",
"the",
"host",
"for",
"a",
"container",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/lxc.py#L97-L125 | train |
saltstack/salt | salt/runners/lxc.py | find_guests | def find_guests(names, path=None):
'''
Return a dict of hosts and named guests
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
'''
ret = {}
names = names.split(',')
for data in _list_iter(path=path):
host, stat = next(six.iteritems(data))
for state in stat:
for name in stat[state]:
if name in names:
if host in ret:
ret[host].append(name)
else:
ret[host] = [name]
return ret | python | def find_guests(names, path=None):
'''
Return a dict of hosts and named guests
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
'''
ret = {}
names = names.split(',')
for data in _list_iter(path=path):
host, stat = next(six.iteritems(data))
for state in stat:
for name in stat[state]:
if name in names:
if host in ret:
ret[host].append(name)
else:
ret[host] = [name]
return ret | [
"def",
"find_guests",
"(",
"names",
",",
"path",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"}",
"names",
"=",
"names",
".",
"split",
"(",
"','",
")",
"for",
"data",
"in",
"_list_iter",
"(",
"path",
"=",
"path",
")",
":",
"host",
",",
"stat",
"=",
... | Return a dict of hosts and named guests
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0 | [
"Return",
"a",
"dict",
"of",
"hosts",
"and",
"named",
"guests"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/lxc.py#L128-L150 | train |
saltstack/salt | salt/runners/lxc.py | init | def init(names, host=None, saltcloud_mode=False, quiet=False, **kwargs):
'''
Initialize a new container
.. code-block:: bash
salt-run lxc.init name host=minion_id [cpuset=cgroups_cpuset] \\
[cpushare=cgroups_cpushare] [memory=cgroups_memory] \\
[template=lxc_template_name] [clone=original name] \\
[profile=lxc_profile] [network_proflile=network_profile] \\
[nic=network_profile] [nic_opts=nic_opts] \\
[start=(true|false)] [seed=(true|false)] \\
[install=(true|false)] [config=minion_config] \\
[snapshot=(true|false)]
names
Name of the containers, supports a single name or a comma delimited
list of names.
host
Minion on which to initialize the container **(required)**
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
saltcloud_mode
init the container with the saltcloud opts format instead
See lxc.init_interface module documentation
cpuset
cgroups cpuset.
cpushare
cgroups cpu shares.
memory
cgroups memory limit, in MB
.. versionchanged:: 2015.5.0
If no value is passed, no limit is set. In earlier Salt versions,
not passing this value causes a 1024MB memory limit to be set, and
it was necessary to pass ``memory=0`` to set no limit.
template
Name of LXC template on which to base this container
clone
Clone this container from an existing container
profile
A LXC profile (defined in config or pillar).
network_profile
Network profile to use for the container
.. versionadded:: 2015.5.2
nic
.. deprecated:: 2015.5.0
Use ``network_profile`` instead
nic_opts
Extra options for network interfaces. E.g.:
``{"eth0": {"mac": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1", "ipv6": "2001:db8::ff00:42:8329"}}``
start
Start the newly created container.
seed
Seed the container with the minion config and autosign its key.
Default: true
install
If salt-minion is not already installed, install it. Default: true
config
Optional config parameters. By default, the id is set to
the name of the container.
'''
path = kwargs.get('path', None)
if quiet:
log.warning("'quiet' argument is being deprecated."
' Please migrate to --quiet')
ret = {'comment': '', 'result': True}
if host is None:
# TODO: Support selection of host based on available memory/cpu/etc.
ret['comment'] = 'A host must be provided'
ret['result'] = False
return ret
if isinstance(names, six.string_types):
names = names.split(',')
if not isinstance(names, list):
ret['comment'] = 'Container names are not formed as a list'
ret['result'] = False
return ret
# check that the host is alive
client = salt.client.get_local_client(__opts__['conf_file'])
alive = False
try:
if client.cmd(host, 'test.ping', timeout=20).get(host, None):
alive = True
except (TypeError, KeyError):
pass
if not alive:
ret['comment'] = 'Host {0} is not reachable'.format(host)
ret['result'] = False
return ret
log.info('Searching for LXC Hosts')
data = __salt__['lxc.list'](host, quiet=True, path=path)
for host, containers in six.iteritems(data):
for name in names:
if name in sum(six.itervalues(containers), []):
log.info(
'Container \'%s\' already exists on host \'%s\', init '
'can be a NO-OP', name, host
)
if host not in data:
ret['comment'] = 'Host \'{0}\' was not found'.format(host)
ret['result'] = False
return ret
kw = salt.utils.args.clean_kwargs(**kwargs)
pub_key = kw.get('pub_key', None)
priv_key = kw.get('priv_key', None)
explicit_auth = pub_key and priv_key
approve_key = kw.get('approve_key', True)
seeds = {}
seed_arg = kwargs.get('seed', True)
if approve_key and not explicit_auth:
skey = salt.key.Key(__opts__)
all_minions = skey.all_keys().get('minions', [])
for name in names:
seed = seed_arg
if name in all_minions:
try:
if client.cmd(name, 'test.ping', timeout=20).get(name, None):
seed = False
except (TypeError, KeyError):
pass
seeds[name] = seed
kv = salt.utils.virt.VirtKey(host, name, __opts__)
if kv.authorize():
log.info('Container key will be preauthorized')
else:
ret['comment'] = 'Container key preauthorization failed'
ret['result'] = False
return ret
log.info('Creating container(s) \'%s\' on host \'%s\'', names, host)
cmds = []
for name in names:
args = [name]
kw = salt.utils.args.clean_kwargs(**kwargs)
if saltcloud_mode:
kw = copy.deepcopy(kw)
kw['name'] = name
saved_kwargs = kw
kw = client.cmd(
host, 'lxc.cloud_init_interface', args + [kw],
tgt_type='list', timeout=600).get(host, {})
kw.update(saved_kwargs)
name = kw.pop('name', name)
# be sure not to seed an already seeded host
kw['seed'] = seeds.get(name, seed_arg)
if not kw['seed']:
kw.pop('seed_cmd', '')
cmds.append(
(host,
name,
client.cmd_iter(host, 'lxc.init', args, kwarg=kw, timeout=600)))
done = ret.setdefault('done', [])
errors = ret.setdefault('errors', _OrderedDict())
for ix, acmd in enumerate(cmds):
hst, container_name, cmd = acmd
containers = ret.setdefault(hst, [])
herrs = errors.setdefault(hst, _OrderedDict())
serrs = herrs.setdefault(container_name, [])
sub_ret = next(cmd)
error = None
if isinstance(sub_ret, dict) and host in sub_ret:
j_ret = sub_ret[hst]
container = j_ret.get('ret', {})
if container and isinstance(container, dict):
if not container.get('result', False):
error = container
else:
error = 'Invalid return for {0}: {1} {2}'.format(
container_name, container, sub_ret)
else:
error = sub_ret
if not error:
error = 'unknown error (no return)'
if error:
ret['result'] = False
serrs.append(error)
else:
container['container_name'] = name
containers.append(container)
done.append(container)
# marking ping status as True only and only if we have at
# least provisioned one container
ret['ping_status'] = bool(len(done))
# for all provisioned containers, last job is to verify
# - the key status
# - we can reach them
for container in done:
# explicitly check and update
# the minion key/pair stored on the master
container_name = container['container_name']
key = os.path.join(__opts__['pki_dir'], 'minions', container_name)
if explicit_auth:
fcontent = ''
if os.path.exists(key):
with salt.utils.files.fopen(key) as fic:
fcontent = salt.utils.stringutils.to_unicode(fic.read()).strip()
pub_key = salt.utils.stringutils.to_unicode(pub_key)
if pub_key.strip() != fcontent:
with salt.utils.files.fopen(key, 'w') as fic:
fic.write(salt.utils.stringutils.to_str(pub_key))
fic.flush()
mid = j_ret.get('mid', None)
if not mid:
continue
def testping(**kw):
mid_ = kw['mid']
ping = client.cmd(mid_, 'test.ping', timeout=20)
time.sleep(1)
if ping:
return 'OK'
raise Exception('Unresponsive {0}'.format(mid_))
ping = salt.utils.cloud.wait_for_fun(testping, timeout=21, mid=mid)
if ping != 'OK':
ret['ping_status'] = False
ret['result'] = False
# if no lxc detected as touched (either inited or verified)
# we result to False
if not done:
ret['result'] = False
if not quiet:
__jid_event__.fire_event({'message': ret}, 'progress')
return ret | python | def init(names, host=None, saltcloud_mode=False, quiet=False, **kwargs):
'''
Initialize a new container
.. code-block:: bash
salt-run lxc.init name host=minion_id [cpuset=cgroups_cpuset] \\
[cpushare=cgroups_cpushare] [memory=cgroups_memory] \\
[template=lxc_template_name] [clone=original name] \\
[profile=lxc_profile] [network_proflile=network_profile] \\
[nic=network_profile] [nic_opts=nic_opts] \\
[start=(true|false)] [seed=(true|false)] \\
[install=(true|false)] [config=minion_config] \\
[snapshot=(true|false)]
names
Name of the containers, supports a single name or a comma delimited
list of names.
host
Minion on which to initialize the container **(required)**
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
saltcloud_mode
init the container with the saltcloud opts format instead
See lxc.init_interface module documentation
cpuset
cgroups cpuset.
cpushare
cgroups cpu shares.
memory
cgroups memory limit, in MB
.. versionchanged:: 2015.5.0
If no value is passed, no limit is set. In earlier Salt versions,
not passing this value causes a 1024MB memory limit to be set, and
it was necessary to pass ``memory=0`` to set no limit.
template
Name of LXC template on which to base this container
clone
Clone this container from an existing container
profile
A LXC profile (defined in config or pillar).
network_profile
Network profile to use for the container
.. versionadded:: 2015.5.2
nic
.. deprecated:: 2015.5.0
Use ``network_profile`` instead
nic_opts
Extra options for network interfaces. E.g.:
``{"eth0": {"mac": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1", "ipv6": "2001:db8::ff00:42:8329"}}``
start
Start the newly created container.
seed
Seed the container with the minion config and autosign its key.
Default: true
install
If salt-minion is not already installed, install it. Default: true
config
Optional config parameters. By default, the id is set to
the name of the container.
'''
path = kwargs.get('path', None)
if quiet:
log.warning("'quiet' argument is being deprecated."
' Please migrate to --quiet')
ret = {'comment': '', 'result': True}
if host is None:
# TODO: Support selection of host based on available memory/cpu/etc.
ret['comment'] = 'A host must be provided'
ret['result'] = False
return ret
if isinstance(names, six.string_types):
names = names.split(',')
if not isinstance(names, list):
ret['comment'] = 'Container names are not formed as a list'
ret['result'] = False
return ret
# check that the host is alive
client = salt.client.get_local_client(__opts__['conf_file'])
alive = False
try:
if client.cmd(host, 'test.ping', timeout=20).get(host, None):
alive = True
except (TypeError, KeyError):
pass
if not alive:
ret['comment'] = 'Host {0} is not reachable'.format(host)
ret['result'] = False
return ret
log.info('Searching for LXC Hosts')
data = __salt__['lxc.list'](host, quiet=True, path=path)
for host, containers in six.iteritems(data):
for name in names:
if name in sum(six.itervalues(containers), []):
log.info(
'Container \'%s\' already exists on host \'%s\', init '
'can be a NO-OP', name, host
)
if host not in data:
ret['comment'] = 'Host \'{0}\' was not found'.format(host)
ret['result'] = False
return ret
kw = salt.utils.args.clean_kwargs(**kwargs)
pub_key = kw.get('pub_key', None)
priv_key = kw.get('priv_key', None)
explicit_auth = pub_key and priv_key
approve_key = kw.get('approve_key', True)
seeds = {}
seed_arg = kwargs.get('seed', True)
if approve_key and not explicit_auth:
skey = salt.key.Key(__opts__)
all_minions = skey.all_keys().get('minions', [])
for name in names:
seed = seed_arg
if name in all_minions:
try:
if client.cmd(name, 'test.ping', timeout=20).get(name, None):
seed = False
except (TypeError, KeyError):
pass
seeds[name] = seed
kv = salt.utils.virt.VirtKey(host, name, __opts__)
if kv.authorize():
log.info('Container key will be preauthorized')
else:
ret['comment'] = 'Container key preauthorization failed'
ret['result'] = False
return ret
log.info('Creating container(s) \'%s\' on host \'%s\'', names, host)
cmds = []
for name in names:
args = [name]
kw = salt.utils.args.clean_kwargs(**kwargs)
if saltcloud_mode:
kw = copy.deepcopy(kw)
kw['name'] = name
saved_kwargs = kw
kw = client.cmd(
host, 'lxc.cloud_init_interface', args + [kw],
tgt_type='list', timeout=600).get(host, {})
kw.update(saved_kwargs)
name = kw.pop('name', name)
# be sure not to seed an already seeded host
kw['seed'] = seeds.get(name, seed_arg)
if not kw['seed']:
kw.pop('seed_cmd', '')
cmds.append(
(host,
name,
client.cmd_iter(host, 'lxc.init', args, kwarg=kw, timeout=600)))
done = ret.setdefault('done', [])
errors = ret.setdefault('errors', _OrderedDict())
for ix, acmd in enumerate(cmds):
hst, container_name, cmd = acmd
containers = ret.setdefault(hst, [])
herrs = errors.setdefault(hst, _OrderedDict())
serrs = herrs.setdefault(container_name, [])
sub_ret = next(cmd)
error = None
if isinstance(sub_ret, dict) and host in sub_ret:
j_ret = sub_ret[hst]
container = j_ret.get('ret', {})
if container and isinstance(container, dict):
if not container.get('result', False):
error = container
else:
error = 'Invalid return for {0}: {1} {2}'.format(
container_name, container, sub_ret)
else:
error = sub_ret
if not error:
error = 'unknown error (no return)'
if error:
ret['result'] = False
serrs.append(error)
else:
container['container_name'] = name
containers.append(container)
done.append(container)
# marking ping status as True only and only if we have at
# least provisioned one container
ret['ping_status'] = bool(len(done))
# for all provisioned containers, last job is to verify
# - the key status
# - we can reach them
for container in done:
# explicitly check and update
# the minion key/pair stored on the master
container_name = container['container_name']
key = os.path.join(__opts__['pki_dir'], 'minions', container_name)
if explicit_auth:
fcontent = ''
if os.path.exists(key):
with salt.utils.files.fopen(key) as fic:
fcontent = salt.utils.stringutils.to_unicode(fic.read()).strip()
pub_key = salt.utils.stringutils.to_unicode(pub_key)
if pub_key.strip() != fcontent:
with salt.utils.files.fopen(key, 'w') as fic:
fic.write(salt.utils.stringutils.to_str(pub_key))
fic.flush()
mid = j_ret.get('mid', None)
if not mid:
continue
def testping(**kw):
mid_ = kw['mid']
ping = client.cmd(mid_, 'test.ping', timeout=20)
time.sleep(1)
if ping:
return 'OK'
raise Exception('Unresponsive {0}'.format(mid_))
ping = salt.utils.cloud.wait_for_fun(testping, timeout=21, mid=mid)
if ping != 'OK':
ret['ping_status'] = False
ret['result'] = False
# if no lxc detected as touched (either inited or verified)
# we result to False
if not done:
ret['result'] = False
if not quiet:
__jid_event__.fire_event({'message': ret}, 'progress')
return ret | [
"def",
"init",
"(",
"names",
",",
"host",
"=",
"None",
",",
"saltcloud_mode",
"=",
"False",
",",
"quiet",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"path",
"=",
"kwargs",
".",
"get",
"(",
"'path'",
",",
"None",
")",
"if",
"quiet",
":",
"lo... | Initialize a new container
.. code-block:: bash
salt-run lxc.init name host=minion_id [cpuset=cgroups_cpuset] \\
[cpushare=cgroups_cpushare] [memory=cgroups_memory] \\
[template=lxc_template_name] [clone=original name] \\
[profile=lxc_profile] [network_proflile=network_profile] \\
[nic=network_profile] [nic_opts=nic_opts] \\
[start=(true|false)] [seed=(true|false)] \\
[install=(true|false)] [config=minion_config] \\
[snapshot=(true|false)]
names
Name of the containers, supports a single name or a comma delimited
list of names.
host
Minion on which to initialize the container **(required)**
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
saltcloud_mode
init the container with the saltcloud opts format instead
See lxc.init_interface module documentation
cpuset
cgroups cpuset.
cpushare
cgroups cpu shares.
memory
cgroups memory limit, in MB
.. versionchanged:: 2015.5.0
If no value is passed, no limit is set. In earlier Salt versions,
not passing this value causes a 1024MB memory limit to be set, and
it was necessary to pass ``memory=0`` to set no limit.
template
Name of LXC template on which to base this container
clone
Clone this container from an existing container
profile
A LXC profile (defined in config or pillar).
network_profile
Network profile to use for the container
.. versionadded:: 2015.5.2
nic
.. deprecated:: 2015.5.0
Use ``network_profile`` instead
nic_opts
Extra options for network interfaces. E.g.:
``{"eth0": {"mac": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1", "ipv6": "2001:db8::ff00:42:8329"}}``
start
Start the newly created container.
seed
Seed the container with the minion config and autosign its key.
Default: true
install
If salt-minion is not already installed, install it. Default: true
config
Optional config parameters. By default, the id is set to
the name of the container. | [
"Initialize",
"a",
"new",
"container"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/lxc.py#L153-L405 | train |
saltstack/salt | salt/runners/lxc.py | cloud_init | def cloud_init(names, host=None, quiet=False, **kwargs):
'''
Wrapper for using lxc.init in saltcloud compatibility mode
names
Name of the containers, supports a single name or a comma delimited
list of names.
host
Minion to start the container on. Required.
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
saltcloud_mode
init the container with the saltcloud opts format instead
'''
if quiet:
log.warning("'quiet' argument is being deprecated. Please migrate to --quiet")
return __salt__['lxc.init'](names=names, host=host,
saltcloud_mode=True, quiet=quiet, **kwargs) | python | def cloud_init(names, host=None, quiet=False, **kwargs):
'''
Wrapper for using lxc.init in saltcloud compatibility mode
names
Name of the containers, supports a single name or a comma delimited
list of names.
host
Minion to start the container on. Required.
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
saltcloud_mode
init the container with the saltcloud opts format instead
'''
if quiet:
log.warning("'quiet' argument is being deprecated. Please migrate to --quiet")
return __salt__['lxc.init'](names=names, host=host,
saltcloud_mode=True, quiet=quiet, **kwargs) | [
"def",
"cloud_init",
"(",
"names",
",",
"host",
"=",
"None",
",",
"quiet",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"quiet",
":",
"log",
".",
"warning",
"(",
"\"'quiet' argument is being deprecated. Please migrate to --quiet\"",
")",
"return",
"_... | Wrapper for using lxc.init in saltcloud compatibility mode
names
Name of the containers, supports a single name or a comma delimited
list of names.
host
Minion to start the container on. Required.
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
saltcloud_mode
init the container with the saltcloud opts format instead | [
"Wrapper",
"for",
"using",
"lxc",
".",
"init",
"in",
"saltcloud",
"compatibility",
"mode"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/lxc.py#L408-L431 | train |
saltstack/salt | salt/runners/lxc.py | _list_iter | def _list_iter(host=None, path=None):
'''
Return a generator iterating over hosts
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
'''
tgt = host or '*'
client = salt.client.get_local_client(__opts__['conf_file'])
for container_info in client.cmd_iter(
tgt, 'lxc.list', kwarg={'path': path}
):
if not container_info:
continue
if not isinstance(container_info, dict):
continue
chunk = {}
id_ = next(six.iterkeys(container_info))
if host and host != id_:
continue
if not isinstance(container_info[id_], dict):
continue
if 'ret' not in container_info[id_]:
continue
if not isinstance(container_info[id_]['ret'], dict):
continue
chunk[id_] = container_info[id_]['ret']
yield chunk | python | def _list_iter(host=None, path=None):
'''
Return a generator iterating over hosts
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
'''
tgt = host or '*'
client = salt.client.get_local_client(__opts__['conf_file'])
for container_info in client.cmd_iter(
tgt, 'lxc.list', kwarg={'path': path}
):
if not container_info:
continue
if not isinstance(container_info, dict):
continue
chunk = {}
id_ = next(six.iterkeys(container_info))
if host and host != id_:
continue
if not isinstance(container_info[id_], dict):
continue
if 'ret' not in container_info[id_]:
continue
if not isinstance(container_info[id_]['ret'], dict):
continue
chunk[id_] = container_info[id_]['ret']
yield chunk | [
"def",
"_list_iter",
"(",
"host",
"=",
"None",
",",
"path",
"=",
"None",
")",
":",
"tgt",
"=",
"host",
"or",
"'*'",
"client",
"=",
"salt",
".",
"client",
".",
"get_local_client",
"(",
"__opts__",
"[",
"'conf_file'",
"]",
")",
"for",
"container_info",
"... | Return a generator iterating over hosts
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0 | [
"Return",
"a",
"generator",
"iterating",
"over",
"hosts"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/lxc.py#L434-L464 | train |
saltstack/salt | salt/runners/lxc.py | list_ | def list_(host=None, quiet=False, path=None):
'''
List defined containers (running, stopped, and frozen) for the named
(or all) host(s).
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
.. code-block:: bash
salt-run lxc.list [host=minion_id]
'''
it = _list_iter(host, path=path)
ret = {}
for chunk in it:
ret.update(chunk)
if not quiet:
__jid_event__.fire_event(
{'data': chunk, 'outputter': 'lxc_list'}, 'progress')
return ret | python | def list_(host=None, quiet=False, path=None):
'''
List defined containers (running, stopped, and frozen) for the named
(or all) host(s).
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
.. code-block:: bash
salt-run lxc.list [host=minion_id]
'''
it = _list_iter(host, path=path)
ret = {}
for chunk in it:
ret.update(chunk)
if not quiet:
__jid_event__.fire_event(
{'data': chunk, 'outputter': 'lxc_list'}, 'progress')
return ret | [
"def",
"list_",
"(",
"host",
"=",
"None",
",",
"quiet",
"=",
"False",
",",
"path",
"=",
"None",
")",
":",
"it",
"=",
"_list_iter",
"(",
"host",
",",
"path",
"=",
"path",
")",
"ret",
"=",
"{",
"}",
"for",
"chunk",
"in",
"it",
":",
"ret",
".",
... | List defined containers (running, stopped, and frozen) for the named
(or all) host(s).
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
.. code-block:: bash
salt-run lxc.list [host=minion_id] | [
"List",
"defined",
"containers",
"(",
"running",
"stopped",
"and",
"frozen",
")",
"for",
"the",
"named",
"(",
"or",
"all",
")",
"host",
"(",
"s",
")",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/lxc.py#L467-L489 | train |
saltstack/salt | salt/runners/lxc.py | purge | def purge(name, delete_key=True, quiet=False, path=None):
'''
Purge the named container and delete its minion key if present.
WARNING: Destroys all data associated with the container.
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
.. code-block:: bash
salt-run lxc.purge name
'''
data = _do_names(name, 'destroy', path=path)
if data is False:
return data
if delete_key:
skey = salt.key.Key(__opts__)
skey.delete_key(name)
if data is None:
return
if not quiet:
__jid_event__.fire_event(
{'data': data, 'outputter': 'lxc_purge'}, 'progress')
return data | python | def purge(name, delete_key=True, quiet=False, path=None):
'''
Purge the named container and delete its minion key if present.
WARNING: Destroys all data associated with the container.
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
.. code-block:: bash
salt-run lxc.purge name
'''
data = _do_names(name, 'destroy', path=path)
if data is False:
return data
if delete_key:
skey = salt.key.Key(__opts__)
skey.delete_key(name)
if data is None:
return
if not quiet:
__jid_event__.fire_event(
{'data': data, 'outputter': 'lxc_purge'}, 'progress')
return data | [
"def",
"purge",
"(",
"name",
",",
"delete_key",
"=",
"True",
",",
"quiet",
"=",
"False",
",",
"path",
"=",
"None",
")",
":",
"data",
"=",
"_do_names",
"(",
"name",
",",
"'destroy'",
",",
"path",
"=",
"path",
")",
"if",
"data",
"is",
"False",
":",
... | Purge the named container and delete its minion key if present.
WARNING: Destroys all data associated with the container.
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
.. code-block:: bash
salt-run lxc.purge name | [
"Purge",
"the",
"named",
"container",
"and",
"delete",
"its",
"minion",
"key",
"if",
"present",
".",
"WARNING",
":",
"Destroys",
"all",
"data",
"associated",
"with",
"the",
"container",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/lxc.py#L492-L521 | train |
saltstack/salt | salt/runners/lxc.py | start | def start(name, quiet=False, path=None):
'''
Start the named container.
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
.. code-block:: bash
salt-run lxc.start name
'''
data = _do_names(name, 'start', path=path)
if data and not quiet:
__jid_event__.fire_event(
{'data': data, 'outputter': 'lxc_start'}, 'progress')
return data | python | def start(name, quiet=False, path=None):
'''
Start the named container.
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
.. code-block:: bash
salt-run lxc.start name
'''
data = _do_names(name, 'start', path=path)
if data and not quiet:
__jid_event__.fire_event(
{'data': data, 'outputter': 'lxc_start'}, 'progress')
return data | [
"def",
"start",
"(",
"name",
",",
"quiet",
"=",
"False",
",",
"path",
"=",
"None",
")",
":",
"data",
"=",
"_do_names",
"(",
"name",
",",
"'start'",
",",
"path",
"=",
"path",
")",
"if",
"data",
"and",
"not",
"quiet",
":",
"__jid_event__",
".",
"fire... | Start the named container.
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
.. code-block:: bash
salt-run lxc.start name | [
"Start",
"the",
"named",
"container",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/lxc.py#L524-L542 | train |
saltstack/salt | salt/modules/selinux.py | selinux_fs_path | def selinux_fs_path():
'''
Return the location of the SELinux VFS directory
CLI Example:
.. code-block:: bash
salt '*' selinux.selinux_fs_path
'''
# systems running systemd (e.g. Fedora 15 and newer)
# have the selinux filesystem in a different location
try:
for directory in ('/sys/fs/selinux', '/selinux'):
if os.path.isdir(directory):
if os.path.isfile(os.path.join(directory, 'enforce')):
return directory
return None
# If selinux is Disabled, the path does not exist.
except AttributeError:
return None | python | def selinux_fs_path():
'''
Return the location of the SELinux VFS directory
CLI Example:
.. code-block:: bash
salt '*' selinux.selinux_fs_path
'''
# systems running systemd (e.g. Fedora 15 and newer)
# have the selinux filesystem in a different location
try:
for directory in ('/sys/fs/selinux', '/selinux'):
if os.path.isdir(directory):
if os.path.isfile(os.path.join(directory, 'enforce')):
return directory
return None
# If selinux is Disabled, the path does not exist.
except AttributeError:
return None | [
"def",
"selinux_fs_path",
"(",
")",
":",
"# systems running systemd (e.g. Fedora 15 and newer)",
"# have the selinux filesystem in a different location",
"try",
":",
"for",
"directory",
"in",
"(",
"'/sys/fs/selinux'",
",",
"'/selinux'",
")",
":",
"if",
"os",
".",
"path",
... | Return the location of the SELinux VFS directory
CLI Example:
.. code-block:: bash
salt '*' selinux.selinux_fs_path | [
"Return",
"the",
"location",
"of",
"the",
"SELinux",
"VFS",
"directory"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/selinux.py#L62-L82 | train |
saltstack/salt | salt/modules/selinux.py | getenforce | def getenforce():
'''
Return the mode selinux is running in
CLI Example:
.. code-block:: bash
salt '*' selinux.getenforce
'''
_selinux_fs_path = selinux_fs_path()
if _selinux_fs_path is None:
return 'Disabled'
try:
enforce = os.path.join(_selinux_fs_path, 'enforce')
with salt.utils.files.fopen(enforce, 'r') as _fp:
if salt.utils.stringutils.to_unicode(_fp.readline()).strip() == '0':
return 'Permissive'
else:
return 'Enforcing'
except (IOError, OSError, AttributeError):
return 'Disabled' | python | def getenforce():
'''
Return the mode selinux is running in
CLI Example:
.. code-block:: bash
salt '*' selinux.getenforce
'''
_selinux_fs_path = selinux_fs_path()
if _selinux_fs_path is None:
return 'Disabled'
try:
enforce = os.path.join(_selinux_fs_path, 'enforce')
with salt.utils.files.fopen(enforce, 'r') as _fp:
if salt.utils.stringutils.to_unicode(_fp.readline()).strip() == '0':
return 'Permissive'
else:
return 'Enforcing'
except (IOError, OSError, AttributeError):
return 'Disabled' | [
"def",
"getenforce",
"(",
")",
":",
"_selinux_fs_path",
"=",
"selinux_fs_path",
"(",
")",
"if",
"_selinux_fs_path",
"is",
"None",
":",
"return",
"'Disabled'",
"try",
":",
"enforce",
"=",
"os",
".",
"path",
".",
"join",
"(",
"_selinux_fs_path",
",",
"'enforce... | Return the mode selinux is running in
CLI Example:
.. code-block:: bash
salt '*' selinux.getenforce | [
"Return",
"the",
"mode",
"selinux",
"is",
"running",
"in"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/selinux.py#L85-L106 | train |
saltstack/salt | salt/modules/selinux.py | getconfig | def getconfig():
'''
Return the selinux mode from the config file
CLI Example:
.. code-block:: bash
salt '*' selinux.getconfig
'''
try:
config = '/etc/selinux/config'
with salt.utils.files.fopen(config, 'r') as _fp:
for line in _fp:
line = salt.utils.stringutils.to_unicode(line)
if line.strip().startswith('SELINUX='):
return line.split('=')[1].capitalize().strip()
except (IOError, OSError, AttributeError):
return None
return None | python | def getconfig():
'''
Return the selinux mode from the config file
CLI Example:
.. code-block:: bash
salt '*' selinux.getconfig
'''
try:
config = '/etc/selinux/config'
with salt.utils.files.fopen(config, 'r') as _fp:
for line in _fp:
line = salt.utils.stringutils.to_unicode(line)
if line.strip().startswith('SELINUX='):
return line.split('=')[1].capitalize().strip()
except (IOError, OSError, AttributeError):
return None
return None | [
"def",
"getconfig",
"(",
")",
":",
"try",
":",
"config",
"=",
"'/etc/selinux/config'",
"with",
"salt",
".",
"utils",
".",
"files",
".",
"fopen",
"(",
"config",
",",
"'r'",
")",
"as",
"_fp",
":",
"for",
"line",
"in",
"_fp",
":",
"line",
"=",
"salt",
... | Return the selinux mode from the config file
CLI Example:
.. code-block:: bash
salt '*' selinux.getconfig | [
"Return",
"the",
"selinux",
"mode",
"from",
"the",
"config",
"file"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/selinux.py#L109-L128 | train |
saltstack/salt | salt/modules/selinux.py | setenforce | def setenforce(mode):
'''
Set the SELinux enforcing mode
CLI Example:
.. code-block:: bash
salt '*' selinux.setenforce enforcing
'''
if isinstance(mode, six.string_types):
if mode.lower() == 'enforcing':
mode = '1'
modestring = 'Enforcing'
elif mode.lower() == 'permissive':
mode = '0'
modestring = 'Permissive'
elif mode.lower() == 'disabled':
mode = '0'
modestring = 'Disabled'
else:
return 'Invalid mode {0}'.format(mode)
elif isinstance(mode, int):
if mode:
mode = '1'
else:
mode = '0'
else:
return 'Invalid mode {0}'.format(mode)
# enforce file does not exist if currently disabled. Only for toggling enforcing/permissive
if getenforce() != 'Disabled':
enforce = os.path.join(selinux_fs_path(), 'enforce')
try:
with salt.utils.files.fopen(enforce, 'w') as _fp:
_fp.write(salt.utils.stringutils.to_str(mode))
except (IOError, OSError) as exc:
msg = 'Could not write SELinux enforce file: {0}'
raise CommandExecutionError(msg.format(exc))
config = '/etc/selinux/config'
try:
with salt.utils.files.fopen(config, 'r') as _cf:
conf = _cf.read()
try:
with salt.utils.files.fopen(config, 'w') as _cf:
conf = re.sub(r"\nSELINUX=.*\n", "\nSELINUX=" + modestring + "\n", conf)
_cf.write(salt.utils.stringutils.to_str(conf))
except (IOError, OSError) as exc:
msg = 'Could not write SELinux config file: {0}'
raise CommandExecutionError(msg.format(exc))
except (IOError, OSError) as exc:
msg = 'Could not read SELinux config file: {0}'
raise CommandExecutionError(msg.format(exc))
return getenforce() | python | def setenforce(mode):
'''
Set the SELinux enforcing mode
CLI Example:
.. code-block:: bash
salt '*' selinux.setenforce enforcing
'''
if isinstance(mode, six.string_types):
if mode.lower() == 'enforcing':
mode = '1'
modestring = 'Enforcing'
elif mode.lower() == 'permissive':
mode = '0'
modestring = 'Permissive'
elif mode.lower() == 'disabled':
mode = '0'
modestring = 'Disabled'
else:
return 'Invalid mode {0}'.format(mode)
elif isinstance(mode, int):
if mode:
mode = '1'
else:
mode = '0'
else:
return 'Invalid mode {0}'.format(mode)
# enforce file does not exist if currently disabled. Only for toggling enforcing/permissive
if getenforce() != 'Disabled':
enforce = os.path.join(selinux_fs_path(), 'enforce')
try:
with salt.utils.files.fopen(enforce, 'w') as _fp:
_fp.write(salt.utils.stringutils.to_str(mode))
except (IOError, OSError) as exc:
msg = 'Could not write SELinux enforce file: {0}'
raise CommandExecutionError(msg.format(exc))
config = '/etc/selinux/config'
try:
with salt.utils.files.fopen(config, 'r') as _cf:
conf = _cf.read()
try:
with salt.utils.files.fopen(config, 'w') as _cf:
conf = re.sub(r"\nSELINUX=.*\n", "\nSELINUX=" + modestring + "\n", conf)
_cf.write(salt.utils.stringutils.to_str(conf))
except (IOError, OSError) as exc:
msg = 'Could not write SELinux config file: {0}'
raise CommandExecutionError(msg.format(exc))
except (IOError, OSError) as exc:
msg = 'Could not read SELinux config file: {0}'
raise CommandExecutionError(msg.format(exc))
return getenforce() | [
"def",
"setenforce",
"(",
"mode",
")",
":",
"if",
"isinstance",
"(",
"mode",
",",
"six",
".",
"string_types",
")",
":",
"if",
"mode",
".",
"lower",
"(",
")",
"==",
"'enforcing'",
":",
"mode",
"=",
"'1'",
"modestring",
"=",
"'Enforcing'",
"elif",
"mode"... | Set the SELinux enforcing mode
CLI Example:
.. code-block:: bash
salt '*' selinux.setenforce enforcing | [
"Set",
"the",
"SELinux",
"enforcing",
"mode"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/selinux.py#L131-L186 | train |
saltstack/salt | salt/modules/selinux.py | setsebool | def setsebool(boolean, value, persist=False):
'''
Set the value for a boolean
CLI Example:
.. code-block:: bash
salt '*' selinux.setsebool virt_use_usb off
'''
if persist:
cmd = 'setsebool -P {0} {1}'.format(boolean, value)
else:
cmd = 'setsebool {0} {1}'.format(boolean, value)
return not __salt__['cmd.retcode'](cmd, python_shell=False) | python | def setsebool(boolean, value, persist=False):
'''
Set the value for a boolean
CLI Example:
.. code-block:: bash
salt '*' selinux.setsebool virt_use_usb off
'''
if persist:
cmd = 'setsebool -P {0} {1}'.format(boolean, value)
else:
cmd = 'setsebool {0} {1}'.format(boolean, value)
return not __salt__['cmd.retcode'](cmd, python_shell=False) | [
"def",
"setsebool",
"(",
"boolean",
",",
"value",
",",
"persist",
"=",
"False",
")",
":",
"if",
"persist",
":",
"cmd",
"=",
"'setsebool -P {0} {1}'",
".",
"format",
"(",
"boolean",
",",
"value",
")",
"else",
":",
"cmd",
"=",
"'setsebool {0} {1}'",
".",
"... | Set the value for a boolean
CLI Example:
.. code-block:: bash
salt '*' selinux.setsebool virt_use_usb off | [
"Set",
"the",
"value",
"for",
"a",
"boolean"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/selinux.py#L202-L216 | train |
saltstack/salt | salt/modules/selinux.py | setsebools | def setsebools(pairs, persist=False):
'''
Set the value of multiple booleans
CLI Example:
.. code-block:: bash
salt '*' selinux.setsebools '{virt_use_usb: on, squid_use_tproxy: off}'
'''
if not isinstance(pairs, dict):
return {}
if persist:
cmd = 'setsebool -P '
else:
cmd = 'setsebool '
for boolean, value in six.iteritems(pairs):
cmd = '{0} {1}={2}'.format(cmd, boolean, value)
return not __salt__['cmd.retcode'](cmd, python_shell=False) | python | def setsebools(pairs, persist=False):
'''
Set the value of multiple booleans
CLI Example:
.. code-block:: bash
salt '*' selinux.setsebools '{virt_use_usb: on, squid_use_tproxy: off}'
'''
if not isinstance(pairs, dict):
return {}
if persist:
cmd = 'setsebool -P '
else:
cmd = 'setsebool '
for boolean, value in six.iteritems(pairs):
cmd = '{0} {1}={2}'.format(cmd, boolean, value)
return not __salt__['cmd.retcode'](cmd, python_shell=False) | [
"def",
"setsebools",
"(",
"pairs",
",",
"persist",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"pairs",
",",
"dict",
")",
":",
"return",
"{",
"}",
"if",
"persist",
":",
"cmd",
"=",
"'setsebool -P '",
"else",
":",
"cmd",
"=",
"'setsebool '",... | Set the value of multiple booleans
CLI Example:
.. code-block:: bash
salt '*' selinux.setsebools '{virt_use_usb: on, squid_use_tproxy: off}' | [
"Set",
"the",
"value",
"of",
"multiple",
"booleans"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/selinux.py#L219-L237 | train |
saltstack/salt | salt/modules/selinux.py | list_sebool | def list_sebool():
'''
Return a structure listing all of the selinux booleans on the system and
what state they are in
CLI Example:
.. code-block:: bash
salt '*' selinux.list_sebool
'''
bdata = __salt__['cmd.run']('semanage boolean -l').splitlines()
ret = {}
for line in bdata[1:]:
if not line.strip():
continue
comps = line.split()
ret[comps[0]] = {'State': comps[1][1:],
'Default': comps[3][:-1],
'Description': ' '.join(comps[4:])}
return ret | python | def list_sebool():
'''
Return a structure listing all of the selinux booleans on the system and
what state they are in
CLI Example:
.. code-block:: bash
salt '*' selinux.list_sebool
'''
bdata = __salt__['cmd.run']('semanage boolean -l').splitlines()
ret = {}
for line in bdata[1:]:
if not line.strip():
continue
comps = line.split()
ret[comps[0]] = {'State': comps[1][1:],
'Default': comps[3][:-1],
'Description': ' '.join(comps[4:])}
return ret | [
"def",
"list_sebool",
"(",
")",
":",
"bdata",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"'semanage boolean -l'",
")",
".",
"splitlines",
"(",
")",
"ret",
"=",
"{",
"}",
"for",
"line",
"in",
"bdata",
"[",
"1",
":",
"]",
":",
"if",
"not",
"line",
... | Return a structure listing all of the selinux booleans on the system and
what state they are in
CLI Example:
.. code-block:: bash
salt '*' selinux.list_sebool | [
"Return",
"a",
"structure",
"listing",
"all",
"of",
"the",
"selinux",
"booleans",
"on",
"the",
"system",
"and",
"what",
"state",
"they",
"are",
"in"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/selinux.py#L240-L260 | train |
saltstack/salt | salt/modules/selinux.py | setsemod | def setsemod(module, state):
'''
Enable or disable an SELinux module.
CLI Example:
.. code-block:: bash
salt '*' selinux.setsemod nagios Enabled
.. versionadded:: 2016.3.0
'''
if state.lower() == 'enabled':
cmd = 'semodule -e {0}'.format(module)
elif state.lower() == 'disabled':
cmd = 'semodule -d {0}'.format(module)
return not __salt__['cmd.retcode'](cmd) | python | def setsemod(module, state):
'''
Enable or disable an SELinux module.
CLI Example:
.. code-block:: bash
salt '*' selinux.setsemod nagios Enabled
.. versionadded:: 2016.3.0
'''
if state.lower() == 'enabled':
cmd = 'semodule -e {0}'.format(module)
elif state.lower() == 'disabled':
cmd = 'semodule -d {0}'.format(module)
return not __salt__['cmd.retcode'](cmd) | [
"def",
"setsemod",
"(",
"module",
",",
"state",
")",
":",
"if",
"state",
".",
"lower",
"(",
")",
"==",
"'enabled'",
":",
"cmd",
"=",
"'semodule -e {0}'",
".",
"format",
"(",
"module",
")",
"elif",
"state",
".",
"lower",
"(",
")",
"==",
"'disabled'",
... | Enable or disable an SELinux module.
CLI Example:
.. code-block:: bash
salt '*' selinux.setsemod nagios Enabled
.. versionadded:: 2016.3.0 | [
"Enable",
"or",
"disable",
"an",
"SELinux",
"module",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/selinux.py#L278-L294 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.