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/ipmi.py | user_delete | def user_delete(uid, channel=14, **kwargs):
'''
Delete user (helper)
:param uid: user number [1:16]
:param channel: number [1:7]
:param kwargs:
- api_host=127.0.0.1
- api_user=admin
- api_pass=example
- api_port=623
- api_kg=None
CLI Examples:
.. code-block:: bash
salt-call ipmi.user_delete uid=2
'''
with _IpmiCommand(**kwargs) as c:
return c.user_delete(uid, channel) | python | def user_delete(uid, channel=14, **kwargs):
'''
Delete user (helper)
:param uid: user number [1:16]
:param channel: number [1:7]
:param kwargs:
- api_host=127.0.0.1
- api_user=admin
- api_pass=example
- api_port=623
- api_kg=None
CLI Examples:
.. code-block:: bash
salt-call ipmi.user_delete uid=2
'''
with _IpmiCommand(**kwargs) as c:
return c.user_delete(uid, channel) | [
"def",
"user_delete",
"(",
"uid",
",",
"channel",
"=",
"14",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"_IpmiCommand",
"(",
"*",
"*",
"kwargs",
")",
"as",
"c",
":",
"return",
"c",
".",
"user_delete",
"(",
"uid",
",",
"channel",
")"
] | Delete user (helper)
:param uid: user number [1:16]
:param channel: number [1:7]
:param kwargs:
- api_host=127.0.0.1
- api_user=admin
- api_pass=example
- api_port=623
- api_kg=None
CLI Examples:
.. code-block:: bash
salt-call ipmi.user_delete uid=2 | [
"Delete",
"user",
"(",
"helper",
")"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ipmi.py#L895-L915 | train |
saltstack/salt | salt/states/tls.py | valid_certificate | def valid_certificate(name,
weeks=0,
days=0,
hours=0,
minutes=0,
seconds=0):
'''
Verify that a TLS certificate is valid now and (optionally) will be valid
for the time specified through weeks, days, hours, minutes, and seconds.
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
now = time.time()
try:
cert_info = __salt__['tls.cert_info'](name)
except IOError as exc:
ret['comment'] = '{}'.format(exc)
ret['result'] = False
log.error(ret['comment'])
return ret
# verify that the cert is valid *now*
if now < cert_info['not_before']:
ret['comment'] = 'Certificate is not yet valid'
return ret
if now > cert_info['not_after']:
ret['comment'] = 'Certificate is expired'
return ret
# verify the cert will be valid for defined time
delta_remaining = datetime.timedelta(seconds=cert_info['not_after']-now)
delta_kind_map = {
'weeks': weeks,
'days': days,
'hours': hours,
'minutes': minutes,
'seconds': seconds,
}
delta_min = datetime.timedelta(**delta_kind_map)
# if ther eisn't enough time remaining, we consider it a failure
if delta_remaining < delta_min:
ret['comment'] = 'Certificate will expire in {0}, which is less than {1}'.format(delta_remaining, delta_min)
return ret
ret['result'] = True
ret['comment'] = 'Certificate is valid for {0}'.format(delta_remaining)
return ret | python | def valid_certificate(name,
weeks=0,
days=0,
hours=0,
minutes=0,
seconds=0):
'''
Verify that a TLS certificate is valid now and (optionally) will be valid
for the time specified through weeks, days, hours, minutes, and seconds.
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
now = time.time()
try:
cert_info = __salt__['tls.cert_info'](name)
except IOError as exc:
ret['comment'] = '{}'.format(exc)
ret['result'] = False
log.error(ret['comment'])
return ret
# verify that the cert is valid *now*
if now < cert_info['not_before']:
ret['comment'] = 'Certificate is not yet valid'
return ret
if now > cert_info['not_after']:
ret['comment'] = 'Certificate is expired'
return ret
# verify the cert will be valid for defined time
delta_remaining = datetime.timedelta(seconds=cert_info['not_after']-now)
delta_kind_map = {
'weeks': weeks,
'days': days,
'hours': hours,
'minutes': minutes,
'seconds': seconds,
}
delta_min = datetime.timedelta(**delta_kind_map)
# if ther eisn't enough time remaining, we consider it a failure
if delta_remaining < delta_min:
ret['comment'] = 'Certificate will expire in {0}, which is less than {1}'.format(delta_remaining, delta_min)
return ret
ret['result'] = True
ret['comment'] = 'Certificate is valid for {0}'.format(delta_remaining)
return ret | [
"def",
"valid_certificate",
"(",
"name",
",",
"weeks",
"=",
"0",
",",
"days",
"=",
"0",
",",
"hours",
"=",
"0",
",",
"minutes",
"=",
"0",
",",
"seconds",
"=",
"0",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}... | Verify that a TLS certificate is valid now and (optionally) will be valid
for the time specified through weeks, days, hours, minutes, and seconds. | [
"Verify",
"that",
"a",
"TLS",
"certificate",
"is",
"valid",
"now",
"and",
"(",
"optionally",
")",
"will",
"be",
"valid",
"for",
"the",
"time",
"specified",
"through",
"weeks",
"days",
"hours",
"minutes",
"and",
"seconds",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/tls.py#L25-L75 | train |
saltstack/salt | salt/beacons/napalm_beacon.py | _compare | def _compare(cur_cmp, cur_struct):
'''
Compares two objects and return a boolean value
when there's a match.
'''
if isinstance(cur_cmp, dict) and isinstance(cur_struct, dict):
log.debug('Comparing dict to dict')
for cmp_key, cmp_value in six.iteritems(cur_cmp):
if cmp_key == '*':
# matches any key from the source dictionary
if isinstance(cmp_value, dict):
found = False
for _, cur_struct_val in six.iteritems(cur_struct):
found |= _compare(cmp_value, cur_struct_val)
return found
else:
found = False
if isinstance(cur_struct, (list, tuple)):
for cur_ele in cur_struct:
found |= _compare(cmp_value, cur_ele)
elif isinstance(cur_struct, dict):
for _, cur_ele in six.iteritems(cur_struct):
found |= _compare(cmp_value, cur_ele)
return found
else:
if isinstance(cmp_value, dict):
if cmp_key not in cur_struct:
return False
return _compare(cmp_value, cur_struct[cmp_key])
if isinstance(cmp_value, list):
found = False
for _, cur_struct_val in six.iteritems(cur_struct):
found |= _compare(cmp_value, cur_struct_val)
return found
else:
return _compare(cmp_value, cur_struct[cmp_key])
elif isinstance(cur_cmp, (list, tuple)) and isinstance(cur_struct, (list, tuple)):
log.debug('Comparing list to list')
found = False
for cur_cmp_ele in cur_cmp:
for cur_struct_ele in cur_struct:
found |= _compare(cur_cmp_ele, cur_struct_ele)
return found
elif isinstance(cur_cmp, dict) and isinstance(cur_struct, (list, tuple)):
log.debug('Comparing dict to list (of dicts?)')
found = False
for cur_struct_ele in cur_struct:
found |= _compare(cur_cmp, cur_struct_ele)
return found
elif isinstance(cur_cmp, bool) and isinstance(cur_struct, bool):
log.debug('Comparing booleans: %s ? %s', cur_cmp, cur_struct)
return cur_cmp == cur_struct
elif isinstance(cur_cmp, (six.string_types, six.text_type)) and \
isinstance(cur_struct, (six.string_types, six.text_type)):
log.debug('Comparing strings (and regex?): %s ? %s', cur_cmp, cur_struct)
# Trying literal match
matched = re.match(cur_cmp, cur_struct, re.I)
if matched:
return True
return False
elif isinstance(cur_cmp, (six.integer_types, float)) and \
isinstance(cur_struct, (six.integer_types, float)):
log.debug('Comparing numeric values: %d ? %d', cur_cmp, cur_struct)
# numeric compare
return cur_cmp == cur_struct
elif isinstance(cur_struct, (six.integer_types, float)) and \
isinstance(cur_cmp, (six.string_types, six.text_type)):
# Comapring the numerical value agains a presumably mathematical value
log.debug('Comparing a numeric value (%d) with a string (%s)', cur_struct, cur_cmp)
numeric_compare = _numeric_regex.match(cur_cmp)
# determine if the value to compare agains is a mathematical operand
if numeric_compare:
compare_value = numeric_compare.group(2)
return getattr(float(cur_struct), _numeric_operand[numeric_compare.group(1)])(float(compare_value))
return False
return False | python | def _compare(cur_cmp, cur_struct):
'''
Compares two objects and return a boolean value
when there's a match.
'''
if isinstance(cur_cmp, dict) and isinstance(cur_struct, dict):
log.debug('Comparing dict to dict')
for cmp_key, cmp_value in six.iteritems(cur_cmp):
if cmp_key == '*':
# matches any key from the source dictionary
if isinstance(cmp_value, dict):
found = False
for _, cur_struct_val in six.iteritems(cur_struct):
found |= _compare(cmp_value, cur_struct_val)
return found
else:
found = False
if isinstance(cur_struct, (list, tuple)):
for cur_ele in cur_struct:
found |= _compare(cmp_value, cur_ele)
elif isinstance(cur_struct, dict):
for _, cur_ele in six.iteritems(cur_struct):
found |= _compare(cmp_value, cur_ele)
return found
else:
if isinstance(cmp_value, dict):
if cmp_key not in cur_struct:
return False
return _compare(cmp_value, cur_struct[cmp_key])
if isinstance(cmp_value, list):
found = False
for _, cur_struct_val in six.iteritems(cur_struct):
found |= _compare(cmp_value, cur_struct_val)
return found
else:
return _compare(cmp_value, cur_struct[cmp_key])
elif isinstance(cur_cmp, (list, tuple)) and isinstance(cur_struct, (list, tuple)):
log.debug('Comparing list to list')
found = False
for cur_cmp_ele in cur_cmp:
for cur_struct_ele in cur_struct:
found |= _compare(cur_cmp_ele, cur_struct_ele)
return found
elif isinstance(cur_cmp, dict) and isinstance(cur_struct, (list, tuple)):
log.debug('Comparing dict to list (of dicts?)')
found = False
for cur_struct_ele in cur_struct:
found |= _compare(cur_cmp, cur_struct_ele)
return found
elif isinstance(cur_cmp, bool) and isinstance(cur_struct, bool):
log.debug('Comparing booleans: %s ? %s', cur_cmp, cur_struct)
return cur_cmp == cur_struct
elif isinstance(cur_cmp, (six.string_types, six.text_type)) and \
isinstance(cur_struct, (six.string_types, six.text_type)):
log.debug('Comparing strings (and regex?): %s ? %s', cur_cmp, cur_struct)
# Trying literal match
matched = re.match(cur_cmp, cur_struct, re.I)
if matched:
return True
return False
elif isinstance(cur_cmp, (six.integer_types, float)) and \
isinstance(cur_struct, (six.integer_types, float)):
log.debug('Comparing numeric values: %d ? %d', cur_cmp, cur_struct)
# numeric compare
return cur_cmp == cur_struct
elif isinstance(cur_struct, (six.integer_types, float)) and \
isinstance(cur_cmp, (six.string_types, six.text_type)):
# Comapring the numerical value agains a presumably mathematical value
log.debug('Comparing a numeric value (%d) with a string (%s)', cur_struct, cur_cmp)
numeric_compare = _numeric_regex.match(cur_cmp)
# determine if the value to compare agains is a mathematical operand
if numeric_compare:
compare_value = numeric_compare.group(2)
return getattr(float(cur_struct), _numeric_operand[numeric_compare.group(1)])(float(compare_value))
return False
return False | [
"def",
"_compare",
"(",
"cur_cmp",
",",
"cur_struct",
")",
":",
"if",
"isinstance",
"(",
"cur_cmp",
",",
"dict",
")",
"and",
"isinstance",
"(",
"cur_struct",
",",
"dict",
")",
":",
"log",
".",
"debug",
"(",
"'Comparing dict to dict'",
")",
"for",
"cmp_key"... | Compares two objects and return a boolean value
when there's a match. | [
"Compares",
"two",
"objects",
"and",
"return",
"a",
"boolean",
"value",
"when",
"there",
"s",
"a",
"match",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/beacons/napalm_beacon.py#L203-L278 | train |
saltstack/salt | salt/beacons/napalm_beacon.py | validate | def validate(config):
'''
Validate the beacon configuration.
'''
# Must be a list of dicts.
if not isinstance(config, list):
return False, 'Configuration for napalm beacon must be a list.'
for mod in config:
fun = mod.keys()[0]
fun_cfg = mod.values()[0]
if not isinstance(fun_cfg, dict):
return False, 'The match structure for the {} execution function output must be a dictionary'.format(fun)
if fun not in __salt__:
return False, 'Execution function {} is not availabe!'.format(fun)
return True, 'Valid configuration for the napal beacon!' | python | def validate(config):
'''
Validate the beacon configuration.
'''
# Must be a list of dicts.
if not isinstance(config, list):
return False, 'Configuration for napalm beacon must be a list.'
for mod in config:
fun = mod.keys()[0]
fun_cfg = mod.values()[0]
if not isinstance(fun_cfg, dict):
return False, 'The match structure for the {} execution function output must be a dictionary'.format(fun)
if fun not in __salt__:
return False, 'Execution function {} is not availabe!'.format(fun)
return True, 'Valid configuration for the napal beacon!' | [
"def",
"validate",
"(",
"config",
")",
":",
"# Must be a list of dicts.",
"if",
"not",
"isinstance",
"(",
"config",
",",
"list",
")",
":",
"return",
"False",
",",
"'Configuration for napalm beacon must be a list.'",
"for",
"mod",
"in",
"config",
":",
"fun",
"=",
... | Validate the beacon configuration. | [
"Validate",
"the",
"beacon",
"configuration",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/beacons/napalm_beacon.py#L281-L295 | train |
saltstack/salt | salt/beacons/napalm_beacon.py | beacon | def beacon(config):
'''
Watch napalm function and fire events.
'''
log.debug('Executing napalm beacon with config:')
log.debug(config)
ret = []
for mod in config:
if not mod:
continue
event = {}
fun = mod.keys()[0]
fun_cfg = mod.values()[0]
args = fun_cfg.pop('_args', [])
kwargs = fun_cfg.pop('_kwargs', {})
log.debug('Executing %s with %s and %s', fun, args, kwargs)
fun_ret = __salt__[fun](*args, **kwargs)
log.debug('Got the reply from the minion:')
log.debug(fun_ret)
if not fun_ret.get('result', False):
log.error('Error whilst executing %s', fun)
log.error(fun_ret)
continue
fun_ret_out = fun_ret['out']
log.debug('Comparing to:')
log.debug(fun_cfg)
try:
fun_cmp_result = _compare(fun_cfg, fun_ret_out)
except Exception as err:
log.error(err, exc_info=True)
# catch any exception and continue
# to not jeopardise the execution of the next function in the list
continue
log.debug('Result of comparison: %s', fun_cmp_result)
if fun_cmp_result:
log.info('Matched %s with %s', fun, fun_cfg)
event['tag'] = '{os}/{fun}'.format(os=__grains__['os'], fun=fun)
event['fun'] = fun
event['args'] = args
event['kwargs'] = kwargs
event['data'] = fun_ret
event['match'] = fun_cfg
log.debug('Queueing event:')
log.debug(event)
ret.append(event)
log.debug('NAPALM beacon generated the events:')
log.debug(ret)
return ret | python | def beacon(config):
'''
Watch napalm function and fire events.
'''
log.debug('Executing napalm beacon with config:')
log.debug(config)
ret = []
for mod in config:
if not mod:
continue
event = {}
fun = mod.keys()[0]
fun_cfg = mod.values()[0]
args = fun_cfg.pop('_args', [])
kwargs = fun_cfg.pop('_kwargs', {})
log.debug('Executing %s with %s and %s', fun, args, kwargs)
fun_ret = __salt__[fun](*args, **kwargs)
log.debug('Got the reply from the minion:')
log.debug(fun_ret)
if not fun_ret.get('result', False):
log.error('Error whilst executing %s', fun)
log.error(fun_ret)
continue
fun_ret_out = fun_ret['out']
log.debug('Comparing to:')
log.debug(fun_cfg)
try:
fun_cmp_result = _compare(fun_cfg, fun_ret_out)
except Exception as err:
log.error(err, exc_info=True)
# catch any exception and continue
# to not jeopardise the execution of the next function in the list
continue
log.debug('Result of comparison: %s', fun_cmp_result)
if fun_cmp_result:
log.info('Matched %s with %s', fun, fun_cfg)
event['tag'] = '{os}/{fun}'.format(os=__grains__['os'], fun=fun)
event['fun'] = fun
event['args'] = args
event['kwargs'] = kwargs
event['data'] = fun_ret
event['match'] = fun_cfg
log.debug('Queueing event:')
log.debug(event)
ret.append(event)
log.debug('NAPALM beacon generated the events:')
log.debug(ret)
return ret | [
"def",
"beacon",
"(",
"config",
")",
":",
"log",
".",
"debug",
"(",
"'Executing napalm beacon with config:'",
")",
"log",
".",
"debug",
"(",
"config",
")",
"ret",
"=",
"[",
"]",
"for",
"mod",
"in",
"config",
":",
"if",
"not",
"mod",
":",
"continue",
"e... | Watch napalm function and fire events. | [
"Watch",
"napalm",
"function",
"and",
"fire",
"events",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/beacons/napalm_beacon.py#L298-L345 | train |
saltstack/salt | salt/modules/ilo.py | __execute_cmd | def __execute_cmd(name, xml):
'''
Execute ilom commands
'''
ret = {name.replace('_', ' '): {}}
id_num = 0
tmp_dir = os.path.join(__opts__['cachedir'], 'tmp')
if not os.path.isdir(tmp_dir):
os.mkdir(tmp_dir)
with tempfile.NamedTemporaryFile(dir=tmp_dir,
prefix=name + six.text_type(os.getpid()),
suffix='.xml',
delete=False) as fh:
tmpfilename = fh.name
fh.write(xml)
cmd = __salt__['cmd.run_all']('hponcfg -f {0}'.format(tmpfilename))
# Clean up the temp file
__salt__['file.remove'](tmpfilename)
if cmd['retcode'] != 0:
for i in cmd['stderr'].splitlines():
if i.startswith(' MESSAGE='):
return {'Failed': i.split('=')[-1]}
return False
try:
for i in ET.fromstring(''.join(cmd['stdout'].splitlines()[3:-1])):
# Make sure dict keys don't collide
if ret[name.replace('_', ' ')].get(i.tag, False):
ret[name.replace('_', ' ')].update(
{i.tag + '_' + six.text_type(id_num): i.attrib}
)
id_num += 1
else:
ret[name.replace('_', ' ')].update(
{i.tag: i.attrib}
)
except SyntaxError:
return True
return ret | python | def __execute_cmd(name, xml):
'''
Execute ilom commands
'''
ret = {name.replace('_', ' '): {}}
id_num = 0
tmp_dir = os.path.join(__opts__['cachedir'], 'tmp')
if not os.path.isdir(tmp_dir):
os.mkdir(tmp_dir)
with tempfile.NamedTemporaryFile(dir=tmp_dir,
prefix=name + six.text_type(os.getpid()),
suffix='.xml',
delete=False) as fh:
tmpfilename = fh.name
fh.write(xml)
cmd = __salt__['cmd.run_all']('hponcfg -f {0}'.format(tmpfilename))
# Clean up the temp file
__salt__['file.remove'](tmpfilename)
if cmd['retcode'] != 0:
for i in cmd['stderr'].splitlines():
if i.startswith(' MESSAGE='):
return {'Failed': i.split('=')[-1]}
return False
try:
for i in ET.fromstring(''.join(cmd['stdout'].splitlines()[3:-1])):
# Make sure dict keys don't collide
if ret[name.replace('_', ' ')].get(i.tag, False):
ret[name.replace('_', ' ')].update(
{i.tag + '_' + six.text_type(id_num): i.attrib}
)
id_num += 1
else:
ret[name.replace('_', ' ')].update(
{i.tag: i.attrib}
)
except SyntaxError:
return True
return ret | [
"def",
"__execute_cmd",
"(",
"name",
",",
"xml",
")",
":",
"ret",
"=",
"{",
"name",
".",
"replace",
"(",
"'_'",
",",
"' '",
")",
":",
"{",
"}",
"}",
"id_num",
"=",
"0",
"tmp_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"__opts__",
"[",
"'cac... | Execute ilom commands | [
"Execute",
"ilom",
"commands"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ilo.py#L32-L75 | train |
saltstack/salt | salt/modules/ilo.py | set_http_port | def set_http_port(port=80):
'''
Configure the port HTTP should listen on
CLI Example:
.. code-block:: bash
salt '*' ilo.set_http_port 8080
'''
_current = global_settings()
if _current['Global Settings']['HTTP_PORT']['VALUE'] == port:
return True
_xml = """<RIBCL VERSION="2.0">
<LOGIN USER_LOGIN="adminname" PASSWORD="password">
<RIB_INFO MODE="write">
<MOD_GLOBAL_SETTINGS>
<HTTP_PORT value="{0}"/>
</MOD_GLOBAL_SETTINGS>
</RIB_INFO>
</LOGIN>
</RIBCL>""".format(port)
return __execute_cmd('Set_HTTP_Port', _xml) | python | def set_http_port(port=80):
'''
Configure the port HTTP should listen on
CLI Example:
.. code-block:: bash
salt '*' ilo.set_http_port 8080
'''
_current = global_settings()
if _current['Global Settings']['HTTP_PORT']['VALUE'] == port:
return True
_xml = """<RIBCL VERSION="2.0">
<LOGIN USER_LOGIN="adminname" PASSWORD="password">
<RIB_INFO MODE="write">
<MOD_GLOBAL_SETTINGS>
<HTTP_PORT value="{0}"/>
</MOD_GLOBAL_SETTINGS>
</RIB_INFO>
</LOGIN>
</RIBCL>""".format(port)
return __execute_cmd('Set_HTTP_Port', _xml) | [
"def",
"set_http_port",
"(",
"port",
"=",
"80",
")",
":",
"_current",
"=",
"global_settings",
"(",
")",
"if",
"_current",
"[",
"'Global Settings'",
"]",
"[",
"'HTTP_PORT'",
"]",
"[",
"'VALUE'",
"]",
"==",
"port",
":",
"return",
"True",
"_xml",
"=",
"\"\"... | Configure the port HTTP should listen on
CLI Example:
.. code-block:: bash
salt '*' ilo.set_http_port 8080 | [
"Configure",
"the",
"port",
"HTTP",
"should",
"listen",
"on"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ilo.py#L100-L125 | train |
saltstack/salt | salt/modules/ilo.py | set_https_port | def set_https_port(port=443):
'''
Configure the port HTTPS should listen on
CLI Example:
.. code-block:: bash
salt '*' ilo.set_https_port 4334
'''
_current = global_settings()
if _current['Global Settings']['HTTP_PORT']['VALUE'] == port:
return True
_xml = """<RIBCL VERSION="2.0">
<LOGIN USER_LOGIN="adminname" PASSWORD="password">
<RIB_INFO MODE="write">
<MOD_GLOBAL_SETTINGS>
<HTTPS_PORT value="{0}"/>
</MOD_GLOBAL_SETTINGS>
</RIB_INFO>
</LOGIN>
</RIBCL>""".format(port)
return __execute_cmd('Set_HTTPS_Port', _xml) | python | def set_https_port(port=443):
'''
Configure the port HTTPS should listen on
CLI Example:
.. code-block:: bash
salt '*' ilo.set_https_port 4334
'''
_current = global_settings()
if _current['Global Settings']['HTTP_PORT']['VALUE'] == port:
return True
_xml = """<RIBCL VERSION="2.0">
<LOGIN USER_LOGIN="adminname" PASSWORD="password">
<RIB_INFO MODE="write">
<MOD_GLOBAL_SETTINGS>
<HTTPS_PORT value="{0}"/>
</MOD_GLOBAL_SETTINGS>
</RIB_INFO>
</LOGIN>
</RIBCL>""".format(port)
return __execute_cmd('Set_HTTPS_Port', _xml) | [
"def",
"set_https_port",
"(",
"port",
"=",
"443",
")",
":",
"_current",
"=",
"global_settings",
"(",
")",
"if",
"_current",
"[",
"'Global Settings'",
"]",
"[",
"'HTTP_PORT'",
"]",
"[",
"'VALUE'",
"]",
"==",
"port",
":",
"return",
"True",
"_xml",
"=",
"\"... | Configure the port HTTPS should listen on
CLI Example:
.. code-block:: bash
salt '*' ilo.set_https_port 4334 | [
"Configure",
"the",
"port",
"HTTPS",
"should",
"listen",
"on"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ilo.py#L128-L153 | train |
saltstack/salt | salt/modules/ilo.py | set_ssh_port | def set_ssh_port(port=22):
'''
Enable SSH on a user defined port
CLI Example:
.. code-block:: bash
salt '*' ilo.set_ssh_port 2222
'''
_current = global_settings()
if _current['Global Settings']['SSH_PORT']['VALUE'] == port:
return True
_xml = """<RIBCL VERSION="2.0">
<LOGIN USER_LOGIN="adminname" PASSWORD="password">
<RIB_INFO MODE="write">
<MOD_GLOBAL_SETTINGS>
<SSH_PORT value="{0}"/>
</MOD_GLOBAL_SETTINGS>
</RIB_INFO>
</LOGIN>
</RIBCL>""".format(port)
return __execute_cmd('Configure_SSH_Port', _xml) | python | def set_ssh_port(port=22):
'''
Enable SSH on a user defined port
CLI Example:
.. code-block:: bash
salt '*' ilo.set_ssh_port 2222
'''
_current = global_settings()
if _current['Global Settings']['SSH_PORT']['VALUE'] == port:
return True
_xml = """<RIBCL VERSION="2.0">
<LOGIN USER_LOGIN="adminname" PASSWORD="password">
<RIB_INFO MODE="write">
<MOD_GLOBAL_SETTINGS>
<SSH_PORT value="{0}"/>
</MOD_GLOBAL_SETTINGS>
</RIB_INFO>
</LOGIN>
</RIBCL>""".format(port)
return __execute_cmd('Configure_SSH_Port', _xml) | [
"def",
"set_ssh_port",
"(",
"port",
"=",
"22",
")",
":",
"_current",
"=",
"global_settings",
"(",
")",
"if",
"_current",
"[",
"'Global Settings'",
"]",
"[",
"'SSH_PORT'",
"]",
"[",
"'VALUE'",
"]",
"==",
"port",
":",
"return",
"True",
"_xml",
"=",
"\"\"\"... | Enable SSH on a user defined port
CLI Example:
.. code-block:: bash
salt '*' ilo.set_ssh_port 2222 | [
"Enable",
"SSH",
"on",
"a",
"user",
"defined",
"port"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ilo.py#L212-L237 | train |
saltstack/salt | salt/modules/ilo.py | create_user | def create_user(name, password, *privileges):
'''
Create user
CLI Example:
.. code-block:: bash
salt '*' ilo.create_user damian secretagent VIRTUAL_MEDIA_PRIV
If no permissions are specify the user will only have a read-only account.
Supported privelges:
* ADMIN_PRIV
Enables the user to administer user accounts.
* REMOTE_CONS_PRIV
Enables the user to access the Remote Console functionality.
* RESET_SERVER_PRIV
Enables the user to remotely manipulate the server power setting.
* VIRTUAL_MEDIA_PRIV
Enables the user permission to access the virtual media functionality.
* CONFIG_ILO_PRIV
Enables the user to configure iLO settings.
'''
_priv = ['ADMIN_PRIV',
'REMOTE_CONS_PRIV',
'RESET_SERVER_PRIV',
'VIRTUAL_MEDIA_PRIV',
'CONFIG_ILO_PRIV']
_xml = """<RIBCL version="2.2">
<LOGIN USER_LOGIN="x" PASSWORD="y">
<RIB_INFO mode="write">
<MOD_GLOBAL_SETTINGS>
<MIN_PASSWORD VALUE="7"/>
</MOD_GLOBAL_SETTINGS>
</RIB_INFO>
<USER_INFO MODE="write">
<ADD_USER USER_NAME="{0}" USER_LOGIN="{0}" PASSWORD="{1}">
{2}
</ADD_USER>
</USER_INFO>
</LOGIN>
</RIBCL>""".format(name, password, '\n'.join(['<{0} value="Y" />'.format(i.upper()) for i in privileges if i.upper() in _priv]))
return __execute_cmd('Create_user', _xml) | python | def create_user(name, password, *privileges):
'''
Create user
CLI Example:
.. code-block:: bash
salt '*' ilo.create_user damian secretagent VIRTUAL_MEDIA_PRIV
If no permissions are specify the user will only have a read-only account.
Supported privelges:
* ADMIN_PRIV
Enables the user to administer user accounts.
* REMOTE_CONS_PRIV
Enables the user to access the Remote Console functionality.
* RESET_SERVER_PRIV
Enables the user to remotely manipulate the server power setting.
* VIRTUAL_MEDIA_PRIV
Enables the user permission to access the virtual media functionality.
* CONFIG_ILO_PRIV
Enables the user to configure iLO settings.
'''
_priv = ['ADMIN_PRIV',
'REMOTE_CONS_PRIV',
'RESET_SERVER_PRIV',
'VIRTUAL_MEDIA_PRIV',
'CONFIG_ILO_PRIV']
_xml = """<RIBCL version="2.2">
<LOGIN USER_LOGIN="x" PASSWORD="y">
<RIB_INFO mode="write">
<MOD_GLOBAL_SETTINGS>
<MIN_PASSWORD VALUE="7"/>
</MOD_GLOBAL_SETTINGS>
</RIB_INFO>
<USER_INFO MODE="write">
<ADD_USER USER_NAME="{0}" USER_LOGIN="{0}" PASSWORD="{1}">
{2}
</ADD_USER>
</USER_INFO>
</LOGIN>
</RIBCL>""".format(name, password, '\n'.join(['<{0} value="Y" />'.format(i.upper()) for i in privileges if i.upper() in _priv]))
return __execute_cmd('Create_user', _xml) | [
"def",
"create_user",
"(",
"name",
",",
"password",
",",
"*",
"privileges",
")",
":",
"_priv",
"=",
"[",
"'ADMIN_PRIV'",
",",
"'REMOTE_CONS_PRIV'",
",",
"'RESET_SERVER_PRIV'",
",",
"'VIRTUAL_MEDIA_PRIV'",
",",
"'CONFIG_ILO_PRIV'",
"]",
"_xml",
"=",
"\"\"\"<RIBCL v... | Create user
CLI Example:
.. code-block:: bash
salt '*' ilo.create_user damian secretagent VIRTUAL_MEDIA_PRIV
If no permissions are specify the user will only have a read-only account.
Supported privelges:
* ADMIN_PRIV
Enables the user to administer user accounts.
* REMOTE_CONS_PRIV
Enables the user to access the Remote Console functionality.
* RESET_SERVER_PRIV
Enables the user to remotely manipulate the server power setting.
* VIRTUAL_MEDIA_PRIV
Enables the user permission to access the virtual media functionality.
* CONFIG_ILO_PRIV
Enables the user to configure iLO settings. | [
"Create",
"user"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ilo.py#L333-L384 | train |
saltstack/salt | salt/modules/ilo.py | configure_network | def configure_network(ip, netmask, gateway):
'''
Configure Network Interface
CLI Example:
.. code-block:: bash
salt '*' ilo.configure_network [IP ADDRESS] [NETMASK] [GATEWAY]
'''
current = network()
# Check to see if the network is already configured
if (ip in current['Network Settings']['IP_ADDRESS']['VALUE'] and
netmask in current['Network Settings']['SUBNET_MASK']['VALUE'] and
gateway in current['Network Settings']['GATEWAY_IP_ADDRESS']['VALUE']):
return True
_xml = """<RIBCL VERSION="2.0">
<LOGIN USER_LOGIN="adminname" PASSWORD="password">
<RIB_INFO MODE="write">
<MOD_NETWORK_SETTINGS>
<IP_ADDRESS value="{0}"/>
<SUBNET_MASK value="{1}"/>
<GATEWAY_IP_ADDRESS value="{2}"/>
</MOD_NETWORK_SETTINGS>
</RIB_INFO>
</LOGIN>
</RIBCL> """.format(ip, netmask, gateway)
return __execute_cmd('Configure_Network', _xml) | python | def configure_network(ip, netmask, gateway):
'''
Configure Network Interface
CLI Example:
.. code-block:: bash
salt '*' ilo.configure_network [IP ADDRESS] [NETMASK] [GATEWAY]
'''
current = network()
# Check to see if the network is already configured
if (ip in current['Network Settings']['IP_ADDRESS']['VALUE'] and
netmask in current['Network Settings']['SUBNET_MASK']['VALUE'] and
gateway in current['Network Settings']['GATEWAY_IP_ADDRESS']['VALUE']):
return True
_xml = """<RIBCL VERSION="2.0">
<LOGIN USER_LOGIN="adminname" PASSWORD="password">
<RIB_INFO MODE="write">
<MOD_NETWORK_SETTINGS>
<IP_ADDRESS value="{0}"/>
<SUBNET_MASK value="{1}"/>
<GATEWAY_IP_ADDRESS value="{2}"/>
</MOD_NETWORK_SETTINGS>
</RIB_INFO>
</LOGIN>
</RIBCL> """.format(ip, netmask, gateway)
return __execute_cmd('Configure_Network', _xml) | [
"def",
"configure_network",
"(",
"ip",
",",
"netmask",
",",
"gateway",
")",
":",
"current",
"=",
"network",
"(",
")",
"# Check to see if the network is already configured",
"if",
"(",
"ip",
"in",
"current",
"[",
"'Network Settings'",
"]",
"[",
"'IP_ADDRESS'",
"]",... | Configure Network Interface
CLI Example:
.. code-block:: bash
salt '*' ilo.configure_network [IP ADDRESS] [NETMASK] [GATEWAY] | [
"Configure",
"Network",
"Interface"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ilo.py#L497-L527 | train |
saltstack/salt | salt/modules/ilo.py | configure_snmp | def configure_snmp(community, snmp_port=161, snmp_trapport=161):
'''
Configure SNMP
CLI Example:
.. code-block:: bash
salt '*' ilo.configure_snmp [COMMUNITY STRING] [SNMP PORT] [SNMP TRAP PORT]
'''
_xml = """<RIBCL VERSION="2.2">
<LOGIN USER_LOGIN="x" PASSWORD="y">
<RIB_INFO mode="write">
<MOD_GLOBAL_SETTINGS>
<SNMP_ACCESS_ENABLED VALUE="Yes"/>
<SNMP_PORT VALUE="{0}"/>
<SNMP_TRAP_PORT VALUE="{1}"/>
</MOD_GLOBAL_SETTINGS>
<MOD_SNMP_IM_SETTINGS>
<SNMP_ADDRESS_1 VALUE=""/>
<SNMP_ADDRESS_1_ROCOMMUNITY VALUE="{2}"/>
<SNMP_ADDRESS_1_TRAPCOMMUNITY VERSION="" VALUE=""/>
<RIB_TRAPS VALUE="Y"/>
<OS_TRAPS VALUE="Y"/>
<SNMP_PASSTHROUGH_STATUS VALUE="N"/>
</MOD_SNMP_IM_SETTINGS>
</RIB_INFO>
</LOGIN>
</RIBCL>""".format(snmp_port, snmp_trapport, community)
return __execute_cmd('Configure_SNMP', _xml) | python | def configure_snmp(community, snmp_port=161, snmp_trapport=161):
'''
Configure SNMP
CLI Example:
.. code-block:: bash
salt '*' ilo.configure_snmp [COMMUNITY STRING] [SNMP PORT] [SNMP TRAP PORT]
'''
_xml = """<RIBCL VERSION="2.2">
<LOGIN USER_LOGIN="x" PASSWORD="y">
<RIB_INFO mode="write">
<MOD_GLOBAL_SETTINGS>
<SNMP_ACCESS_ENABLED VALUE="Yes"/>
<SNMP_PORT VALUE="{0}"/>
<SNMP_TRAP_PORT VALUE="{1}"/>
</MOD_GLOBAL_SETTINGS>
<MOD_SNMP_IM_SETTINGS>
<SNMP_ADDRESS_1 VALUE=""/>
<SNMP_ADDRESS_1_ROCOMMUNITY VALUE="{2}"/>
<SNMP_ADDRESS_1_TRAPCOMMUNITY VERSION="" VALUE=""/>
<RIB_TRAPS VALUE="Y"/>
<OS_TRAPS VALUE="Y"/>
<SNMP_PASSTHROUGH_STATUS VALUE="N"/>
</MOD_SNMP_IM_SETTINGS>
</RIB_INFO>
</LOGIN>
</RIBCL>""".format(snmp_port, snmp_trapport, community)
return __execute_cmd('Configure_SNMP', _xml) | [
"def",
"configure_snmp",
"(",
"community",
",",
"snmp_port",
"=",
"161",
",",
"snmp_trapport",
"=",
"161",
")",
":",
"_xml",
"=",
"\"\"\"<RIBCL VERSION=\"2.2\">\n <LOGIN USER_LOGIN=\"x\" PASSWORD=\"y\">\n <RIB_INFO mode=\"write\">\n ... | Configure SNMP
CLI Example:
.. code-block:: bash
salt '*' ilo.configure_snmp [COMMUNITY STRING] [SNMP PORT] [SNMP TRAP PORT] | [
"Configure",
"SNMP"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ilo.py#L586-L617 | train |
saltstack/salt | salt/states/rdp.py | enabled | def enabled(name):
'''
Enable the RDP service and make sure access to the RDP
port is allowed in the firewall configuration
'''
ret = {'name': name,
'result': True,
'changes': {},
'comment': ''}
stat = __salt__['rdp.status']()
if not stat:
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'RDP will be enabled'
return ret
ret['result'] = __salt__['rdp.enable']()
ret['changes'] = {'RDP was enabled': True}
return ret
ret['comment'] = 'RDP is enabled'
return ret | python | def enabled(name):
'''
Enable the RDP service and make sure access to the RDP
port is allowed in the firewall configuration
'''
ret = {'name': name,
'result': True,
'changes': {},
'comment': ''}
stat = __salt__['rdp.status']()
if not stat:
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'RDP will be enabled'
return ret
ret['result'] = __salt__['rdp.enable']()
ret['changes'] = {'RDP was enabled': True}
return ret
ret['comment'] = 'RDP is enabled'
return ret | [
"def",
"enabled",
"(",
"name",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"True",
",",
"'changes'",
":",
"{",
"}",
",",
"'comment'",
":",
"''",
"}",
"stat",
"=",
"__salt__",
"[",
"'rdp.status'",
"]",
"(",
")",
"if",
"... | Enable the RDP service and make sure access to the RDP
port is allowed in the firewall configuration | [
"Enable",
"the",
"RDP",
"service",
"and",
"make",
"sure",
"access",
"to",
"the",
"RDP",
"port",
"is",
"allowed",
"in",
"the",
"firewall",
"configuration"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/rdp.py#L15-L38 | train |
saltstack/salt | salt/states/rdp.py | disabled | def disabled(name):
'''
Disable the RDP service
'''
ret = {'name': name,
'result': True,
'changes': {},
'comment': ''}
stat = __salt__['rdp.status']()
if stat:
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'RDP will be disabled'
return ret
ret['result'] = __salt__['rdp.disable']()
ret['changes'] = {'RDP was disabled': True}
return ret
ret['comment'] = 'RDP is disabled'
return ret | python | def disabled(name):
'''
Disable the RDP service
'''
ret = {'name': name,
'result': True,
'changes': {},
'comment': ''}
stat = __salt__['rdp.status']()
if stat:
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'RDP will be disabled'
return ret
ret['result'] = __salt__['rdp.disable']()
ret['changes'] = {'RDP was disabled': True}
return ret
ret['comment'] = 'RDP is disabled'
return ret | [
"def",
"disabled",
"(",
"name",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"True",
",",
"'changes'",
":",
"{",
"}",
",",
"'comment'",
":",
"''",
"}",
"stat",
"=",
"__salt__",
"[",
"'rdp.status'",
"]",
"(",
")",
"if",
... | Disable the RDP service | [
"Disable",
"the",
"RDP",
"service"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/rdp.py#L41-L63 | train |
saltstack/salt | salt/states/kapacitor.py | task_present | def task_present(name,
tick_script,
task_type='stream',
database=None,
retention_policy='default',
enable=True,
dbrps=None):
'''
Ensure that a task is present and up-to-date in Kapacitor.
name
Name of the task.
tick_script
Path to the TICK script for the task. Can be a salt:// source.
task_type
Task type. Defaults to 'stream'
dbrps
A list of databases and retention policies in "dbname"."rpname" format
to fetch data from. For backward compatibility, the value of
'database' and 'retention_policy' will be merged as part of dbrps.
.. versionadded:: 2019.2.0
database
Which database to fetch data from. Defaults to None, which will use the
default database in InfluxDB.
retention_policy
Which retention policy to fetch data from. Defaults to 'default'.
enable
Whether to enable the task or not. Defaults to True.
'''
comments = []
changes = []
ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''}
task = __salt__['kapacitor.get_task'](name)
old_script = task['script'] if task else ''
if not dbrps:
dbrps = []
if database and retention_policy:
dbrp = '{0}.{1}'.format(database, retention_policy)
dbrps.append(dbrp)
task_dbrps = [{'db': dbrp[0], 'rp': dbrp[1]} for dbrp in (dbrp.split('.') for dbrp in dbrps)]
if tick_script.startswith('salt://'):
script_path = __salt__['cp.cache_file'](tick_script, __env__)
else:
script_path = tick_script
with salt.utils.files.fopen(script_path, 'r') as file:
new_script = salt.utils.stringutils.to_unicode(file.read()).replace('\t', ' ')
is_up_to_date = task and (
old_script == new_script and
task_type == task['type'] and
task['dbrps'] == task_dbrps
)
if is_up_to_date:
comments.append('Task script is already up-to-date')
else:
if __opts__['test']:
ret['result'] = None
comments.append('Task would have been updated')
else:
result = __salt__['kapacitor.define_task'](
name,
script_path,
task_type=task_type,
database=database,
retention_policy=retention_policy,
dbrps=dbrps
)
ret['result'] = result['success']
if not ret['result']:
comments.append('Could not define task')
if result.get('stderr'):
comments.append(result['stderr'])
ret['comment'] = '\n'.join(comments)
return ret
if old_script != new_script:
ret['changes']['TICKscript diff'] = '\n'.join(difflib.unified_diff(
old_script.splitlines(),
new_script.splitlines(),
))
comments.append('Task script updated')
if not task or task['type'] != task_type:
ret['changes']['type'] = task_type
comments.append('Task type updated')
if not task or task['dbrps'] != task_dbrps:
ret['changes']['dbrps'] = task_dbrps
comments.append('Task dbrps updated')
if enable:
if task and task['enabled']:
comments.append('Task is already enabled')
else:
if __opts__['test']:
ret['result'] = None
comments.append('Task would have been enabled')
else:
result = __salt__['kapacitor.enable_task'](name)
ret['result'] = result['success']
if not ret['result']:
comments.append('Could not enable task')
if result.get('stderr'):
comments.append(result['stderr'])
ret['comment'] = '\n'.join(comments)
return ret
comments.append('Task was enabled')
ret['changes']['enabled'] = {'old': False, 'new': True}
else:
if task and not task['enabled']:
comments.append('Task is already disabled')
else:
if __opts__['test']:
ret['result'] = None
comments.append('Task would have been disabled')
else:
result = __salt__['kapacitor.disable_task'](name)
ret['result'] = result['success']
if not ret['result']:
comments.append('Could not disable task')
if result.get('stderr'):
comments.append(result['stderr'])
ret['comment'] = '\n'.join(comments)
return ret
comments.append('Task was disabled')
ret['changes']['enabled'] = {'old': True, 'new': False}
ret['comment'] = '\n'.join(comments)
return ret | python | def task_present(name,
tick_script,
task_type='stream',
database=None,
retention_policy='default',
enable=True,
dbrps=None):
'''
Ensure that a task is present and up-to-date in Kapacitor.
name
Name of the task.
tick_script
Path to the TICK script for the task. Can be a salt:// source.
task_type
Task type. Defaults to 'stream'
dbrps
A list of databases and retention policies in "dbname"."rpname" format
to fetch data from. For backward compatibility, the value of
'database' and 'retention_policy' will be merged as part of dbrps.
.. versionadded:: 2019.2.0
database
Which database to fetch data from. Defaults to None, which will use the
default database in InfluxDB.
retention_policy
Which retention policy to fetch data from. Defaults to 'default'.
enable
Whether to enable the task or not. Defaults to True.
'''
comments = []
changes = []
ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''}
task = __salt__['kapacitor.get_task'](name)
old_script = task['script'] if task else ''
if not dbrps:
dbrps = []
if database and retention_policy:
dbrp = '{0}.{1}'.format(database, retention_policy)
dbrps.append(dbrp)
task_dbrps = [{'db': dbrp[0], 'rp': dbrp[1]} for dbrp in (dbrp.split('.') for dbrp in dbrps)]
if tick_script.startswith('salt://'):
script_path = __salt__['cp.cache_file'](tick_script, __env__)
else:
script_path = tick_script
with salt.utils.files.fopen(script_path, 'r') as file:
new_script = salt.utils.stringutils.to_unicode(file.read()).replace('\t', ' ')
is_up_to_date = task and (
old_script == new_script and
task_type == task['type'] and
task['dbrps'] == task_dbrps
)
if is_up_to_date:
comments.append('Task script is already up-to-date')
else:
if __opts__['test']:
ret['result'] = None
comments.append('Task would have been updated')
else:
result = __salt__['kapacitor.define_task'](
name,
script_path,
task_type=task_type,
database=database,
retention_policy=retention_policy,
dbrps=dbrps
)
ret['result'] = result['success']
if not ret['result']:
comments.append('Could not define task')
if result.get('stderr'):
comments.append(result['stderr'])
ret['comment'] = '\n'.join(comments)
return ret
if old_script != new_script:
ret['changes']['TICKscript diff'] = '\n'.join(difflib.unified_diff(
old_script.splitlines(),
new_script.splitlines(),
))
comments.append('Task script updated')
if not task or task['type'] != task_type:
ret['changes']['type'] = task_type
comments.append('Task type updated')
if not task or task['dbrps'] != task_dbrps:
ret['changes']['dbrps'] = task_dbrps
comments.append('Task dbrps updated')
if enable:
if task and task['enabled']:
comments.append('Task is already enabled')
else:
if __opts__['test']:
ret['result'] = None
comments.append('Task would have been enabled')
else:
result = __salt__['kapacitor.enable_task'](name)
ret['result'] = result['success']
if not ret['result']:
comments.append('Could not enable task')
if result.get('stderr'):
comments.append(result['stderr'])
ret['comment'] = '\n'.join(comments)
return ret
comments.append('Task was enabled')
ret['changes']['enabled'] = {'old': False, 'new': True}
else:
if task and not task['enabled']:
comments.append('Task is already disabled')
else:
if __opts__['test']:
ret['result'] = None
comments.append('Task would have been disabled')
else:
result = __salt__['kapacitor.disable_task'](name)
ret['result'] = result['success']
if not ret['result']:
comments.append('Could not disable task')
if result.get('stderr'):
comments.append(result['stderr'])
ret['comment'] = '\n'.join(comments)
return ret
comments.append('Task was disabled')
ret['changes']['enabled'] = {'old': True, 'new': False}
ret['comment'] = '\n'.join(comments)
return ret | [
"def",
"task_present",
"(",
"name",
",",
"tick_script",
",",
"task_type",
"=",
"'stream'",
",",
"database",
"=",
"None",
",",
"retention_policy",
"=",
"'default'",
",",
"enable",
"=",
"True",
",",
"dbrps",
"=",
"None",
")",
":",
"comments",
"=",
"[",
"]"... | Ensure that a task is present and up-to-date in Kapacitor.
name
Name of the task.
tick_script
Path to the TICK script for the task. Can be a salt:// source.
task_type
Task type. Defaults to 'stream'
dbrps
A list of databases and retention policies in "dbname"."rpname" format
to fetch data from. For backward compatibility, the value of
'database' and 'retention_policy' will be merged as part of dbrps.
.. versionadded:: 2019.2.0
database
Which database to fetch data from. Defaults to None, which will use the
default database in InfluxDB.
retention_policy
Which retention policy to fetch data from. Defaults to 'default'.
enable
Whether to enable the task or not. Defaults to True. | [
"Ensure",
"that",
"a",
"task",
"is",
"present",
"and",
"up",
"-",
"to",
"-",
"date",
"in",
"Kapacitor",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/kapacitor.py#L32-L171 | train |
saltstack/salt | salt/states/kapacitor.py | task_absent | def task_absent(name):
'''
Ensure that a task is absent from Kapacitor.
name
Name of the task.
'''
ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''}
task = __salt__['kapacitor.get_task'](name)
if task:
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Task would have been deleted'
else:
result = __salt__['kapacitor.delete_task'](name)
ret['result'] = result['success']
if not ret['result']:
ret['comment'] = 'Could not disable task'
if result.get('stderr'):
ret['comment'] += '\n' + result['stderr']
return ret
ret['comment'] = 'Task was deleted'
ret['changes'][name] = 'deleted'
else:
ret['comment'] = 'Task does not exist'
return ret | python | def task_absent(name):
'''
Ensure that a task is absent from Kapacitor.
name
Name of the task.
'''
ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''}
task = __salt__['kapacitor.get_task'](name)
if task:
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Task would have been deleted'
else:
result = __salt__['kapacitor.delete_task'](name)
ret['result'] = result['success']
if not ret['result']:
ret['comment'] = 'Could not disable task'
if result.get('stderr'):
ret['comment'] += '\n' + result['stderr']
return ret
ret['comment'] = 'Task was deleted'
ret['changes'][name] = 'deleted'
else:
ret['comment'] = 'Task does not exist'
return ret | [
"def",
"task_absent",
"(",
"name",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",
"''",
"}",
"task",
"=",
"__salt__",
"[",
"'kapacitor.get_task'",
"]",
"(",
"nam... | Ensure that a task is absent from Kapacitor.
name
Name of the task. | [
"Ensure",
"that",
"a",
"task",
"is",
"absent",
"from",
"Kapacitor",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/kapacitor.py#L174-L202 | train |
saltstack/salt | salt/modules/win_ntp.py | set_servers | def set_servers(*servers):
'''
Set Windows to use a list of NTP servers
CLI Example:
.. code-block:: bash
salt '*' ntp.set_servers 'pool.ntp.org' 'us.pool.ntp.org'
'''
service_name = 'w32time'
if not __salt__['service.status'](service_name):
if not __salt__['service.start'](service_name):
return False
server_cmd = ['W32tm', '/config', '/syncfromflags:manual',
'/manualpeerlist:{0}'.format(' '.join(servers))]
reliable_cmd = ['W32tm', '/config', '/reliable:yes']
update_cmd = ['W32tm', '/config', '/update']
for cmd in server_cmd, reliable_cmd, update_cmd:
__salt__['cmd.run'](cmd, python_shell=False)
if not sorted(list(servers)) == get_servers():
return False
__salt__['service.restart'](service_name)
return True | python | def set_servers(*servers):
'''
Set Windows to use a list of NTP servers
CLI Example:
.. code-block:: bash
salt '*' ntp.set_servers 'pool.ntp.org' 'us.pool.ntp.org'
'''
service_name = 'w32time'
if not __salt__['service.status'](service_name):
if not __salt__['service.start'](service_name):
return False
server_cmd = ['W32tm', '/config', '/syncfromflags:manual',
'/manualpeerlist:{0}'.format(' '.join(servers))]
reliable_cmd = ['W32tm', '/config', '/reliable:yes']
update_cmd = ['W32tm', '/config', '/update']
for cmd in server_cmd, reliable_cmd, update_cmd:
__salt__['cmd.run'](cmd, python_shell=False)
if not sorted(list(servers)) == get_servers():
return False
__salt__['service.restart'](service_name)
return True | [
"def",
"set_servers",
"(",
"*",
"servers",
")",
":",
"service_name",
"=",
"'w32time'",
"if",
"not",
"__salt__",
"[",
"'service.status'",
"]",
"(",
"service_name",
")",
":",
"if",
"not",
"__salt__",
"[",
"'service.start'",
"]",
"(",
"service_name",
")",
":",
... | Set Windows to use a list of NTP servers
CLI Example:
.. code-block:: bash
salt '*' ntp.set_servers 'pool.ntp.org' 'us.pool.ntp.org' | [
"Set",
"Windows",
"to",
"use",
"a",
"list",
"of",
"NTP",
"servers"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_ntp.py#L30-L57 | train |
saltstack/salt | salt/modules/win_ntp.py | get_servers | def get_servers():
'''
Get list of configured NTP servers
CLI Example:
.. code-block:: bash
salt '*' ntp.get_servers
'''
cmd = ['w32tm', '/query', '/configuration']
lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
for line in lines:
try:
if line.startswith('NtpServer:'):
_, ntpsvrs = line.rsplit(' (', 1)[0].split(':', 1)
return sorted(ntpsvrs.split())
except ValueError as e:
return False
return False | python | def get_servers():
'''
Get list of configured NTP servers
CLI Example:
.. code-block:: bash
salt '*' ntp.get_servers
'''
cmd = ['w32tm', '/query', '/configuration']
lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
for line in lines:
try:
if line.startswith('NtpServer:'):
_, ntpsvrs = line.rsplit(' (', 1)[0].split(':', 1)
return sorted(ntpsvrs.split())
except ValueError as e:
return False
return False | [
"def",
"get_servers",
"(",
")",
":",
"cmd",
"=",
"[",
"'w32tm'",
",",
"'/query'",
",",
"'/configuration'",
"]",
"lines",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"cmd",
",",
"python_shell",
"=",
"False",
")",
".",
"splitlines",
"(",
")",
"for",
"li... | Get list of configured NTP servers
CLI Example:
.. code-block:: bash
salt '*' ntp.get_servers | [
"Get",
"list",
"of",
"configured",
"NTP",
"servers"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_ntp.py#L60-L79 | train |
saltstack/salt | salt/modules/junos.py | facts_refresh | def facts_refresh():
'''
Reload the facts dictionary from the device. Usually only needed if,
the device configuration is changed by some other actor.
This function will also refresh the facts stored in the salt grains.
CLI Example:
.. code-block:: bash
salt 'device_name' junos.facts_refresh
'''
conn = __proxy__['junos.conn']()
ret = {}
ret['out'] = True
try:
conn.facts_refresh()
except Exception as exception:
ret['message'] = 'Execution failed due to "{0}"'.format(exception)
ret['out'] = False
return ret
ret['facts'] = __proxy__['junos.get_serialized_facts']()
try:
__salt__['saltutil.sync_grains']()
except Exception as exception:
log.error('Grains could not be updated due to "%s"', exception)
return ret | python | def facts_refresh():
'''
Reload the facts dictionary from the device. Usually only needed if,
the device configuration is changed by some other actor.
This function will also refresh the facts stored in the salt grains.
CLI Example:
.. code-block:: bash
salt 'device_name' junos.facts_refresh
'''
conn = __proxy__['junos.conn']()
ret = {}
ret['out'] = True
try:
conn.facts_refresh()
except Exception as exception:
ret['message'] = 'Execution failed due to "{0}"'.format(exception)
ret['out'] = False
return ret
ret['facts'] = __proxy__['junos.get_serialized_facts']()
try:
__salt__['saltutil.sync_grains']()
except Exception as exception:
log.error('Grains could not be updated due to "%s"', exception)
return ret | [
"def",
"facts_refresh",
"(",
")",
":",
"conn",
"=",
"__proxy__",
"[",
"'junos.conn'",
"]",
"(",
")",
"ret",
"=",
"{",
"}",
"ret",
"[",
"'out'",
"]",
"=",
"True",
"try",
":",
"conn",
".",
"facts_refresh",
"(",
")",
"except",
"Exception",
"as",
"except... | Reload the facts dictionary from the device. Usually only needed if,
the device configuration is changed by some other actor.
This function will also refresh the facts stored in the salt grains.
CLI Example:
.. code-block:: bash
salt 'device_name' junos.facts_refresh | [
"Reload",
"the",
"facts",
"dictionary",
"from",
"the",
"device",
".",
"Usually",
"only",
"needed",
"if",
"the",
"device",
"configuration",
"is",
"changed",
"by",
"some",
"other",
"actor",
".",
"This",
"function",
"will",
"also",
"refresh",
"the",
"facts",
"s... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/junos.py#L106-L134 | train |
saltstack/salt | salt/modules/junos.py | facts | def facts():
'''
Displays the facts gathered during the connection.
These facts are also stored in Salt grains.
CLI Example:
.. code-block:: bash
salt 'device_name' junos.facts
'''
ret = {}
try:
ret['facts'] = __proxy__['junos.get_serialized_facts']()
ret['out'] = True
except Exception as exception:
ret['message'] = 'Could not display facts due to "{0}"'.format(
exception)
ret['out'] = False
return ret | python | def facts():
'''
Displays the facts gathered during the connection.
These facts are also stored in Salt grains.
CLI Example:
.. code-block:: bash
salt 'device_name' junos.facts
'''
ret = {}
try:
ret['facts'] = __proxy__['junos.get_serialized_facts']()
ret['out'] = True
except Exception as exception:
ret['message'] = 'Could not display facts due to "{0}"'.format(
exception)
ret['out'] = False
return ret | [
"def",
"facts",
"(",
")",
":",
"ret",
"=",
"{",
"}",
"try",
":",
"ret",
"[",
"'facts'",
"]",
"=",
"__proxy__",
"[",
"'junos.get_serialized_facts'",
"]",
"(",
")",
"ret",
"[",
"'out'",
"]",
"=",
"True",
"except",
"Exception",
"as",
"exception",
":",
"... | Displays the facts gathered during the connection.
These facts are also stored in Salt grains.
CLI Example:
.. code-block:: bash
salt 'device_name' junos.facts | [
"Displays",
"the",
"facts",
"gathered",
"during",
"the",
"connection",
".",
"These",
"facts",
"are",
"also",
"stored",
"in",
"Salt",
"grains",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/junos.py#L137-L156 | train |
saltstack/salt | salt/modules/junos.py | rpc | def rpc(cmd=None, dest=None, **kwargs):
'''
This function executes the RPC provided as arguments on the junos device.
The returned data can be stored in a file.
cmd
The RPC to be executed
dest
Destination file where the RPC output is stored. Note that the file
will be stored on the proxy minion. To push the files to the master use
:py:func:`cp.push <salt.modules.cp.push>`.
format : xml
The format in which the RPC reply is received from the device
dev_timeout : 30
The NETCONF RPC timeout (in seconds)
filter
Used with the ``get-config`` RPC to get specific configuration
terse : False
Amount of information you want
interface_name
Name of the interface to query
CLI Example:
.. code-block:: bash
salt 'device' junos.rpc get_config /var/log/config.txt format=text filter='<configuration><system/></configuration>'
salt 'device' junos.rpc get-interface-information /home/user/interface.xml interface_name='lo0' terse=True
salt 'device' junos.rpc get-chassis-inventory
'''
conn = __proxy__['junos.conn']()
ret = {}
ret['out'] = True
if cmd is None:
ret['message'] = 'Please provide the rpc to execute.'
ret['out'] = False
return ret
format_ = kwargs.pop('format', 'xml')
if not format_:
format_ = 'xml'
op = dict()
if '__pub_arg' in kwargs:
if kwargs['__pub_arg']:
if isinstance(kwargs['__pub_arg'][-1], dict):
op.update(kwargs['__pub_arg'][-1])
elif '__pub_schedule' in kwargs:
for key, value in six.iteritems(kwargs):
if not key.startswith('__pub_'):
op[key] = value
else:
op.update(kwargs)
if cmd in ['get-config', 'get_config']:
filter_reply = None
if 'filter' in op:
filter_reply = etree.XML(op['filter'])
del op['filter']
op.update({'format': format_})
try:
reply = getattr(
conn.rpc,
cmd.replace('-',
'_'))(filter_reply,
options=op)
except Exception as exception:
ret['message'] = 'RPC execution failed due to "{0}"'.format(
exception)
ret['out'] = False
return ret
else:
if 'filter' in op:
log.warning(
'Filter ignored as it is only used with "get-config" rpc')
try:
reply = getattr(
conn.rpc,
cmd.replace('-',
'_'))({'format': format_},
**op)
except Exception as exception:
ret['message'] = 'RPC execution failed due to "{0}"'.format(
exception)
ret['out'] = False
return ret
if format_ == 'text':
# Earlier it was ret['message']
ret['rpc_reply'] = reply.text
elif format_ == 'json':
# Earlier it was ret['message']
ret['rpc_reply'] = reply
else:
# Earlier it was ret['message']
ret['rpc_reply'] = jxmlease.parse(etree.tostring(reply))
if dest:
if format_ == 'text':
write_response = reply.text
elif format_ == 'json':
write_response = salt.utils.json.dumps(reply, indent=1)
else:
write_response = etree.tostring(reply)
with salt.utils.files.fopen(dest, 'w') as fp:
fp.write(salt.utils.stringutils.to_str(write_response))
return ret | python | def rpc(cmd=None, dest=None, **kwargs):
'''
This function executes the RPC provided as arguments on the junos device.
The returned data can be stored in a file.
cmd
The RPC to be executed
dest
Destination file where the RPC output is stored. Note that the file
will be stored on the proxy minion. To push the files to the master use
:py:func:`cp.push <salt.modules.cp.push>`.
format : xml
The format in which the RPC reply is received from the device
dev_timeout : 30
The NETCONF RPC timeout (in seconds)
filter
Used with the ``get-config`` RPC to get specific configuration
terse : False
Amount of information you want
interface_name
Name of the interface to query
CLI Example:
.. code-block:: bash
salt 'device' junos.rpc get_config /var/log/config.txt format=text filter='<configuration><system/></configuration>'
salt 'device' junos.rpc get-interface-information /home/user/interface.xml interface_name='lo0' terse=True
salt 'device' junos.rpc get-chassis-inventory
'''
conn = __proxy__['junos.conn']()
ret = {}
ret['out'] = True
if cmd is None:
ret['message'] = 'Please provide the rpc to execute.'
ret['out'] = False
return ret
format_ = kwargs.pop('format', 'xml')
if not format_:
format_ = 'xml'
op = dict()
if '__pub_arg' in kwargs:
if kwargs['__pub_arg']:
if isinstance(kwargs['__pub_arg'][-1], dict):
op.update(kwargs['__pub_arg'][-1])
elif '__pub_schedule' in kwargs:
for key, value in six.iteritems(kwargs):
if not key.startswith('__pub_'):
op[key] = value
else:
op.update(kwargs)
if cmd in ['get-config', 'get_config']:
filter_reply = None
if 'filter' in op:
filter_reply = etree.XML(op['filter'])
del op['filter']
op.update({'format': format_})
try:
reply = getattr(
conn.rpc,
cmd.replace('-',
'_'))(filter_reply,
options=op)
except Exception as exception:
ret['message'] = 'RPC execution failed due to "{0}"'.format(
exception)
ret['out'] = False
return ret
else:
if 'filter' in op:
log.warning(
'Filter ignored as it is only used with "get-config" rpc')
try:
reply = getattr(
conn.rpc,
cmd.replace('-',
'_'))({'format': format_},
**op)
except Exception as exception:
ret['message'] = 'RPC execution failed due to "{0}"'.format(
exception)
ret['out'] = False
return ret
if format_ == 'text':
# Earlier it was ret['message']
ret['rpc_reply'] = reply.text
elif format_ == 'json':
# Earlier it was ret['message']
ret['rpc_reply'] = reply
else:
# Earlier it was ret['message']
ret['rpc_reply'] = jxmlease.parse(etree.tostring(reply))
if dest:
if format_ == 'text':
write_response = reply.text
elif format_ == 'json':
write_response = salt.utils.json.dumps(reply, indent=1)
else:
write_response = etree.tostring(reply)
with salt.utils.files.fopen(dest, 'w') as fp:
fp.write(salt.utils.stringutils.to_str(write_response))
return ret | [
"def",
"rpc",
"(",
"cmd",
"=",
"None",
",",
"dest",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"conn",
"=",
"__proxy__",
"[",
"'junos.conn'",
"]",
"(",
")",
"ret",
"=",
"{",
"}",
"ret",
"[",
"'out'",
"]",
"=",
"True",
"if",
"cmd",
"is",
... | This function executes the RPC provided as arguments on the junos device.
The returned data can be stored in a file.
cmd
The RPC to be executed
dest
Destination file where the RPC output is stored. Note that the file
will be stored on the proxy minion. To push the files to the master use
:py:func:`cp.push <salt.modules.cp.push>`.
format : xml
The format in which the RPC reply is received from the device
dev_timeout : 30
The NETCONF RPC timeout (in seconds)
filter
Used with the ``get-config`` RPC to get specific configuration
terse : False
Amount of information you want
interface_name
Name of the interface to query
CLI Example:
.. code-block:: bash
salt 'device' junos.rpc get_config /var/log/config.txt format=text filter='<configuration><system/></configuration>'
salt 'device' junos.rpc get-interface-information /home/user/interface.xml interface_name='lo0' terse=True
salt 'device' junos.rpc get-chassis-inventory | [
"This",
"function",
"executes",
"the",
"RPC",
"provided",
"as",
"arguments",
"on",
"the",
"junos",
"device",
".",
"The",
"returned",
"data",
"can",
"be",
"stored",
"in",
"a",
"file",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/junos.py#L160-L275 | train |
saltstack/salt | salt/modules/junos.py | set_hostname | def set_hostname(hostname=None, **kwargs):
'''
Set the device's hostname
hostname
The name to be set
comment
Provide a comment to the commit
dev_timeout : 30
The NETCONF RPC timeout (in seconds)
confirm
Provide time in minutes for commit confirmation. If this option is
specified, the commit will be rolled back in the specified amount of time
unless the commit is confirmed.
CLI Example:
.. code-block:: bash
salt 'device_name' junos.set_hostname salt-device
'''
conn = __proxy__['junos.conn']()
ret = {}
if hostname is None:
ret['message'] = 'Please provide the hostname.'
ret['out'] = False
return ret
op = dict()
if '__pub_arg' in kwargs:
if kwargs['__pub_arg']:
if isinstance(kwargs['__pub_arg'][-1], dict):
op.update(kwargs['__pub_arg'][-1])
else:
op.update(kwargs)
# Added to recent versions of JunOs
# Use text format instead
set_string = 'set system host-name {0}'.format(hostname)
try:
conn.cu.load(set_string, format='set')
except Exception as exception:
ret['message'] = 'Could not load configuration due to error "{0}"'.format(
exception)
ret['out'] = False
return ret
try:
commit_ok = conn.cu.commit_check()
except Exception as exception:
ret['message'] = 'Could not commit check due to error "{0}"'.format(
exception)
ret['out'] = False
return ret
if commit_ok:
try:
conn.cu.commit(**op)
ret['message'] = 'Successfully changed hostname.'
ret['out'] = True
except Exception as exception:
ret['out'] = False
ret['message'] = 'Successfully loaded host-name but commit failed with "{0}"'.format(
exception)
return ret
else:
ret['out'] = False
ret[
'message'] = 'Successfully loaded host-name but pre-commit check failed.'
conn.cu.rollback()
return ret | python | def set_hostname(hostname=None, **kwargs):
'''
Set the device's hostname
hostname
The name to be set
comment
Provide a comment to the commit
dev_timeout : 30
The NETCONF RPC timeout (in seconds)
confirm
Provide time in minutes for commit confirmation. If this option is
specified, the commit will be rolled back in the specified amount of time
unless the commit is confirmed.
CLI Example:
.. code-block:: bash
salt 'device_name' junos.set_hostname salt-device
'''
conn = __proxy__['junos.conn']()
ret = {}
if hostname is None:
ret['message'] = 'Please provide the hostname.'
ret['out'] = False
return ret
op = dict()
if '__pub_arg' in kwargs:
if kwargs['__pub_arg']:
if isinstance(kwargs['__pub_arg'][-1], dict):
op.update(kwargs['__pub_arg'][-1])
else:
op.update(kwargs)
# Added to recent versions of JunOs
# Use text format instead
set_string = 'set system host-name {0}'.format(hostname)
try:
conn.cu.load(set_string, format='set')
except Exception as exception:
ret['message'] = 'Could not load configuration due to error "{0}"'.format(
exception)
ret['out'] = False
return ret
try:
commit_ok = conn.cu.commit_check()
except Exception as exception:
ret['message'] = 'Could not commit check due to error "{0}"'.format(
exception)
ret['out'] = False
return ret
if commit_ok:
try:
conn.cu.commit(**op)
ret['message'] = 'Successfully changed hostname.'
ret['out'] = True
except Exception as exception:
ret['out'] = False
ret['message'] = 'Successfully loaded host-name but commit failed with "{0}"'.format(
exception)
return ret
else:
ret['out'] = False
ret[
'message'] = 'Successfully loaded host-name but pre-commit check failed.'
conn.cu.rollback()
return ret | [
"def",
"set_hostname",
"(",
"hostname",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"conn",
"=",
"__proxy__",
"[",
"'junos.conn'",
"]",
"(",
")",
"ret",
"=",
"{",
"}",
"if",
"hostname",
"is",
"None",
":",
"ret",
"[",
"'message'",
"]",
"=",
"'Pl... | Set the device's hostname
hostname
The name to be set
comment
Provide a comment to the commit
dev_timeout : 30
The NETCONF RPC timeout (in seconds)
confirm
Provide time in minutes for commit confirmation. If this option is
specified, the commit will be rolled back in the specified amount of time
unless the commit is confirmed.
CLI Example:
.. code-block:: bash
salt 'device_name' junos.set_hostname salt-device | [
"Set",
"the",
"device",
"s",
"hostname"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/junos.py#L279-L353 | train |
saltstack/salt | salt/modules/junos.py | commit | def commit(**kwargs):
'''
To commit the changes loaded in the candidate configuration.
dev_timeout : 30
The NETCONF RPC timeout (in seconds)
comment
Provide a comment for the commit
confirm
Provide time in minutes for commit confirmation. If this option is
specified, the commit will be rolled back in the specified amount of time
unless the commit is confirmed.
sync : False
When ``True``, on dual control plane systems, requests that the candidate
configuration on one control plane be copied to the other control plane,
checked for correct syntax, and committed on both Routing Engines.
force_sync : False
When ``True``, on dual control plane systems, force the candidate
configuration on one control plane to be copied to the other control
plane.
full
When ``True``, requires all the daemons to check and evaluate the new
configuration.
detail
When ``True``, return commit detail
CLI Examples:
.. code-block:: bash
salt 'device_name' junos.commit comment='Commiting via saltstack' detail=True
salt 'device_name' junos.commit dev_timeout=60 confirm=10
salt 'device_name' junos.commit sync=True dev_timeout=90
'''
conn = __proxy__['junos.conn']()
ret = {}
op = dict()
if '__pub_arg' in kwargs:
if kwargs['__pub_arg']:
if isinstance(kwargs['__pub_arg'][-1], dict):
op.update(kwargs['__pub_arg'][-1])
else:
op.update(kwargs)
op['detail'] = op.get('detail', False)
try:
commit_ok = conn.cu.commit_check()
except Exception as exception:
ret['message'] = 'Could not perform commit check due to "{0}"'.format(
exception)
ret['out'] = False
return ret
if commit_ok:
try:
commit = conn.cu.commit(**op)
ret['out'] = True
if commit:
if op['detail']:
ret['message'] = jxmlease.parse(etree.tostring(commit))
else:
ret['message'] = 'Commit Successful.'
else:
ret['message'] = 'Commit failed.'
ret['out'] = False
except Exception as exception:
ret['out'] = False
ret['message'] = \
'Commit check succeeded but actual commit failed with "{0}"' \
.format(exception)
else:
ret['out'] = False
ret['message'] = 'Pre-commit check failed.'
conn.cu.rollback()
return ret | python | def commit(**kwargs):
'''
To commit the changes loaded in the candidate configuration.
dev_timeout : 30
The NETCONF RPC timeout (in seconds)
comment
Provide a comment for the commit
confirm
Provide time in minutes for commit confirmation. If this option is
specified, the commit will be rolled back in the specified amount of time
unless the commit is confirmed.
sync : False
When ``True``, on dual control plane systems, requests that the candidate
configuration on one control plane be copied to the other control plane,
checked for correct syntax, and committed on both Routing Engines.
force_sync : False
When ``True``, on dual control plane systems, force the candidate
configuration on one control plane to be copied to the other control
plane.
full
When ``True``, requires all the daemons to check and evaluate the new
configuration.
detail
When ``True``, return commit detail
CLI Examples:
.. code-block:: bash
salt 'device_name' junos.commit comment='Commiting via saltstack' detail=True
salt 'device_name' junos.commit dev_timeout=60 confirm=10
salt 'device_name' junos.commit sync=True dev_timeout=90
'''
conn = __proxy__['junos.conn']()
ret = {}
op = dict()
if '__pub_arg' in kwargs:
if kwargs['__pub_arg']:
if isinstance(kwargs['__pub_arg'][-1], dict):
op.update(kwargs['__pub_arg'][-1])
else:
op.update(kwargs)
op['detail'] = op.get('detail', False)
try:
commit_ok = conn.cu.commit_check()
except Exception as exception:
ret['message'] = 'Could not perform commit check due to "{0}"'.format(
exception)
ret['out'] = False
return ret
if commit_ok:
try:
commit = conn.cu.commit(**op)
ret['out'] = True
if commit:
if op['detail']:
ret['message'] = jxmlease.parse(etree.tostring(commit))
else:
ret['message'] = 'Commit Successful.'
else:
ret['message'] = 'Commit failed.'
ret['out'] = False
except Exception as exception:
ret['out'] = False
ret['message'] = \
'Commit check succeeded but actual commit failed with "{0}"' \
.format(exception)
else:
ret['out'] = False
ret['message'] = 'Pre-commit check failed.'
conn.cu.rollback()
return ret | [
"def",
"commit",
"(",
"*",
"*",
"kwargs",
")",
":",
"conn",
"=",
"__proxy__",
"[",
"'junos.conn'",
"]",
"(",
")",
"ret",
"=",
"{",
"}",
"op",
"=",
"dict",
"(",
")",
"if",
"'__pub_arg'",
"in",
"kwargs",
":",
"if",
"kwargs",
"[",
"'__pub_arg'",
"]",
... | To commit the changes loaded in the candidate configuration.
dev_timeout : 30
The NETCONF RPC timeout (in seconds)
comment
Provide a comment for the commit
confirm
Provide time in minutes for commit confirmation. If this option is
specified, the commit will be rolled back in the specified amount of time
unless the commit is confirmed.
sync : False
When ``True``, on dual control plane systems, requests that the candidate
configuration on one control plane be copied to the other control plane,
checked for correct syntax, and committed on both Routing Engines.
force_sync : False
When ``True``, on dual control plane systems, force the candidate
configuration on one control plane to be copied to the other control
plane.
full
When ``True``, requires all the daemons to check and evaluate the new
configuration.
detail
When ``True``, return commit detail
CLI Examples:
.. code-block:: bash
salt 'device_name' junos.commit comment='Commiting via saltstack' detail=True
salt 'device_name' junos.commit dev_timeout=60 confirm=10
salt 'device_name' junos.commit sync=True dev_timeout=90 | [
"To",
"commit",
"the",
"changes",
"loaded",
"in",
"the",
"candidate",
"configuration",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/junos.py#L357-L440 | train |
saltstack/salt | salt/modules/junos.py | rollback | def rollback(**kwargs):
'''
Roll back the last committed configuration changes and commit
id : 0
The rollback ID value (0-49)
dev_timeout : 30
The NETCONF RPC timeout (in seconds)
comment
Provide a comment for the commit
confirm
Provide time in minutes for commit confirmation. If this option is
specified, the commit will be rolled back in the specified amount of time
unless the commit is confirmed.
diffs_file
Path to the file where the diff (difference in old configuration and the
committed configuration) will be stored. Note that the file will be
stored on the proxy minion. To push the files to the master use
:py:func:`cp.push <salt.modules.cp.push>`.
CLI Example:
.. code-block:: bash
salt 'device_name' junos.rollback 10
'''
id_ = kwargs.pop('id', 0)
ret = {}
conn = __proxy__['junos.conn']()
op = dict()
if '__pub_arg' in kwargs:
if kwargs['__pub_arg']:
if isinstance(kwargs['__pub_arg'][-1], dict):
op.update(kwargs['__pub_arg'][-1])
else:
op.update(kwargs)
try:
ret['out'] = conn.cu.rollback(id_)
except Exception as exception:
ret['message'] = 'Rollback failed due to "{0}"'.format(exception)
ret['out'] = False
return ret
if ret['out']:
ret['message'] = 'Rollback successful'
else:
ret['message'] = 'Rollback failed'
return ret
if 'diffs_file' in op and op['diffs_file'] is not None:
diff = conn.cu.diff()
if diff is not None:
with salt.utils.files.fopen(op['diffs_file'], 'w') as fp:
fp.write(salt.utils.stringutils.to_str(diff))
else:
log.info(
'No diff between current configuration and \
rollbacked configuration, so no diff file created')
try:
commit_ok = conn.cu.commit_check()
except Exception as exception:
ret['message'] = 'Could not commit check due to "{0}"'.format(
exception)
ret['out'] = False
return ret
if commit_ok:
try:
conn.cu.commit(**op)
ret['out'] = True
except Exception as exception:
ret['out'] = False
ret['message'] = \
'Rollback successful but commit failed with error "{0}"'\
.format(exception)
return ret
else:
ret['message'] = 'Rollback succesfull but pre-commit check failed.'
ret['out'] = False
return ret | python | def rollback(**kwargs):
'''
Roll back the last committed configuration changes and commit
id : 0
The rollback ID value (0-49)
dev_timeout : 30
The NETCONF RPC timeout (in seconds)
comment
Provide a comment for the commit
confirm
Provide time in minutes for commit confirmation. If this option is
specified, the commit will be rolled back in the specified amount of time
unless the commit is confirmed.
diffs_file
Path to the file where the diff (difference in old configuration and the
committed configuration) will be stored. Note that the file will be
stored on the proxy minion. To push the files to the master use
:py:func:`cp.push <salt.modules.cp.push>`.
CLI Example:
.. code-block:: bash
salt 'device_name' junos.rollback 10
'''
id_ = kwargs.pop('id', 0)
ret = {}
conn = __proxy__['junos.conn']()
op = dict()
if '__pub_arg' in kwargs:
if kwargs['__pub_arg']:
if isinstance(kwargs['__pub_arg'][-1], dict):
op.update(kwargs['__pub_arg'][-1])
else:
op.update(kwargs)
try:
ret['out'] = conn.cu.rollback(id_)
except Exception as exception:
ret['message'] = 'Rollback failed due to "{0}"'.format(exception)
ret['out'] = False
return ret
if ret['out']:
ret['message'] = 'Rollback successful'
else:
ret['message'] = 'Rollback failed'
return ret
if 'diffs_file' in op and op['diffs_file'] is not None:
diff = conn.cu.diff()
if diff is not None:
with salt.utils.files.fopen(op['diffs_file'], 'w') as fp:
fp.write(salt.utils.stringutils.to_str(diff))
else:
log.info(
'No diff between current configuration and \
rollbacked configuration, so no diff file created')
try:
commit_ok = conn.cu.commit_check()
except Exception as exception:
ret['message'] = 'Could not commit check due to "{0}"'.format(
exception)
ret['out'] = False
return ret
if commit_ok:
try:
conn.cu.commit(**op)
ret['out'] = True
except Exception as exception:
ret['out'] = False
ret['message'] = \
'Rollback successful but commit failed with error "{0}"'\
.format(exception)
return ret
else:
ret['message'] = 'Rollback succesfull but pre-commit check failed.'
ret['out'] = False
return ret | [
"def",
"rollback",
"(",
"*",
"*",
"kwargs",
")",
":",
"id_",
"=",
"kwargs",
".",
"pop",
"(",
"'id'",
",",
"0",
")",
"ret",
"=",
"{",
"}",
"conn",
"=",
"__proxy__",
"[",
"'junos.conn'",
"]",
"(",
")",
"op",
"=",
"dict",
"(",
")",
"if",
"'__pub_a... | Roll back the last committed configuration changes and commit
id : 0
The rollback ID value (0-49)
dev_timeout : 30
The NETCONF RPC timeout (in seconds)
comment
Provide a comment for the commit
confirm
Provide time in minutes for commit confirmation. If this option is
specified, the commit will be rolled back in the specified amount of time
unless the commit is confirmed.
diffs_file
Path to the file where the diff (difference in old configuration and the
committed configuration) will be stored. Note that the file will be
stored on the proxy minion. To push the files to the master use
:py:func:`cp.push <salt.modules.cp.push>`.
CLI Example:
.. code-block:: bash
salt 'device_name' junos.rollback 10 | [
"Roll",
"back",
"the",
"last",
"committed",
"configuration",
"changes",
"and",
"commit"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/junos.py#L444-L531 | train |
saltstack/salt | salt/modules/junos.py | diff | def diff(**kwargs):
'''
Returns the difference between the candidate and the current configuration
id : 0
The rollback ID value (0-49)
CLI Example:
.. code-block:: bash
salt 'device_name' junos.diff 3
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
id_ = kwargs.pop('id', 0)
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
conn = __proxy__['junos.conn']()
ret = {}
ret['out'] = True
try:
ret['message'] = conn.cu.diff(rb_id=id_)
except Exception as exception:
ret['message'] = 'Could not get diff with error "{0}"'.format(
exception)
ret['out'] = False
return ret | python | def diff(**kwargs):
'''
Returns the difference between the candidate and the current configuration
id : 0
The rollback ID value (0-49)
CLI Example:
.. code-block:: bash
salt 'device_name' junos.diff 3
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
id_ = kwargs.pop('id', 0)
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
conn = __proxy__['junos.conn']()
ret = {}
ret['out'] = True
try:
ret['message'] = conn.cu.diff(rb_id=id_)
except Exception as exception:
ret['message'] = 'Could not get diff with error "{0}"'.format(
exception)
ret['out'] = False
return ret | [
"def",
"diff",
"(",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"=",
"salt",
".",
"utils",
".",
"args",
".",
"clean_kwargs",
"(",
"*",
"*",
"kwargs",
")",
"id_",
"=",
"kwargs",
".",
"pop",
"(",
"'id'",
",",
"0",
")",
"if",
"kwargs",
":",
"salt",
".... | Returns the difference between the candidate and the current configuration
id : 0
The rollback ID value (0-49)
CLI Example:
.. code-block:: bash
salt 'device_name' junos.diff 3 | [
"Returns",
"the",
"difference",
"between",
"the",
"candidate",
"and",
"the",
"current",
"configuration"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/junos.py#L534-L562 | train |
saltstack/salt | salt/modules/junos.py | ping | def ping(dest_ip=None, **kwargs):
'''
Send a ping RPC to a device
dest_ip
The IP of the device to ping
dev_timeout : 30
The NETCONF RPC timeout (in seconds)
rapid : False
When ``True``, executes ping at 100pps instead of 1pps
ttl
Maximum number of IP routers (IP hops) allowed between source and
destination
routing_instance
Name of the routing instance to use to send the ping
interface
Interface used to send traffic
count : 5
Number of packets to send
CLI Examples:
.. code-block:: bash
salt 'device_name' junos.ping '8.8.8.8' count=5
salt 'device_name' junos.ping '8.8.8.8' ttl=1 rapid=True
'''
conn = __proxy__['junos.conn']()
ret = {}
if dest_ip is None:
ret['message'] = 'Please specify the destination ip to ping.'
ret['out'] = False
return ret
op = {'host': dest_ip}
if '__pub_arg' in kwargs:
if kwargs['__pub_arg']:
if isinstance(kwargs['__pub_arg'][-1], dict):
op.update(kwargs['__pub_arg'][-1])
else:
op.update(kwargs)
op['count'] = six.text_type(op.pop('count', 5))
if 'ttl' in op:
op['ttl'] = six.text_type(op['ttl'])
ret['out'] = True
try:
ret['message'] = jxmlease.parse(etree.tostring(conn.rpc.ping(**op)))
except Exception as exception:
ret['message'] = 'Execution failed due to "{0}"'.format(exception)
ret['out'] = False
return ret | python | def ping(dest_ip=None, **kwargs):
'''
Send a ping RPC to a device
dest_ip
The IP of the device to ping
dev_timeout : 30
The NETCONF RPC timeout (in seconds)
rapid : False
When ``True``, executes ping at 100pps instead of 1pps
ttl
Maximum number of IP routers (IP hops) allowed between source and
destination
routing_instance
Name of the routing instance to use to send the ping
interface
Interface used to send traffic
count : 5
Number of packets to send
CLI Examples:
.. code-block:: bash
salt 'device_name' junos.ping '8.8.8.8' count=5
salt 'device_name' junos.ping '8.8.8.8' ttl=1 rapid=True
'''
conn = __proxy__['junos.conn']()
ret = {}
if dest_ip is None:
ret['message'] = 'Please specify the destination ip to ping.'
ret['out'] = False
return ret
op = {'host': dest_ip}
if '__pub_arg' in kwargs:
if kwargs['__pub_arg']:
if isinstance(kwargs['__pub_arg'][-1], dict):
op.update(kwargs['__pub_arg'][-1])
else:
op.update(kwargs)
op['count'] = six.text_type(op.pop('count', 5))
if 'ttl' in op:
op['ttl'] = six.text_type(op['ttl'])
ret['out'] = True
try:
ret['message'] = jxmlease.parse(etree.tostring(conn.rpc.ping(**op)))
except Exception as exception:
ret['message'] = 'Execution failed due to "{0}"'.format(exception)
ret['out'] = False
return ret | [
"def",
"ping",
"(",
"dest_ip",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"conn",
"=",
"__proxy__",
"[",
"'junos.conn'",
"]",
"(",
")",
"ret",
"=",
"{",
"}",
"if",
"dest_ip",
"is",
"None",
":",
"ret",
"[",
"'message'",
"]",
"=",
"'Please speci... | Send a ping RPC to a device
dest_ip
The IP of the device to ping
dev_timeout : 30
The NETCONF RPC timeout (in seconds)
rapid : False
When ``True``, executes ping at 100pps instead of 1pps
ttl
Maximum number of IP routers (IP hops) allowed between source and
destination
routing_instance
Name of the routing instance to use to send the ping
interface
Interface used to send traffic
count : 5
Number of packets to send
CLI Examples:
.. code-block:: bash
salt 'device_name' junos.ping '8.8.8.8' count=5
salt 'device_name' junos.ping '8.8.8.8' ttl=1 rapid=True | [
"Send",
"a",
"ping",
"RPC",
"to",
"a",
"device"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/junos.py#L566-L625 | train |
saltstack/salt | salt/modules/junos.py | cli | def cli(command=None, **kwargs):
'''
Executes the CLI commands and returns the output in specified format. \
(default is text) The output can also be stored in a file.
command (required)
The command to execute on the Junos CLI
format : text
Format in which to get the CLI output (either ``text`` or ``xml``)
dev_timeout : 30
The NETCONF RPC timeout (in seconds)
dest
Destination file where the RPC output is stored. Note that the file
will be stored on the proxy minion. To push the files to the master use
:py:func:`cp.push <salt.modules.cp.push>`.
CLI Examples:
.. code-block:: bash
salt 'device_name' junos.cli 'show system commit'
salt 'device_name' junos.cli 'show system alarms' format=xml dest=/home/user/cli_output.txt
'''
conn = __proxy__['junos.conn']()
format_ = kwargs.pop('format', 'text')
if not format_:
format_ = 'text'
ret = {}
if command is None:
ret['message'] = 'Please provide the CLI command to be executed.'
ret['out'] = False
return ret
op = dict()
if '__pub_arg' in kwargs:
if kwargs['__pub_arg']:
if isinstance(kwargs['__pub_arg'][-1], dict):
op.update(kwargs['__pub_arg'][-1])
else:
op.update(kwargs)
try:
result = conn.cli(command, format_, warning=False)
except Exception as exception:
ret['message'] = 'Execution failed due to "{0}"'.format(exception)
ret['out'] = False
return ret
if format_ == 'text':
ret['message'] = result
else:
result = etree.tostring(result)
ret['message'] = jxmlease.parse(result)
if 'dest' in op and op['dest'] is not None:
with salt.utils.files.fopen(op['dest'], 'w') as fp:
fp.write(salt.utils.stringutils.to_str(result))
ret['out'] = True
return ret | python | def cli(command=None, **kwargs):
'''
Executes the CLI commands and returns the output in specified format. \
(default is text) The output can also be stored in a file.
command (required)
The command to execute on the Junos CLI
format : text
Format in which to get the CLI output (either ``text`` or ``xml``)
dev_timeout : 30
The NETCONF RPC timeout (in seconds)
dest
Destination file where the RPC output is stored. Note that the file
will be stored on the proxy minion. To push the files to the master use
:py:func:`cp.push <salt.modules.cp.push>`.
CLI Examples:
.. code-block:: bash
salt 'device_name' junos.cli 'show system commit'
salt 'device_name' junos.cli 'show system alarms' format=xml dest=/home/user/cli_output.txt
'''
conn = __proxy__['junos.conn']()
format_ = kwargs.pop('format', 'text')
if not format_:
format_ = 'text'
ret = {}
if command is None:
ret['message'] = 'Please provide the CLI command to be executed.'
ret['out'] = False
return ret
op = dict()
if '__pub_arg' in kwargs:
if kwargs['__pub_arg']:
if isinstance(kwargs['__pub_arg'][-1], dict):
op.update(kwargs['__pub_arg'][-1])
else:
op.update(kwargs)
try:
result = conn.cli(command, format_, warning=False)
except Exception as exception:
ret['message'] = 'Execution failed due to "{0}"'.format(exception)
ret['out'] = False
return ret
if format_ == 'text':
ret['message'] = result
else:
result = etree.tostring(result)
ret['message'] = jxmlease.parse(result)
if 'dest' in op and op['dest'] is not None:
with salt.utils.files.fopen(op['dest'], 'w') as fp:
fp.write(salt.utils.stringutils.to_str(result))
ret['out'] = True
return ret | [
"def",
"cli",
"(",
"command",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"conn",
"=",
"__proxy__",
"[",
"'junos.conn'",
"]",
"(",
")",
"format_",
"=",
"kwargs",
".",
"pop",
"(",
"'format'",
",",
"'text'",
")",
"if",
"not",
"format_",
":",
"for... | Executes the CLI commands and returns the output in specified format. \
(default is text) The output can also be stored in a file.
command (required)
The command to execute on the Junos CLI
format : text
Format in which to get the CLI output (either ``text`` or ``xml``)
dev_timeout : 30
The NETCONF RPC timeout (in seconds)
dest
Destination file where the RPC output is stored. Note that the file
will be stored on the proxy minion. To push the files to the master use
:py:func:`cp.push <salt.modules.cp.push>`.
CLI Examples:
.. code-block:: bash
salt 'device_name' junos.cli 'show system commit'
salt 'device_name' junos.cli 'show system alarms' format=xml dest=/home/user/cli_output.txt | [
"Executes",
"the",
"CLI",
"commands",
"and",
"returns",
"the",
"output",
"in",
"specified",
"format",
".",
"\\",
"(",
"default",
"is",
"text",
")",
"The",
"output",
"can",
"also",
"be",
"stored",
"in",
"a",
"file",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/junos.py#L629-L693 | train |
saltstack/salt | salt/modules/junos.py | shutdown | def shutdown(**kwargs):
'''
Shut down (power off) or reboot a device running Junos OS. This includes
all Routing Engines in a Virtual Chassis or a dual Routing Engine system.
.. note::
One of ``shutdown`` or ``reboot`` must be set to ``True`` or no
action will be taken.
shutdown : False
Set this to ``True`` if you want to shutdown the machine. This is a
safety mechanism so that the user does not accidentally shutdown the
junos device.
reboot : False
If ``True``, reboot instead of shutting down
at
Used when rebooting, to specify the date and time the reboot should take
place. The value of this option must match the JunOS CLI reboot syntax.
in_min
Used when shutting down. Specify the delay (in minutes) before the
device will be shut down.
CLI Examples:
.. code-block:: bash
salt 'device_name' junos.shutdown reboot=True
salt 'device_name' junos.shutdown shutdown=True in_min=10
salt 'device_name' junos.shutdown shutdown=True
'''
conn = __proxy__['junos.conn']()
ret = {}
sw = SW(conn)
op = {}
if '__pub_arg' in kwargs:
if kwargs['__pub_arg']:
if isinstance(kwargs['__pub_arg'][-1], dict):
op.update(kwargs['__pub_arg'][-1])
else:
op.update(kwargs)
if 'shutdown' not in op and 'reboot' not in op:
ret['message'] = \
'Provide either one of the arguments: shutdown or reboot.'
ret['out'] = False
return ret
try:
if 'reboot' in op and op['reboot']:
shut = sw.reboot
elif 'shutdown' in op and op['shutdown']:
shut = sw.poweroff
else:
ret['message'] = 'Nothing to be done.'
ret['out'] = False
return ret
if 'in_min' in op:
shut(in_min=op['in_min'])
elif 'at' in op:
shut(at=op['at'])
else:
shut()
ret['message'] = 'Successfully powered off/rebooted.'
ret['out'] = True
except Exception as exception:
ret['message'] = \
'Could not poweroff/reboot beacause "{0}"'.format(exception)
ret['out'] = False
return ret | python | def shutdown(**kwargs):
'''
Shut down (power off) or reboot a device running Junos OS. This includes
all Routing Engines in a Virtual Chassis or a dual Routing Engine system.
.. note::
One of ``shutdown`` or ``reboot`` must be set to ``True`` or no
action will be taken.
shutdown : False
Set this to ``True`` if you want to shutdown the machine. This is a
safety mechanism so that the user does not accidentally shutdown the
junos device.
reboot : False
If ``True``, reboot instead of shutting down
at
Used when rebooting, to specify the date and time the reboot should take
place. The value of this option must match the JunOS CLI reboot syntax.
in_min
Used when shutting down. Specify the delay (in minutes) before the
device will be shut down.
CLI Examples:
.. code-block:: bash
salt 'device_name' junos.shutdown reboot=True
salt 'device_name' junos.shutdown shutdown=True in_min=10
salt 'device_name' junos.shutdown shutdown=True
'''
conn = __proxy__['junos.conn']()
ret = {}
sw = SW(conn)
op = {}
if '__pub_arg' in kwargs:
if kwargs['__pub_arg']:
if isinstance(kwargs['__pub_arg'][-1], dict):
op.update(kwargs['__pub_arg'][-1])
else:
op.update(kwargs)
if 'shutdown' not in op and 'reboot' not in op:
ret['message'] = \
'Provide either one of the arguments: shutdown or reboot.'
ret['out'] = False
return ret
try:
if 'reboot' in op and op['reboot']:
shut = sw.reboot
elif 'shutdown' in op and op['shutdown']:
shut = sw.poweroff
else:
ret['message'] = 'Nothing to be done.'
ret['out'] = False
return ret
if 'in_min' in op:
shut(in_min=op['in_min'])
elif 'at' in op:
shut(at=op['at'])
else:
shut()
ret['message'] = 'Successfully powered off/rebooted.'
ret['out'] = True
except Exception as exception:
ret['message'] = \
'Could not poweroff/reboot beacause "{0}"'.format(exception)
ret['out'] = False
return ret | [
"def",
"shutdown",
"(",
"*",
"*",
"kwargs",
")",
":",
"conn",
"=",
"__proxy__",
"[",
"'junos.conn'",
"]",
"(",
")",
"ret",
"=",
"{",
"}",
"sw",
"=",
"SW",
"(",
"conn",
")",
"op",
"=",
"{",
"}",
"if",
"'__pub_arg'",
"in",
"kwargs",
":",
"if",
"k... | Shut down (power off) or reboot a device running Junos OS. This includes
all Routing Engines in a Virtual Chassis or a dual Routing Engine system.
.. note::
One of ``shutdown`` or ``reboot`` must be set to ``True`` or no
action will be taken.
shutdown : False
Set this to ``True`` if you want to shutdown the machine. This is a
safety mechanism so that the user does not accidentally shutdown the
junos device.
reboot : False
If ``True``, reboot instead of shutting down
at
Used when rebooting, to specify the date and time the reboot should take
place. The value of this option must match the JunOS CLI reboot syntax.
in_min
Used when shutting down. Specify the delay (in minutes) before the
device will be shut down.
CLI Examples:
.. code-block:: bash
salt 'device_name' junos.shutdown reboot=True
salt 'device_name' junos.shutdown shutdown=True in_min=10
salt 'device_name' junos.shutdown shutdown=True | [
"Shut",
"down",
"(",
"power",
"off",
")",
"or",
"reboot",
"a",
"device",
"running",
"Junos",
"OS",
".",
"This",
"includes",
"all",
"Routing",
"Engines",
"in",
"a",
"Virtual",
"Chassis",
"or",
"a",
"dual",
"Routing",
"Engine",
"system",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/junos.py#L696-L768 | train |
saltstack/salt | salt/modules/junos.py | install_config | def install_config(path=None, **kwargs):
'''
Installs the given configuration file into the candidate configuration.
Commits the changes if the commit checks or throws an error.
path (required)
Path where the configuration/template file is present. If the file has
a ``.conf`` extension, the content is treated as text format. If the
file has a ``.xml`` extension, the content is treated as XML format. If
the file has a ``.set`` extension, the content is treated as Junos OS
``set`` commands.
mode : exclusive
The mode in which the configuration is locked. Can be one of
``private``, ``dynamic``, ``batch``, ``exclusive``.
dev_timeout : 30
Set NETCONF RPC timeout. Can be used for commands which take a while to
execute.
overwrite : False
Set to ``True`` if you want this file is to completely replace the
configuration file.
replace : False
Specify whether the configuration file uses ``replace:`` statements. If
``True``, only those statements under the ``replace`` tag will be
changed.
format
Determines the format of the contents
update : False
Compare a complete loaded configuration against the candidate
configuration. For each hierarchy level or configuration object that is
different in the two configurations, the version in the loaded
configuration replaces the version in the candidate configuration. When
the configuration is later committed, only system processes that are
affected by the changed configuration elements parse the new
configuration. This action is supported from PyEZ 2.1.
comment
Provide a comment for the commit
confirm
Provide time in minutes for commit confirmation. If this option is
specified, the commit will be rolled back in the specified amount of time
unless the commit is confirmed.
diffs_file
Path to the file where the diff (difference in old configuration and the
committed configuration) will be stored. Note that the file will be
stored on the proxy minion. To push the files to the master use
:py:func:`cp.push <salt.modules.cp.push>`.
template_vars
Variables to be passed into the template processing engine in addition to
those present in pillar, the minion configuration, grains, etc. You may
reference these variables in your template like so:
.. code-block:: jinja
{{ template_vars["var_name"] }}
CLI Examples:
.. code-block:: bash
salt 'device_name' junos.install_config 'salt://production/network/routers/config.set'
salt 'device_name' junos.install_config 'salt://templates/replace_config.conf' replace=True comment='Committed via SaltStack'
salt 'device_name' junos.install_config 'salt://my_new_configuration.conf' dev_timeout=300 diffs_file='/salt/confs/old_config.conf' overwrite=True
salt 'device_name' junos.install_config 'salt://syslog_template.conf' template_vars='{"syslog_host": "10.180.222.7"}'
'''
conn = __proxy__['junos.conn']()
ret = {}
ret['out'] = True
if path is None:
ret['message'] = \
'Please provide the salt path where the configuration is present'
ret['out'] = False
return ret
op = {}
if '__pub_arg' in kwargs:
if kwargs['__pub_arg']:
if isinstance(kwargs['__pub_arg'][-1], dict):
op.update(kwargs['__pub_arg'][-1])
else:
op.update(kwargs)
test = op.pop('test', False)
template_vars = {}
if "template_vars" in op:
template_vars = op["template_vars"]
template_cached_path = salt.utils.files.mkstemp()
__salt__['cp.get_template'](
path,
template_cached_path,
template_vars=template_vars)
if not os.path.isfile(template_cached_path):
ret['message'] = 'Invalid file path.'
ret['out'] = False
return ret
if os.path.getsize(template_cached_path) == 0:
ret['message'] = 'Template failed to render'
ret['out'] = False
return ret
write_diff = ''
if 'diffs_file' in op and op['diffs_file'] is not None:
write_diff = op['diffs_file']
del op['diffs_file']
op['path'] = template_cached_path
if 'format' not in op:
if path.endswith('set'):
template_format = 'set'
elif path.endswith('xml'):
template_format = 'xml'
else:
template_format = 'text'
op['format'] = template_format
if 'replace' in op and op['replace']:
op['merge'] = False
del op['replace']
elif 'overwrite' in op and op['overwrite']:
op['overwrite'] = True
elif 'overwrite' in op and not op['overwrite']:
op['merge'] = True
del op['overwrite']
db_mode = op.pop('mode', 'exclusive')
with Config(conn, mode=db_mode) as cu:
try:
cu.load(**op)
except Exception as exception:
ret['message'] = 'Could not load configuration due to : "{0}"'.format(
exception)
ret['format'] = op['format']
ret['out'] = False
return ret
finally:
salt.utils.files.safe_rm(template_cached_path)
config_diff = cu.diff()
if config_diff is None:
ret['message'] = 'Configuration already applied!'
ret['out'] = True
return ret
commit_params = {}
if 'confirm' in op:
commit_params['confirm'] = op['confirm']
if 'comment' in op:
commit_params['comment'] = op['comment']
try:
check = cu.commit_check()
except Exception as exception:
ret['message'] = \
'Commit check threw the following exception: "{0}"'\
.format(exception)
ret['out'] = False
return ret
if check and not test:
try:
cu.commit(**commit_params)
ret['message'] = 'Successfully loaded and committed!'
except Exception as exception:
ret['message'] = \
'Commit check successful but commit failed with "{0}"'\
.format(exception)
ret['out'] = False
return ret
elif not check:
cu.rollback()
ret['message'] = 'Loaded configuration but commit check failed, hence rolling back configuration.'
ret['out'] = False
else:
cu.rollback()
ret['message'] = 'Commit check passed, but skipping commit for dry-run and rolling back configuration.'
ret['out'] = True
try:
if write_diff and config_diff is not None:
with salt.utils.files.fopen(write_diff, 'w') as fp:
fp.write(salt.utils.stringutils.to_str(config_diff))
except Exception as exception:
ret['message'] = 'Could not write into diffs_file due to: "{0}"'.format(
exception)
ret['out'] = False
return ret | python | def install_config(path=None, **kwargs):
'''
Installs the given configuration file into the candidate configuration.
Commits the changes if the commit checks or throws an error.
path (required)
Path where the configuration/template file is present. If the file has
a ``.conf`` extension, the content is treated as text format. If the
file has a ``.xml`` extension, the content is treated as XML format. If
the file has a ``.set`` extension, the content is treated as Junos OS
``set`` commands.
mode : exclusive
The mode in which the configuration is locked. Can be one of
``private``, ``dynamic``, ``batch``, ``exclusive``.
dev_timeout : 30
Set NETCONF RPC timeout. Can be used for commands which take a while to
execute.
overwrite : False
Set to ``True`` if you want this file is to completely replace the
configuration file.
replace : False
Specify whether the configuration file uses ``replace:`` statements. If
``True``, only those statements under the ``replace`` tag will be
changed.
format
Determines the format of the contents
update : False
Compare a complete loaded configuration against the candidate
configuration. For each hierarchy level or configuration object that is
different in the two configurations, the version in the loaded
configuration replaces the version in the candidate configuration. When
the configuration is later committed, only system processes that are
affected by the changed configuration elements parse the new
configuration. This action is supported from PyEZ 2.1.
comment
Provide a comment for the commit
confirm
Provide time in minutes for commit confirmation. If this option is
specified, the commit will be rolled back in the specified amount of time
unless the commit is confirmed.
diffs_file
Path to the file where the diff (difference in old configuration and the
committed configuration) will be stored. Note that the file will be
stored on the proxy minion. To push the files to the master use
:py:func:`cp.push <salt.modules.cp.push>`.
template_vars
Variables to be passed into the template processing engine in addition to
those present in pillar, the minion configuration, grains, etc. You may
reference these variables in your template like so:
.. code-block:: jinja
{{ template_vars["var_name"] }}
CLI Examples:
.. code-block:: bash
salt 'device_name' junos.install_config 'salt://production/network/routers/config.set'
salt 'device_name' junos.install_config 'salt://templates/replace_config.conf' replace=True comment='Committed via SaltStack'
salt 'device_name' junos.install_config 'salt://my_new_configuration.conf' dev_timeout=300 diffs_file='/salt/confs/old_config.conf' overwrite=True
salt 'device_name' junos.install_config 'salt://syslog_template.conf' template_vars='{"syslog_host": "10.180.222.7"}'
'''
conn = __proxy__['junos.conn']()
ret = {}
ret['out'] = True
if path is None:
ret['message'] = \
'Please provide the salt path where the configuration is present'
ret['out'] = False
return ret
op = {}
if '__pub_arg' in kwargs:
if kwargs['__pub_arg']:
if isinstance(kwargs['__pub_arg'][-1], dict):
op.update(kwargs['__pub_arg'][-1])
else:
op.update(kwargs)
test = op.pop('test', False)
template_vars = {}
if "template_vars" in op:
template_vars = op["template_vars"]
template_cached_path = salt.utils.files.mkstemp()
__salt__['cp.get_template'](
path,
template_cached_path,
template_vars=template_vars)
if not os.path.isfile(template_cached_path):
ret['message'] = 'Invalid file path.'
ret['out'] = False
return ret
if os.path.getsize(template_cached_path) == 0:
ret['message'] = 'Template failed to render'
ret['out'] = False
return ret
write_diff = ''
if 'diffs_file' in op and op['diffs_file'] is not None:
write_diff = op['diffs_file']
del op['diffs_file']
op['path'] = template_cached_path
if 'format' not in op:
if path.endswith('set'):
template_format = 'set'
elif path.endswith('xml'):
template_format = 'xml'
else:
template_format = 'text'
op['format'] = template_format
if 'replace' in op and op['replace']:
op['merge'] = False
del op['replace']
elif 'overwrite' in op and op['overwrite']:
op['overwrite'] = True
elif 'overwrite' in op and not op['overwrite']:
op['merge'] = True
del op['overwrite']
db_mode = op.pop('mode', 'exclusive')
with Config(conn, mode=db_mode) as cu:
try:
cu.load(**op)
except Exception as exception:
ret['message'] = 'Could not load configuration due to : "{0}"'.format(
exception)
ret['format'] = op['format']
ret['out'] = False
return ret
finally:
salt.utils.files.safe_rm(template_cached_path)
config_diff = cu.diff()
if config_diff is None:
ret['message'] = 'Configuration already applied!'
ret['out'] = True
return ret
commit_params = {}
if 'confirm' in op:
commit_params['confirm'] = op['confirm']
if 'comment' in op:
commit_params['comment'] = op['comment']
try:
check = cu.commit_check()
except Exception as exception:
ret['message'] = \
'Commit check threw the following exception: "{0}"'\
.format(exception)
ret['out'] = False
return ret
if check and not test:
try:
cu.commit(**commit_params)
ret['message'] = 'Successfully loaded and committed!'
except Exception as exception:
ret['message'] = \
'Commit check successful but commit failed with "{0}"'\
.format(exception)
ret['out'] = False
return ret
elif not check:
cu.rollback()
ret['message'] = 'Loaded configuration but commit check failed, hence rolling back configuration.'
ret['out'] = False
else:
cu.rollback()
ret['message'] = 'Commit check passed, but skipping commit for dry-run and rolling back configuration.'
ret['out'] = True
try:
if write_diff and config_diff is not None:
with salt.utils.files.fopen(write_diff, 'w') as fp:
fp.write(salt.utils.stringutils.to_str(config_diff))
except Exception as exception:
ret['message'] = 'Could not write into diffs_file due to: "{0}"'.format(
exception)
ret['out'] = False
return ret | [
"def",
"install_config",
"(",
"path",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"conn",
"=",
"__proxy__",
"[",
"'junos.conn'",
"]",
"(",
")",
"ret",
"=",
"{",
"}",
"ret",
"[",
"'out'",
"]",
"=",
"True",
"if",
"path",
"is",
"None",
":",
"ret... | Installs the given configuration file into the candidate configuration.
Commits the changes if the commit checks or throws an error.
path (required)
Path where the configuration/template file is present. If the file has
a ``.conf`` extension, the content is treated as text format. If the
file has a ``.xml`` extension, the content is treated as XML format. If
the file has a ``.set`` extension, the content is treated as Junos OS
``set`` commands.
mode : exclusive
The mode in which the configuration is locked. Can be one of
``private``, ``dynamic``, ``batch``, ``exclusive``.
dev_timeout : 30
Set NETCONF RPC timeout. Can be used for commands which take a while to
execute.
overwrite : False
Set to ``True`` if you want this file is to completely replace the
configuration file.
replace : False
Specify whether the configuration file uses ``replace:`` statements. If
``True``, only those statements under the ``replace`` tag will be
changed.
format
Determines the format of the contents
update : False
Compare a complete loaded configuration against the candidate
configuration. For each hierarchy level or configuration object that is
different in the two configurations, the version in the loaded
configuration replaces the version in the candidate configuration. When
the configuration is later committed, only system processes that are
affected by the changed configuration elements parse the new
configuration. This action is supported from PyEZ 2.1.
comment
Provide a comment for the commit
confirm
Provide time in minutes for commit confirmation. If this option is
specified, the commit will be rolled back in the specified amount of time
unless the commit is confirmed.
diffs_file
Path to the file where the diff (difference in old configuration and the
committed configuration) will be stored. Note that the file will be
stored on the proxy minion. To push the files to the master use
:py:func:`cp.push <salt.modules.cp.push>`.
template_vars
Variables to be passed into the template processing engine in addition to
those present in pillar, the minion configuration, grains, etc. You may
reference these variables in your template like so:
.. code-block:: jinja
{{ template_vars["var_name"] }}
CLI Examples:
.. code-block:: bash
salt 'device_name' junos.install_config 'salt://production/network/routers/config.set'
salt 'device_name' junos.install_config 'salt://templates/replace_config.conf' replace=True comment='Committed via SaltStack'
salt 'device_name' junos.install_config 'salt://my_new_configuration.conf' dev_timeout=300 diffs_file='/salt/confs/old_config.conf' overwrite=True
salt 'device_name' junos.install_config 'salt://syslog_template.conf' template_vars='{"syslog_host": "10.180.222.7"}' | [
"Installs",
"the",
"given",
"configuration",
"file",
"into",
"the",
"candidate",
"configuration",
".",
"Commits",
"the",
"changes",
"if",
"the",
"commit",
"checks",
"or",
"throws",
"an",
"error",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/junos.py#L772-L975 | train |
saltstack/salt | salt/modules/junos.py | zeroize | def zeroize():
'''
Resets the device to default factory settings
CLI Example:
.. code-block:: bash
salt 'device_name' junos.zeroize
'''
conn = __proxy__['junos.conn']()
ret = {}
ret['out'] = True
try:
conn.cli('request system zeroize')
ret['message'] = 'Completed zeroize and rebooted'
except Exception as exception:
ret['message'] = 'Could not zeroize due to : "{0}"'.format(exception)
ret['out'] = False
return ret | python | def zeroize():
'''
Resets the device to default factory settings
CLI Example:
.. code-block:: bash
salt 'device_name' junos.zeroize
'''
conn = __proxy__['junos.conn']()
ret = {}
ret['out'] = True
try:
conn.cli('request system zeroize')
ret['message'] = 'Completed zeroize and rebooted'
except Exception as exception:
ret['message'] = 'Could not zeroize due to : "{0}"'.format(exception)
ret['out'] = False
return ret | [
"def",
"zeroize",
"(",
")",
":",
"conn",
"=",
"__proxy__",
"[",
"'junos.conn'",
"]",
"(",
")",
"ret",
"=",
"{",
"}",
"ret",
"[",
"'out'",
"]",
"=",
"True",
"try",
":",
"conn",
".",
"cli",
"(",
"'request system zeroize'",
")",
"ret",
"[",
"'message'",... | Resets the device to default factory settings
CLI Example:
.. code-block:: bash
salt 'device_name' junos.zeroize | [
"Resets",
"the",
"device",
"to",
"default",
"factory",
"settings"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/junos.py#L978-L998 | train |
saltstack/salt | salt/modules/junos.py | install_os | def install_os(path=None, **kwargs):
'''
Installs the given image on the device. After the installation is complete\
the device is rebooted,
if reboot=True is given as a keyworded argument.
path (required)
Path where the image file is present on the proxy minion
remote_path :
If the value of path is a file path on the local
(Salt host's) filesystem, then the image is copied from the local
filesystem to the :remote_path: directory on the target Junos
device. The default is ``/var/tmp``. If the value of :path: or
is a URL, then the value of :remote_path: is unused.
dev_timeout : 30
The NETCONF RPC timeout (in seconds). This argument was added since most of
the time the "package add" RPC takes a significant amount of time. The default
RPC timeout is 30 seconds. So this :timeout: value will be
used in the context of the SW installation process. Defaults to
30 minutes (30*60=1800)
reboot : False
Whether to reboot after installation
no_copy : False
If ``True`` the software package will not be SCP’d to the device
bool validate:
When ``True`` this method will perform a config validation against
the new image
bool issu:
When ``True`` allows unified in-service software upgrade
(ISSU) feature enables you to upgrade between two different Junos OS
releases with no disruption on the control plane and with minimal
disruption of traffic.
bool nssu:
When ``True`` allows nonstop software upgrade (NSSU)
enables you to upgrade the software running on a Juniper Networks
EX Series Virtual Chassis or a Juniper Networks EX Series Ethernet
Switch with redundant Routing Engines with a single command and
minimal disruption to network traffic.
CLI Examples:
.. code-block:: bash
salt 'device_name' junos.install_os 'salt://images/junos_image.tgz' reboot=True
salt 'device_name' junos.install_os 'salt://junos_16_1.tgz' dev_timeout=300
'''
conn = __proxy__['junos.conn']()
ret = {}
ret['out'] = True
op = {}
if '__pub_arg' in kwargs:
if kwargs['__pub_arg']:
if isinstance(kwargs['__pub_arg'][-1], dict):
op.update(kwargs['__pub_arg'][-1])
else:
op.update(kwargs)
no_copy_ = op.get('no_copy', False)
if path is None:
ret['message'] = \
'Please provide the salt path where the junos image is present.'
ret['out'] = False
return ret
if not no_copy_:
image_cached_path = salt.utils.files.mkstemp()
__salt__['cp.get_file'](path, image_cached_path)
if not os.path.isfile(image_cached_path):
ret['message'] = 'Invalid image path.'
ret['out'] = False
return ret
if os.path.getsize(image_cached_path) == 0:
ret['message'] = 'Failed to copy image'
ret['out'] = False
return ret
path = image_cached_path
try:
conn.sw.install(path, progress=True, **op)
ret['message'] = 'Installed the os.'
except Exception as exception:
ret['message'] = 'Installation failed due to: "{0}"'.format(exception)
ret['out'] = False
return ret
finally:
if not no_copy_:
salt.utils.files.safe_rm(image_cached_path)
if 'reboot' in op and op['reboot'] is True:
try:
conn.sw.reboot()
except Exception as exception:
ret['message'] = \
'Installation successful but reboot failed due to : "{0}"' \
.format(exception)
ret['out'] = False
return ret
ret['message'] = 'Successfully installed and rebooted!'
return ret | python | def install_os(path=None, **kwargs):
'''
Installs the given image on the device. After the installation is complete\
the device is rebooted,
if reboot=True is given as a keyworded argument.
path (required)
Path where the image file is present on the proxy minion
remote_path :
If the value of path is a file path on the local
(Salt host's) filesystem, then the image is copied from the local
filesystem to the :remote_path: directory on the target Junos
device. The default is ``/var/tmp``. If the value of :path: or
is a URL, then the value of :remote_path: is unused.
dev_timeout : 30
The NETCONF RPC timeout (in seconds). This argument was added since most of
the time the "package add" RPC takes a significant amount of time. The default
RPC timeout is 30 seconds. So this :timeout: value will be
used in the context of the SW installation process. Defaults to
30 minutes (30*60=1800)
reboot : False
Whether to reboot after installation
no_copy : False
If ``True`` the software package will not be SCP’d to the device
bool validate:
When ``True`` this method will perform a config validation against
the new image
bool issu:
When ``True`` allows unified in-service software upgrade
(ISSU) feature enables you to upgrade between two different Junos OS
releases with no disruption on the control plane and with minimal
disruption of traffic.
bool nssu:
When ``True`` allows nonstop software upgrade (NSSU)
enables you to upgrade the software running on a Juniper Networks
EX Series Virtual Chassis or a Juniper Networks EX Series Ethernet
Switch with redundant Routing Engines with a single command and
minimal disruption to network traffic.
CLI Examples:
.. code-block:: bash
salt 'device_name' junos.install_os 'salt://images/junos_image.tgz' reboot=True
salt 'device_name' junos.install_os 'salt://junos_16_1.tgz' dev_timeout=300
'''
conn = __proxy__['junos.conn']()
ret = {}
ret['out'] = True
op = {}
if '__pub_arg' in kwargs:
if kwargs['__pub_arg']:
if isinstance(kwargs['__pub_arg'][-1], dict):
op.update(kwargs['__pub_arg'][-1])
else:
op.update(kwargs)
no_copy_ = op.get('no_copy', False)
if path is None:
ret['message'] = \
'Please provide the salt path where the junos image is present.'
ret['out'] = False
return ret
if not no_copy_:
image_cached_path = salt.utils.files.mkstemp()
__salt__['cp.get_file'](path, image_cached_path)
if not os.path.isfile(image_cached_path):
ret['message'] = 'Invalid image path.'
ret['out'] = False
return ret
if os.path.getsize(image_cached_path) == 0:
ret['message'] = 'Failed to copy image'
ret['out'] = False
return ret
path = image_cached_path
try:
conn.sw.install(path, progress=True, **op)
ret['message'] = 'Installed the os.'
except Exception as exception:
ret['message'] = 'Installation failed due to: "{0}"'.format(exception)
ret['out'] = False
return ret
finally:
if not no_copy_:
salt.utils.files.safe_rm(image_cached_path)
if 'reboot' in op and op['reboot'] is True:
try:
conn.sw.reboot()
except Exception as exception:
ret['message'] = \
'Installation successful but reboot failed due to : "{0}"' \
.format(exception)
ret['out'] = False
return ret
ret['message'] = 'Successfully installed and rebooted!'
return ret | [
"def",
"install_os",
"(",
"path",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"conn",
"=",
"__proxy__",
"[",
"'junos.conn'",
"]",
"(",
")",
"ret",
"=",
"{",
"}",
"ret",
"[",
"'out'",
"]",
"=",
"True",
"op",
"=",
"{",
"}",
"if",
"'__pub_arg'",... | Installs the given image on the device. After the installation is complete\
the device is rebooted,
if reboot=True is given as a keyworded argument.
path (required)
Path where the image file is present on the proxy minion
remote_path :
If the value of path is a file path on the local
(Salt host's) filesystem, then the image is copied from the local
filesystem to the :remote_path: directory on the target Junos
device. The default is ``/var/tmp``. If the value of :path: or
is a URL, then the value of :remote_path: is unused.
dev_timeout : 30
The NETCONF RPC timeout (in seconds). This argument was added since most of
the time the "package add" RPC takes a significant amount of time. The default
RPC timeout is 30 seconds. So this :timeout: value will be
used in the context of the SW installation process. Defaults to
30 minutes (30*60=1800)
reboot : False
Whether to reboot after installation
no_copy : False
If ``True`` the software package will not be SCP’d to the device
bool validate:
When ``True`` this method will perform a config validation against
the new image
bool issu:
When ``True`` allows unified in-service software upgrade
(ISSU) feature enables you to upgrade between two different Junos OS
releases with no disruption on the control plane and with minimal
disruption of traffic.
bool nssu:
When ``True`` allows nonstop software upgrade (NSSU)
enables you to upgrade the software running on a Juniper Networks
EX Series Virtual Chassis or a Juniper Networks EX Series Ethernet
Switch with redundant Routing Engines with a single command and
minimal disruption to network traffic.
CLI Examples:
.. code-block:: bash
salt 'device_name' junos.install_os 'salt://images/junos_image.tgz' reboot=True
salt 'device_name' junos.install_os 'salt://junos_16_1.tgz' dev_timeout=300 | [
"Installs",
"the",
"given",
"image",
"on",
"the",
"device",
".",
"After",
"the",
"installation",
"is",
"complete",
"\\",
"the",
"device",
"is",
"rebooted",
"if",
"reboot",
"=",
"True",
"is",
"given",
"as",
"a",
"keyworded",
"argument",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/junos.py#L1002-L1112 | train |
saltstack/salt | salt/modules/junos.py | file_copy | def file_copy(src=None, dest=None):
'''
Copies the file from the local device to the junos device
src
The source path where the file is kept.
dest
The destination path on the where the file will be copied
CLI Example:
.. code-block:: bash
salt 'device_name' junos.file_copy /home/m2/info.txt info_copy.txt
'''
conn = __proxy__['junos.conn']()
ret = {}
ret['out'] = True
if src is None:
ret['message'] = \
'Please provide the absolute path of the file to be copied.'
ret['out'] = False
return ret
if not os.path.isfile(src):
ret['message'] = 'Invalid source file path'
ret['out'] = False
return ret
if dest is None:
ret['message'] = \
'Please provide the absolute path of the destination where the file is to be copied.'
ret['out'] = False
return ret
try:
with SCP(conn, progress=True) as scp:
scp.put(src, dest)
ret['message'] = 'Successfully copied file from {0} to {1}'.format(
src, dest)
except Exception as exception:
ret['message'] = 'Could not copy file : "{0}"'.format(exception)
ret['out'] = False
return ret | python | def file_copy(src=None, dest=None):
'''
Copies the file from the local device to the junos device
src
The source path where the file is kept.
dest
The destination path on the where the file will be copied
CLI Example:
.. code-block:: bash
salt 'device_name' junos.file_copy /home/m2/info.txt info_copy.txt
'''
conn = __proxy__['junos.conn']()
ret = {}
ret['out'] = True
if src is None:
ret['message'] = \
'Please provide the absolute path of the file to be copied.'
ret['out'] = False
return ret
if not os.path.isfile(src):
ret['message'] = 'Invalid source file path'
ret['out'] = False
return ret
if dest is None:
ret['message'] = \
'Please provide the absolute path of the destination where the file is to be copied.'
ret['out'] = False
return ret
try:
with SCP(conn, progress=True) as scp:
scp.put(src, dest)
ret['message'] = 'Successfully copied file from {0} to {1}'.format(
src, dest)
except Exception as exception:
ret['message'] = 'Could not copy file : "{0}"'.format(exception)
ret['out'] = False
return ret | [
"def",
"file_copy",
"(",
"src",
"=",
"None",
",",
"dest",
"=",
"None",
")",
":",
"conn",
"=",
"__proxy__",
"[",
"'junos.conn'",
"]",
"(",
")",
"ret",
"=",
"{",
"}",
"ret",
"[",
"'out'",
"]",
"=",
"True",
"if",
"src",
"is",
"None",
":",
"ret",
"... | Copies the file from the local device to the junos device
src
The source path where the file is kept.
dest
The destination path on the where the file will be copied
CLI Example:
.. code-block:: bash
salt 'device_name' junos.file_copy /home/m2/info.txt info_copy.txt | [
"Copies",
"the",
"file",
"from",
"the",
"local",
"device",
"to",
"the",
"junos",
"device"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/junos.py#L1115-L1160 | train |
saltstack/salt | salt/modules/junos.py | lock | def lock():
'''
Attempts an exclusive lock on the candidate configuration. This
is a non-blocking call.
.. note::
When locking, it is important to remember to call
:py:func:`junos.unlock <salt.modules.junos.unlock>` once finished. If
locking during orchestration, remember to include a step in the
orchestration job to unlock.
CLI Example:
.. code-block:: bash
salt 'device_name' junos.lock
'''
conn = __proxy__['junos.conn']()
ret = {}
ret['out'] = True
try:
conn.cu.lock()
ret['message'] = "Successfully locked the configuration."
except jnpr.junos.exception.LockError as exception:
ret['message'] = 'Could not gain lock due to : "{0}"'.format(exception)
ret['out'] = False
return ret | python | def lock():
'''
Attempts an exclusive lock on the candidate configuration. This
is a non-blocking call.
.. note::
When locking, it is important to remember to call
:py:func:`junos.unlock <salt.modules.junos.unlock>` once finished. If
locking during orchestration, remember to include a step in the
orchestration job to unlock.
CLI Example:
.. code-block:: bash
salt 'device_name' junos.lock
'''
conn = __proxy__['junos.conn']()
ret = {}
ret['out'] = True
try:
conn.cu.lock()
ret['message'] = "Successfully locked the configuration."
except jnpr.junos.exception.LockError as exception:
ret['message'] = 'Could not gain lock due to : "{0}"'.format(exception)
ret['out'] = False
return ret | [
"def",
"lock",
"(",
")",
":",
"conn",
"=",
"__proxy__",
"[",
"'junos.conn'",
"]",
"(",
")",
"ret",
"=",
"{",
"}",
"ret",
"[",
"'out'",
"]",
"=",
"True",
"try",
":",
"conn",
".",
"cu",
".",
"lock",
"(",
")",
"ret",
"[",
"'message'",
"]",
"=",
... | Attempts an exclusive lock on the candidate configuration. This
is a non-blocking call.
.. note::
When locking, it is important to remember to call
:py:func:`junos.unlock <salt.modules.junos.unlock>` once finished. If
locking during orchestration, remember to include a step in the
orchestration job to unlock.
CLI Example:
.. code-block:: bash
salt 'device_name' junos.lock | [
"Attempts",
"an",
"exclusive",
"lock",
"on",
"the",
"candidate",
"configuration",
".",
"This",
"is",
"a",
"non",
"-",
"blocking",
"call",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/junos.py#L1163-L1190 | train |
saltstack/salt | salt/modules/junos.py | unlock | def unlock():
'''
Unlocks the candidate configuration.
CLI Example:
.. code-block:: bash
salt 'device_name' junos.unlock
'''
conn = __proxy__['junos.conn']()
ret = {}
ret['out'] = True
try:
conn.cu.unlock()
ret['message'] = "Successfully unlocked the configuration."
except jnpr.junos.exception.UnlockError as exception:
ret['message'] = \
'Could not unlock configuration due to : "{0}"'.format(exception)
ret['out'] = False
return ret | python | def unlock():
'''
Unlocks the candidate configuration.
CLI Example:
.. code-block:: bash
salt 'device_name' junos.unlock
'''
conn = __proxy__['junos.conn']()
ret = {}
ret['out'] = True
try:
conn.cu.unlock()
ret['message'] = "Successfully unlocked the configuration."
except jnpr.junos.exception.UnlockError as exception:
ret['message'] = \
'Could not unlock configuration due to : "{0}"'.format(exception)
ret['out'] = False
return ret | [
"def",
"unlock",
"(",
")",
":",
"conn",
"=",
"__proxy__",
"[",
"'junos.conn'",
"]",
"(",
")",
"ret",
"=",
"{",
"}",
"ret",
"[",
"'out'",
"]",
"=",
"True",
"try",
":",
"conn",
".",
"cu",
".",
"unlock",
"(",
")",
"ret",
"[",
"'message'",
"]",
"="... | Unlocks the candidate configuration.
CLI Example:
.. code-block:: bash
salt 'device_name' junos.unlock | [
"Unlocks",
"the",
"candidate",
"configuration",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/junos.py#L1193-L1214 | train |
saltstack/salt | salt/modules/junos.py | load | def load(path=None, **kwargs):
'''
Loads the configuration from the file provided onto the device.
path (required)
Path where the configuration/template file is present. If the file has
a ``.conf`` extension, the content is treated as text format. If the
file has a ``.xml`` extension, the content is treated as XML format. If
the file has a ``.set`` extension, the content is treated as Junos OS
``set`` commands.
overwrite : False
Set to ``True`` if you want this file is to completely replace the
configuration file.
replace : False
Specify whether the configuration file uses ``replace:`` statements. If
``True``, only those statements under the ``replace`` tag will be
changed.
format
Determines the format of the contents
update : False
Compare a complete loaded configuration against the candidate
configuration. For each hierarchy level or configuration object that is
different in the two configurations, the version in the loaded
configuration replaces the version in the candidate configuration. When
the configuration is later committed, only system processes that are
affected by the changed configuration elements parse the new
configuration. This action is supported from PyEZ 2.1.
template_vars
Variables to be passed into the template processing engine in addition to
those present in pillar, the minion configuration, grains, etc. You may
reference these variables in your template like so:
.. code-block:: jinja
{{ template_vars["var_name"] }}
CLI Examples:
.. code-block:: bash
salt 'device_name' junos.load 'salt://production/network/routers/config.set'
salt 'device_name' junos.load 'salt://templates/replace_config.conf' replace=True
salt 'device_name' junos.load 'salt://my_new_configuration.conf' overwrite=True
salt 'device_name' junos.load 'salt://syslog_template.conf' template_vars='{"syslog_host": "10.180.222.7"}'
'''
conn = __proxy__['junos.conn']()
ret = {}
ret['out'] = True
if path is None:
ret['message'] = \
'Please provide the salt path where the configuration is present'
ret['out'] = False
return ret
op = {}
if '__pub_arg' in kwargs:
if kwargs['__pub_arg']:
if isinstance(kwargs['__pub_arg'][-1], dict):
op.update(kwargs['__pub_arg'][-1])
else:
op.update(kwargs)
template_vars = {}
if "template_vars" in op:
template_vars = op["template_vars"]
template_cached_path = salt.utils.files.mkstemp()
__salt__['cp.get_template'](
path,
template_cached_path,
template_vars=template_vars)
if not os.path.isfile(template_cached_path):
ret['message'] = 'Invalid file path.'
ret['out'] = False
return ret
if os.path.getsize(template_cached_path) == 0:
ret['message'] = 'Template failed to render'
ret['out'] = False
return ret
op['path'] = template_cached_path
if 'format' not in op:
if path.endswith('set'):
template_format = 'set'
elif path.endswith('xml'):
template_format = 'xml'
else:
template_format = 'text'
op['format'] = template_format
if 'replace' in op and op['replace']:
op['merge'] = False
del op['replace']
elif 'overwrite' in op and op['overwrite']:
op['overwrite'] = True
elif 'overwrite' in op and not op['overwrite']:
op['merge'] = True
del op['overwrite']
try:
conn.cu.load(**op)
ret['message'] = "Successfully loaded the configuration."
except Exception as exception:
ret['message'] = 'Could not load configuration due to : "{0}"'.format(
exception)
ret['format'] = op['format']
ret['out'] = False
return ret
finally:
salt.utils.files.safe_rm(template_cached_path)
return ret | python | def load(path=None, **kwargs):
'''
Loads the configuration from the file provided onto the device.
path (required)
Path where the configuration/template file is present. If the file has
a ``.conf`` extension, the content is treated as text format. If the
file has a ``.xml`` extension, the content is treated as XML format. If
the file has a ``.set`` extension, the content is treated as Junos OS
``set`` commands.
overwrite : False
Set to ``True`` if you want this file is to completely replace the
configuration file.
replace : False
Specify whether the configuration file uses ``replace:`` statements. If
``True``, only those statements under the ``replace`` tag will be
changed.
format
Determines the format of the contents
update : False
Compare a complete loaded configuration against the candidate
configuration. For each hierarchy level or configuration object that is
different in the two configurations, the version in the loaded
configuration replaces the version in the candidate configuration. When
the configuration is later committed, only system processes that are
affected by the changed configuration elements parse the new
configuration. This action is supported from PyEZ 2.1.
template_vars
Variables to be passed into the template processing engine in addition to
those present in pillar, the minion configuration, grains, etc. You may
reference these variables in your template like so:
.. code-block:: jinja
{{ template_vars["var_name"] }}
CLI Examples:
.. code-block:: bash
salt 'device_name' junos.load 'salt://production/network/routers/config.set'
salt 'device_name' junos.load 'salt://templates/replace_config.conf' replace=True
salt 'device_name' junos.load 'salt://my_new_configuration.conf' overwrite=True
salt 'device_name' junos.load 'salt://syslog_template.conf' template_vars='{"syslog_host": "10.180.222.7"}'
'''
conn = __proxy__['junos.conn']()
ret = {}
ret['out'] = True
if path is None:
ret['message'] = \
'Please provide the salt path where the configuration is present'
ret['out'] = False
return ret
op = {}
if '__pub_arg' in kwargs:
if kwargs['__pub_arg']:
if isinstance(kwargs['__pub_arg'][-1], dict):
op.update(kwargs['__pub_arg'][-1])
else:
op.update(kwargs)
template_vars = {}
if "template_vars" in op:
template_vars = op["template_vars"]
template_cached_path = salt.utils.files.mkstemp()
__salt__['cp.get_template'](
path,
template_cached_path,
template_vars=template_vars)
if not os.path.isfile(template_cached_path):
ret['message'] = 'Invalid file path.'
ret['out'] = False
return ret
if os.path.getsize(template_cached_path) == 0:
ret['message'] = 'Template failed to render'
ret['out'] = False
return ret
op['path'] = template_cached_path
if 'format' not in op:
if path.endswith('set'):
template_format = 'set'
elif path.endswith('xml'):
template_format = 'xml'
else:
template_format = 'text'
op['format'] = template_format
if 'replace' in op and op['replace']:
op['merge'] = False
del op['replace']
elif 'overwrite' in op and op['overwrite']:
op['overwrite'] = True
elif 'overwrite' in op and not op['overwrite']:
op['merge'] = True
del op['overwrite']
try:
conn.cu.load(**op)
ret['message'] = "Successfully loaded the configuration."
except Exception as exception:
ret['message'] = 'Could not load configuration due to : "{0}"'.format(
exception)
ret['format'] = op['format']
ret['out'] = False
return ret
finally:
salt.utils.files.safe_rm(template_cached_path)
return ret | [
"def",
"load",
"(",
"path",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"conn",
"=",
"__proxy__",
"[",
"'junos.conn'",
"]",
"(",
")",
"ret",
"=",
"{",
"}",
"ret",
"[",
"'out'",
"]",
"=",
"True",
"if",
"path",
"is",
"None",
":",
"ret",
"[",
... | Loads the configuration from the file provided onto the device.
path (required)
Path where the configuration/template file is present. If the file has
a ``.conf`` extension, the content is treated as text format. If the
file has a ``.xml`` extension, the content is treated as XML format. If
the file has a ``.set`` extension, the content is treated as Junos OS
``set`` commands.
overwrite : False
Set to ``True`` if you want this file is to completely replace the
configuration file.
replace : False
Specify whether the configuration file uses ``replace:`` statements. If
``True``, only those statements under the ``replace`` tag will be
changed.
format
Determines the format of the contents
update : False
Compare a complete loaded configuration against the candidate
configuration. For each hierarchy level or configuration object that is
different in the two configurations, the version in the loaded
configuration replaces the version in the candidate configuration. When
the configuration is later committed, only system processes that are
affected by the changed configuration elements parse the new
configuration. This action is supported from PyEZ 2.1.
template_vars
Variables to be passed into the template processing engine in addition to
those present in pillar, the minion configuration, grains, etc. You may
reference these variables in your template like so:
.. code-block:: jinja
{{ template_vars["var_name"] }}
CLI Examples:
.. code-block:: bash
salt 'device_name' junos.load 'salt://production/network/routers/config.set'
salt 'device_name' junos.load 'salt://templates/replace_config.conf' replace=True
salt 'device_name' junos.load 'salt://my_new_configuration.conf' overwrite=True
salt 'device_name' junos.load 'salt://syslog_template.conf' template_vars='{"syslog_host": "10.180.222.7"}' | [
"Loads",
"the",
"configuration",
"from",
"the",
"file",
"provided",
"onto",
"the",
"device",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/junos.py#L1217-L1341 | train |
saltstack/salt | salt/modules/junos.py | commit_check | def commit_check():
'''
Perform a commit check on the configuration
CLI Example:
.. code-block:: bash
salt 'device_name' junos.commit_check
'''
conn = __proxy__['junos.conn']()
ret = {}
ret['out'] = True
try:
conn.cu.commit_check()
ret['message'] = 'Commit check succeeded.'
except Exception as exception:
ret['message'] = 'Commit check failed with {0}'.format(exception)
ret['out'] = False
return ret | python | def commit_check():
'''
Perform a commit check on the configuration
CLI Example:
.. code-block:: bash
salt 'device_name' junos.commit_check
'''
conn = __proxy__['junos.conn']()
ret = {}
ret['out'] = True
try:
conn.cu.commit_check()
ret['message'] = 'Commit check succeeded.'
except Exception as exception:
ret['message'] = 'Commit check failed with {0}'.format(exception)
ret['out'] = False
return ret | [
"def",
"commit_check",
"(",
")",
":",
"conn",
"=",
"__proxy__",
"[",
"'junos.conn'",
"]",
"(",
")",
"ret",
"=",
"{",
"}",
"ret",
"[",
"'out'",
"]",
"=",
"True",
"try",
":",
"conn",
".",
"cu",
".",
"commit_check",
"(",
")",
"ret",
"[",
"'message'",
... | Perform a commit check on the configuration
CLI Example:
.. code-block:: bash
salt 'device_name' junos.commit_check | [
"Perform",
"a",
"commit",
"check",
"on",
"the",
"configuration"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/junos.py#L1344-L1364 | train |
saltstack/salt | salt/modules/junos.py | get_table | def get_table(table, table_file, path=None, target=None, key=None, key_items=None,
filters=None, template_args=None):
'''
Retrieve data from a Junos device using Tables/Views
table (required)
Name of PyEZ Table
table_file (required)
YAML file that has the table specified in table parameter
path:
Path of location of the YAML file.
defaults to op directory in jnpr.junos.op
target:
if command need to run on FPC, can specify fpc target
key:
To overwrite key provided in YAML
key_items:
To select only given key items
filters:
To select only filter for the dictionary from columns
template_args:
key/value pair which should render Jinja template command
CLI Example:
.. code-block:: bash
salt 'device_name' junos.get_table
'''
conn = __proxy__['junos.conn']()
ret = {}
ret['out'] = True
ret['hostname'] = conn._hostname
ret['tablename'] = table
get_kvargs = {}
if target is not None:
get_kvargs['target'] = target
if key is not None:
get_kvargs['key'] = key
if key_items is not None:
get_kvargs['key_items'] = key_items
if filters is not None:
get_kvargs['filters'] = filters
if template_args is not None and isinstance(template_args, dict):
get_kvargs['args'] = template_args
pyez_tables_path = os.path.dirname(os.path.abspath(tables_dir.__file__))
try:
if path is not None:
file_loc = glob.glob(os.path.join(path, '{}'.format(table_file)))
else:
file_loc = glob.glob(os.path.join(pyez_tables_path, '{}'.format(table_file)))
if len(file_loc) == 1:
file_name = file_loc[0]
else:
ret['message'] = 'Given table file {} cannot be located'.format(table_file)
ret['out'] = False
return ret
try:
with salt.utils.files.fopen(file_name) as fp:
ret['table'] = yaml.load(fp.read(),
Loader=yamlordereddictloader.Loader)
globals().update(FactoryLoader().load(ret['table']))
except IOError as err:
ret['message'] = 'Uncaught exception during YAML Load - please ' \
'report: {0}'.format(six.text_type(err))
ret['out'] = False
return ret
try:
data = globals()[table](conn)
data.get(**get_kvargs)
except KeyError as err:
ret['message'] = 'Uncaught exception during get API call - please ' \
'report: {0}'.format(six.text_type(err))
ret['out'] = False
return ret
except ConnectClosedError:
ret['message'] = 'Got ConnectClosedError exception. Connection lost ' \
'with {}'.format(conn)
ret['out'] = False
return ret
ret['reply'] = json.loads(data.to_json())
if data.__class__.__bases__[0] == OpTable:
# Sets key value if not present in YAML. To be used by returner
if ret['table'][table].get('key') is None:
ret['table'][table]['key'] = data.ITEM_NAME_XPATH
# If key is provided from salt state file.
if key is not None:
ret['table'][table]['key'] = data.KEY
else:
if target is not None:
ret['table'][table]['target'] = data.TARGET
if key is not None:
ret['table'][table]['key'] = data.KEY
if key_items is not None:
ret['table'][table]['key_items'] = data.KEY_ITEMS
if template_args is not None:
ret['table'][table]['args'] = data.CMD_ARGS
ret['table'][table]['command'] = data.GET_CMD
except Exception as err:
ret['message'] = 'Uncaught exception - please report: {0}'.format(
str(err))
traceback.print_exc()
ret['out'] = False
return ret
return ret | python | def get_table(table, table_file, path=None, target=None, key=None, key_items=None,
filters=None, template_args=None):
'''
Retrieve data from a Junos device using Tables/Views
table (required)
Name of PyEZ Table
table_file (required)
YAML file that has the table specified in table parameter
path:
Path of location of the YAML file.
defaults to op directory in jnpr.junos.op
target:
if command need to run on FPC, can specify fpc target
key:
To overwrite key provided in YAML
key_items:
To select only given key items
filters:
To select only filter for the dictionary from columns
template_args:
key/value pair which should render Jinja template command
CLI Example:
.. code-block:: bash
salt 'device_name' junos.get_table
'''
conn = __proxy__['junos.conn']()
ret = {}
ret['out'] = True
ret['hostname'] = conn._hostname
ret['tablename'] = table
get_kvargs = {}
if target is not None:
get_kvargs['target'] = target
if key is not None:
get_kvargs['key'] = key
if key_items is not None:
get_kvargs['key_items'] = key_items
if filters is not None:
get_kvargs['filters'] = filters
if template_args is not None and isinstance(template_args, dict):
get_kvargs['args'] = template_args
pyez_tables_path = os.path.dirname(os.path.abspath(tables_dir.__file__))
try:
if path is not None:
file_loc = glob.glob(os.path.join(path, '{}'.format(table_file)))
else:
file_loc = glob.glob(os.path.join(pyez_tables_path, '{}'.format(table_file)))
if len(file_loc) == 1:
file_name = file_loc[0]
else:
ret['message'] = 'Given table file {} cannot be located'.format(table_file)
ret['out'] = False
return ret
try:
with salt.utils.files.fopen(file_name) as fp:
ret['table'] = yaml.load(fp.read(),
Loader=yamlordereddictloader.Loader)
globals().update(FactoryLoader().load(ret['table']))
except IOError as err:
ret['message'] = 'Uncaught exception during YAML Load - please ' \
'report: {0}'.format(six.text_type(err))
ret['out'] = False
return ret
try:
data = globals()[table](conn)
data.get(**get_kvargs)
except KeyError as err:
ret['message'] = 'Uncaught exception during get API call - please ' \
'report: {0}'.format(six.text_type(err))
ret['out'] = False
return ret
except ConnectClosedError:
ret['message'] = 'Got ConnectClosedError exception. Connection lost ' \
'with {}'.format(conn)
ret['out'] = False
return ret
ret['reply'] = json.loads(data.to_json())
if data.__class__.__bases__[0] == OpTable:
# Sets key value if not present in YAML. To be used by returner
if ret['table'][table].get('key') is None:
ret['table'][table]['key'] = data.ITEM_NAME_XPATH
# If key is provided from salt state file.
if key is not None:
ret['table'][table]['key'] = data.KEY
else:
if target is not None:
ret['table'][table]['target'] = data.TARGET
if key is not None:
ret['table'][table]['key'] = data.KEY
if key_items is not None:
ret['table'][table]['key_items'] = data.KEY_ITEMS
if template_args is not None:
ret['table'][table]['args'] = data.CMD_ARGS
ret['table'][table]['command'] = data.GET_CMD
except Exception as err:
ret['message'] = 'Uncaught exception - please report: {0}'.format(
str(err))
traceback.print_exc()
ret['out'] = False
return ret
return ret | [
"def",
"get_table",
"(",
"table",
",",
"table_file",
",",
"path",
"=",
"None",
",",
"target",
"=",
"None",
",",
"key",
"=",
"None",
",",
"key_items",
"=",
"None",
",",
"filters",
"=",
"None",
",",
"template_args",
"=",
"None",
")",
":",
"conn",
"=",
... | Retrieve data from a Junos device using Tables/Views
table (required)
Name of PyEZ Table
table_file (required)
YAML file that has the table specified in table parameter
path:
Path of location of the YAML file.
defaults to op directory in jnpr.junos.op
target:
if command need to run on FPC, can specify fpc target
key:
To overwrite key provided in YAML
key_items:
To select only given key items
filters:
To select only filter for the dictionary from columns
template_args:
key/value pair which should render Jinja template command
CLI Example:
.. code-block:: bash
salt 'device_name' junos.get_table | [
"Retrieve",
"data",
"from",
"a",
"Junos",
"device",
"using",
"Tables",
"/",
"Views"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/junos.py#L1367-L1478 | train |
saltstack/salt | salt/modules/guestfs.py | mount | def mount(location, access='rw', root=None):
'''
Mount an image
CLI Example:
.. code-block:: bash
salt '*' guest.mount /srv/images/fedora.qcow
'''
if root is None:
root = os.path.join(
tempfile.gettempdir(),
'guest',
location.lstrip(os.sep).replace('/', '.')
)
log.debug('Using root %s', root)
if not os.path.isdir(root):
try:
os.makedirs(root)
except OSError:
# Somehow the path already exists
pass
while True:
if os.listdir(root):
# Stuff is in there, don't use it
hash_type = getattr(hashlib, __opts__.get('hash_type', 'md5'))
rand = hash_type(os.urandom(32)).hexdigest()
root = os.path.join(
tempfile.gettempdir(),
'guest',
location.lstrip(os.sep).replace('/', '.') + rand
)
log.debug('Establishing new root as %s', root)
else:
break
cmd = 'guestmount -i -a {0} --{1} {2}'.format(location, access, root)
__salt__['cmd.run'](cmd, python_shell=False)
return root | python | def mount(location, access='rw', root=None):
'''
Mount an image
CLI Example:
.. code-block:: bash
salt '*' guest.mount /srv/images/fedora.qcow
'''
if root is None:
root = os.path.join(
tempfile.gettempdir(),
'guest',
location.lstrip(os.sep).replace('/', '.')
)
log.debug('Using root %s', root)
if not os.path.isdir(root):
try:
os.makedirs(root)
except OSError:
# Somehow the path already exists
pass
while True:
if os.listdir(root):
# Stuff is in there, don't use it
hash_type = getattr(hashlib, __opts__.get('hash_type', 'md5'))
rand = hash_type(os.urandom(32)).hexdigest()
root = os.path.join(
tempfile.gettempdir(),
'guest',
location.lstrip(os.sep).replace('/', '.') + rand
)
log.debug('Establishing new root as %s', root)
else:
break
cmd = 'guestmount -i -a {0} --{1} {2}'.format(location, access, root)
__salt__['cmd.run'](cmd, python_shell=False)
return root | [
"def",
"mount",
"(",
"location",
",",
"access",
"=",
"'rw'",
",",
"root",
"=",
"None",
")",
":",
"if",
"root",
"is",
"None",
":",
"root",
"=",
"os",
".",
"path",
".",
"join",
"(",
"tempfile",
".",
"gettempdir",
"(",
")",
",",
"'guest'",
",",
"loc... | Mount an image
CLI Example:
.. code-block:: bash
salt '*' guest.mount /srv/images/fedora.qcow | [
"Mount",
"an",
"image"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/guestfs.py#L30-L68 | train |
saltstack/salt | salt/states/drac.py | present | def present(name, password, permission):
'''
Ensure the user exists on the Dell DRAC
name:
The users username
password
The password used to authenticate
permission
The permissions that should be assigned to a user
'''
ret = {'name': name,
'result': True,
'changes': {},
'comment': ''}
users = __salt__['drac.list_users']()
if __opts__['test']:
if name in users:
ret['comment'] = '`{0}` already exists'.format(name)
else:
ret['comment'] = '`{0}` will be created'.format(name)
ret['changes'] = {name: 'will be created'}
return ret
if name in users:
ret['comment'] = '`{0}` already exists'.format(name)
else:
if __salt__['drac.create_user'](name, password, permission, users):
ret['comment'] = '`{0}` user created'.format(name)
ret['changes'] = {name: 'new user created'}
else:
ret['comment'] = 'Unable to create user'
ret['result'] = False
return ret | python | def present(name, password, permission):
'''
Ensure the user exists on the Dell DRAC
name:
The users username
password
The password used to authenticate
permission
The permissions that should be assigned to a user
'''
ret = {'name': name,
'result': True,
'changes': {},
'comment': ''}
users = __salt__['drac.list_users']()
if __opts__['test']:
if name in users:
ret['comment'] = '`{0}` already exists'.format(name)
else:
ret['comment'] = '`{0}` will be created'.format(name)
ret['changes'] = {name: 'will be created'}
return ret
if name in users:
ret['comment'] = '`{0}` already exists'.format(name)
else:
if __salt__['drac.create_user'](name, password, permission, users):
ret['comment'] = '`{0}` user created'.format(name)
ret['changes'] = {name: 'new user created'}
else:
ret['comment'] = 'Unable to create user'
ret['result'] = False
return ret | [
"def",
"present",
"(",
"name",
",",
"password",
",",
"permission",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"True",
",",
"'changes'",
":",
"{",
"}",
",",
"'comment'",
":",
"''",
"}",
"users",
"=",
"__salt__",
"[",
"'d... | Ensure the user exists on the Dell DRAC
name:
The users username
password
The password used to authenticate
permission
The permissions that should be assigned to a user | [
"Ensure",
"the",
"user",
"exists",
"on",
"the",
"Dell",
"DRAC"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/drac.py#L55-L94 | train |
saltstack/salt | salt/states/drac.py | network | def network(ip, netmask, gateway):
'''
Ensure the DRAC network settings are consistent
'''
ret = {'name': ip,
'result': True,
'changes': {},
'comment': ''}
current_network = __salt__['drac.network_info']()
new_network = {}
if ip != current_network['IPv4 settings']['IP Address']:
ret['changes'].update({'IP Address':
{'Old': current_network['IPv4 settings']['IP Address'],
'New': ip}})
if netmask != current_network['IPv4 settings']['Subnet Mask']:
ret['changes'].update({'Netmask':
{'Old': current_network['IPv4 settings']['Subnet Mask'],
'New': netmask}})
if gateway != current_network['IPv4 settings']['Gateway']:
ret['changes'].update({'Gateway':
{'Old': current_network['IPv4 settings']['Gateway'],
'New': gateway}})
if __opts__['test']:
ret['result'] = None
return ret
if __salt__['drac.set_network'](ip, netmask, gateway):
if not ret['changes']:
ret['comment'] = 'Network is in the desired state'
return ret
ret['result'] = False
ret['comment'] = 'unable to configure network'
return ret | python | def network(ip, netmask, gateway):
'''
Ensure the DRAC network settings are consistent
'''
ret = {'name': ip,
'result': True,
'changes': {},
'comment': ''}
current_network = __salt__['drac.network_info']()
new_network = {}
if ip != current_network['IPv4 settings']['IP Address']:
ret['changes'].update({'IP Address':
{'Old': current_network['IPv4 settings']['IP Address'],
'New': ip}})
if netmask != current_network['IPv4 settings']['Subnet Mask']:
ret['changes'].update({'Netmask':
{'Old': current_network['IPv4 settings']['Subnet Mask'],
'New': netmask}})
if gateway != current_network['IPv4 settings']['Gateway']:
ret['changes'].update({'Gateway':
{'Old': current_network['IPv4 settings']['Gateway'],
'New': gateway}})
if __opts__['test']:
ret['result'] = None
return ret
if __salt__['drac.set_network'](ip, netmask, gateway):
if not ret['changes']:
ret['comment'] = 'Network is in the desired state'
return ret
ret['result'] = False
ret['comment'] = 'unable to configure network'
return ret | [
"def",
"network",
"(",
"ip",
",",
"netmask",
",",
"gateway",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"ip",
",",
"'result'",
":",
"True",
",",
"'changes'",
":",
"{",
"}",
",",
"'comment'",
":",
"''",
"}",
"current_network",
"=",
"__salt__",
"[",
"... | Ensure the DRAC network settings are consistent | [
"Ensure",
"the",
"DRAC",
"network",
"settings",
"are",
"consistent"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/drac.py#L133-L173 | train |
saltstack/salt | salt/transport/client.py | AsyncPushChannel.factory | def factory(opts, **kwargs):
'''
If we have additional IPC transports other than UxD and TCP, add them here
'''
# FIXME for now, just UXD
# Obviously, this makes the factory approach pointless, but we'll extend later
import salt.transport.ipc
return salt.transport.ipc.IPCMessageClient(opts, **kwargs) | python | def factory(opts, **kwargs):
'''
If we have additional IPC transports other than UxD and TCP, add them here
'''
# FIXME for now, just UXD
# Obviously, this makes the factory approach pointless, but we'll extend later
import salt.transport.ipc
return salt.transport.ipc.IPCMessageClient(opts, **kwargs) | [
"def",
"factory",
"(",
"opts",
",",
"*",
"*",
"kwargs",
")",
":",
"# FIXME for now, just UXD",
"# Obviously, this makes the factory approach pointless, but we'll extend later",
"import",
"salt",
".",
"transport",
".",
"ipc",
"return",
"salt",
".",
"transport",
".",
"ipc... | If we have additional IPC transports other than UxD and TCP, add them here | [
"If",
"we",
"have",
"additional",
"IPC",
"transports",
"other",
"than",
"UxD",
"and",
"TCP",
"add",
"them",
"here"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/transport/client.py#L193-L200 | train |
saltstack/salt | salt/transport/client.py | AsyncPullChannel.factory | def factory(opts, **kwargs):
'''
If we have additional IPC transports other than UXD and TCP, add them here
'''
import salt.transport.ipc
return salt.transport.ipc.IPCMessageServer(opts, **kwargs) | python | def factory(opts, **kwargs):
'''
If we have additional IPC transports other than UXD and TCP, add them here
'''
import salt.transport.ipc
return salt.transport.ipc.IPCMessageServer(opts, **kwargs) | [
"def",
"factory",
"(",
"opts",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"salt",
".",
"transport",
".",
"ipc",
"return",
"salt",
".",
"transport",
".",
"ipc",
".",
"IPCMessageServer",
"(",
"opts",
",",
"*",
"*",
"kwargs",
")"
] | If we have additional IPC transports other than UXD and TCP, add them here | [
"If",
"we",
"have",
"additional",
"IPC",
"transports",
"other",
"than",
"UXD",
"and",
"TCP",
"add",
"them",
"here"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/transport/client.py#L208-L213 | train |
saltstack/salt | salt/runners/reactor.py | list_ | def list_(saltenv='base', test=None):
'''
List currently configured reactors
CLI Example:
.. code-block:: bash
salt-run reactor.list
'''
sevent = salt.utils.event.get_event(
'master',
__opts__['sock_dir'],
__opts__['transport'],
opts=__opts__,
listen=True)
master_key = salt.utils.master.get_master_key('root', __opts__)
__jid_event__.fire_event({'key': master_key}, 'salt/reactors/manage/list')
results = sevent.get_event(wait=30, tag='salt/reactors/manage/list-results')
reactors = results['reactors']
return reactors | python | def list_(saltenv='base', test=None):
'''
List currently configured reactors
CLI Example:
.. code-block:: bash
salt-run reactor.list
'''
sevent = salt.utils.event.get_event(
'master',
__opts__['sock_dir'],
__opts__['transport'],
opts=__opts__,
listen=True)
master_key = salt.utils.master.get_master_key('root', __opts__)
__jid_event__.fire_event({'key': master_key}, 'salt/reactors/manage/list')
results = sevent.get_event(wait=30, tag='salt/reactors/manage/list-results')
reactors = results['reactors']
return reactors | [
"def",
"list_",
"(",
"saltenv",
"=",
"'base'",
",",
"test",
"=",
"None",
")",
":",
"sevent",
"=",
"salt",
".",
"utils",
".",
"event",
".",
"get_event",
"(",
"'master'",
",",
"__opts__",
"[",
"'sock_dir'",
"]",
",",
"__opts__",
"[",
"'transport'",
"]",
... | List currently configured reactors
CLI Example:
.. code-block:: bash
salt-run reactor.list | [
"List",
"currently",
"configured",
"reactors"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/reactor.py#L36-L59 | train |
saltstack/salt | salt/runners/reactor.py | add | def add(event, reactors, saltenv='base', test=None):
'''
Add a new reactor
CLI Example:
.. code-block:: bash
salt-run reactor.add 'salt/cloud/*/destroyed' reactors='/srv/reactor/destroy/*.sls'
'''
if isinstance(reactors, string_types):
reactors = [reactors]
sevent = salt.utils.event.get_event(
'master',
__opts__['sock_dir'],
__opts__['transport'],
opts=__opts__,
listen=True)
master_key = salt.utils.master.get_master_key('root', __opts__)
__jid_event__.fire_event({'event': event,
'reactors': reactors,
'key': master_key},
'salt/reactors/manage/add')
res = sevent.get_event(wait=30, tag='salt/reactors/manage/add-complete')
return res['result'] | python | def add(event, reactors, saltenv='base', test=None):
'''
Add a new reactor
CLI Example:
.. code-block:: bash
salt-run reactor.add 'salt/cloud/*/destroyed' reactors='/srv/reactor/destroy/*.sls'
'''
if isinstance(reactors, string_types):
reactors = [reactors]
sevent = salt.utils.event.get_event(
'master',
__opts__['sock_dir'],
__opts__['transport'],
opts=__opts__,
listen=True)
master_key = salt.utils.master.get_master_key('root', __opts__)
__jid_event__.fire_event({'event': event,
'reactors': reactors,
'key': master_key},
'salt/reactors/manage/add')
res = sevent.get_event(wait=30, tag='salt/reactors/manage/add-complete')
return res['result'] | [
"def",
"add",
"(",
"event",
",",
"reactors",
",",
"saltenv",
"=",
"'base'",
",",
"test",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"reactors",
",",
"string_types",
")",
":",
"reactors",
"=",
"[",
"reactors",
"]",
"sevent",
"=",
"salt",
".",
"ut... | Add a new reactor
CLI Example:
.. code-block:: bash
salt-run reactor.add 'salt/cloud/*/destroyed' reactors='/srv/reactor/destroy/*.sls' | [
"Add",
"a",
"new",
"reactor"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/reactor.py#L62-L90 | train |
saltstack/salt | salt/runners/reactor.py | delete | def delete(event, saltenv='base', test=None):
'''
Delete a reactor
CLI Example:
.. code-block:: bash
salt-run reactor.delete 'salt/cloud/*/destroyed'
'''
sevent = salt.utils.event.get_event(
'master',
__opts__['sock_dir'],
__opts__['transport'],
opts=__opts__,
listen=True)
master_key = salt.utils.master.get_master_key('root', __opts__)
__jid_event__.fire_event({'event': event, 'key': master_key}, 'salt/reactors/manage/delete')
res = sevent.get_event(wait=30, tag='salt/reactors/manage/delete-complete')
return res['result'] | python | def delete(event, saltenv='base', test=None):
'''
Delete a reactor
CLI Example:
.. code-block:: bash
salt-run reactor.delete 'salt/cloud/*/destroyed'
'''
sevent = salt.utils.event.get_event(
'master',
__opts__['sock_dir'],
__opts__['transport'],
opts=__opts__,
listen=True)
master_key = salt.utils.master.get_master_key('root', __opts__)
__jid_event__.fire_event({'event': event, 'key': master_key}, 'salt/reactors/manage/delete')
res = sevent.get_event(wait=30, tag='salt/reactors/manage/delete-complete')
return res['result'] | [
"def",
"delete",
"(",
"event",
",",
"saltenv",
"=",
"'base'",
",",
"test",
"=",
"None",
")",
":",
"sevent",
"=",
"salt",
".",
"utils",
".",
"event",
".",
"get_event",
"(",
"'master'",
",",
"__opts__",
"[",
"'sock_dir'",
"]",
",",
"__opts__",
"[",
"'t... | Delete a reactor
CLI Example:
.. code-block:: bash
salt-run reactor.delete 'salt/cloud/*/destroyed' | [
"Delete",
"a",
"reactor"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/reactor.py#L93-L115 | train |
saltstack/salt | salt/utils/zeromq.py | ip_bracket | def ip_bracket(addr):
'''
Convert IP address representation to ZMQ (URL) format. ZMQ expects
brackets around IPv6 literals, since they are used in URLs.
'''
addr = ipaddress.ip_address(addr)
return ('[{}]' if addr.version == 6 else '{}').format(addr) | python | def ip_bracket(addr):
'''
Convert IP address representation to ZMQ (URL) format. ZMQ expects
brackets around IPv6 literals, since they are used in URLs.
'''
addr = ipaddress.ip_address(addr)
return ('[{}]' if addr.version == 6 else '{}').format(addr) | [
"def",
"ip_bracket",
"(",
"addr",
")",
":",
"addr",
"=",
"ipaddress",
".",
"ip_address",
"(",
"addr",
")",
"return",
"(",
"'[{}]'",
"if",
"addr",
".",
"version",
"==",
"6",
"else",
"'{}'",
")",
".",
"format",
"(",
"addr",
")"
] | Convert IP address representation to ZMQ (URL) format. ZMQ expects
brackets around IPv6 literals, since they are used in URLs. | [
"Convert",
"IP",
"address",
"representation",
"to",
"ZMQ",
"(",
"URL",
")",
"format",
".",
"ZMQ",
"expects",
"brackets",
"around",
"IPv6",
"literals",
"since",
"they",
"are",
"used",
"in",
"URLs",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/zeromq.py#L81-L87 | train |
saltstack/salt | salt/output/virt_query.py | output | def output(data, **kwargs): # pylint: disable=unused-argument
'''
Display output for the salt-run virt.query function
'''
out = ''
for id_ in data['data']:
out += '{0}\n'.format(id_)
for vm_ in data['data'][id_]['vm_info']:
out += ' {0}\n'.format(vm_)
vm_data = data[id_]['vm_info'][vm_]
if 'cpu' in vm_data:
out += ' CPU: {0}\n'.format(vm_data['cpu'])
if 'mem' in vm_data:
out += ' Memory: {0}\n'.format(vm_data['mem'])
if 'state' in vm_data:
out += ' State: {0}\n'.format(vm_data['state'])
if 'graphics' in vm_data:
if vm_data['graphics'].get('type', '') == 'vnc':
out += ' Graphics: vnc - {0}:{1}\n'.format(
id_,
vm_data['graphics']['port'])
if 'disks' in vm_data:
for disk, d_data in six.iteritems(vm_data['disks']):
out += ' Disk - {0}:\n'.format(disk)
out += ' Size: {0}\n'.format(d_data['disk size'])
out += ' File: {0}\n'.format(d_data['file'])
out += ' File Format: {0}\n'.format(d_data['file format'])
if 'nics' in vm_data:
for mac in vm_data['nics']:
out += ' Nic - {0}:\n'.format(mac)
out += ' Source: {0}\n'.format(
vm_data['nics'][mac]['source'][next(six.iterkeys(vm_data['nics'][mac]['source']))])
out += ' Type: {0}\n'.format(vm_data['nics'][mac]['type'])
return out | python | def output(data, **kwargs): # pylint: disable=unused-argument
'''
Display output for the salt-run virt.query function
'''
out = ''
for id_ in data['data']:
out += '{0}\n'.format(id_)
for vm_ in data['data'][id_]['vm_info']:
out += ' {0}\n'.format(vm_)
vm_data = data[id_]['vm_info'][vm_]
if 'cpu' in vm_data:
out += ' CPU: {0}\n'.format(vm_data['cpu'])
if 'mem' in vm_data:
out += ' Memory: {0}\n'.format(vm_data['mem'])
if 'state' in vm_data:
out += ' State: {0}\n'.format(vm_data['state'])
if 'graphics' in vm_data:
if vm_data['graphics'].get('type', '') == 'vnc':
out += ' Graphics: vnc - {0}:{1}\n'.format(
id_,
vm_data['graphics']['port'])
if 'disks' in vm_data:
for disk, d_data in six.iteritems(vm_data['disks']):
out += ' Disk - {0}:\n'.format(disk)
out += ' Size: {0}\n'.format(d_data['disk size'])
out += ' File: {0}\n'.format(d_data['file'])
out += ' File Format: {0}\n'.format(d_data['file format'])
if 'nics' in vm_data:
for mac in vm_data['nics']:
out += ' Nic - {0}:\n'.format(mac)
out += ' Source: {0}\n'.format(
vm_data['nics'][mac]['source'][next(six.iterkeys(vm_data['nics'][mac]['source']))])
out += ' Type: {0}\n'.format(vm_data['nics'][mac]['type'])
return out | [
"def",
"output",
"(",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=unused-argument",
"out",
"=",
"''",
"for",
"id_",
"in",
"data",
"[",
"'data'",
"]",
":",
"out",
"+=",
"'{0}\\n'",
".",
"format",
"(",
"id_",
")",
"for",
"vm_",
"in",
... | Display output for the salt-run virt.query function | [
"Display",
"output",
"for",
"the",
"salt",
"-",
"run",
"virt",
".",
"query",
"function"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/output/virt_query.py#L17-L50 | train |
saltstack/salt | salt/modules/win_ip.py | _interface_configs | def _interface_configs():
'''
Return all interface configs
'''
cmd = ['netsh', 'interface', 'ip', 'show', 'config']
lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
ret = {}
current_iface = None
current_ip_list = None
for line in lines:
line = line.strip()
if not line:
current_iface = None
current_ip_list = None
continue
if 'Configuration for interface' in line:
_, iface = line.rstrip('"').split('"', 1) # get iface name
current_iface = {}
ret[iface] = current_iface
continue
if ':' not in line:
if current_ip_list:
current_ip_list.append(line)
else:
log.warning('Cannot parse "%s"', line)
continue
key, val = line.split(':', 1)
key = key.strip()
val = val.strip()
lkey = key.lower()
if ('dns servers' in lkey) or ('wins servers' in lkey):
current_ip_list = []
current_iface[key] = current_ip_list
current_ip_list.append(val)
elif 'ip address' in lkey:
current_iface.setdefault('ip_addrs', []).append({key: val})
elif 'subnet prefix' in lkey:
subnet, _, netmask = val.split(' ', 2)
last_ip = current_iface['ip_addrs'][-1]
last_ip['Subnet'] = subnet.strip()
last_ip['Netmask'] = netmask.lstrip().rstrip(')')
else:
current_iface[key] = val
return ret | python | def _interface_configs():
'''
Return all interface configs
'''
cmd = ['netsh', 'interface', 'ip', 'show', 'config']
lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
ret = {}
current_iface = None
current_ip_list = None
for line in lines:
line = line.strip()
if not line:
current_iface = None
current_ip_list = None
continue
if 'Configuration for interface' in line:
_, iface = line.rstrip('"').split('"', 1) # get iface name
current_iface = {}
ret[iface] = current_iface
continue
if ':' not in line:
if current_ip_list:
current_ip_list.append(line)
else:
log.warning('Cannot parse "%s"', line)
continue
key, val = line.split(':', 1)
key = key.strip()
val = val.strip()
lkey = key.lower()
if ('dns servers' in lkey) or ('wins servers' in lkey):
current_ip_list = []
current_iface[key] = current_ip_list
current_ip_list.append(val)
elif 'ip address' in lkey:
current_iface.setdefault('ip_addrs', []).append({key: val})
elif 'subnet prefix' in lkey:
subnet, _, netmask = val.split(' ', 2)
last_ip = current_iface['ip_addrs'][-1]
last_ip['Subnet'] = subnet.strip()
last_ip['Netmask'] = netmask.lstrip().rstrip(')')
else:
current_iface[key] = val
return ret | [
"def",
"_interface_configs",
"(",
")",
":",
"cmd",
"=",
"[",
"'netsh'",
",",
"'interface'",
",",
"'ip'",
",",
"'show'",
",",
"'config'",
"]",
"lines",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"cmd",
",",
"python_shell",
"=",
"False",
")",
".",
"spl... | Return all interface configs | [
"Return",
"all",
"interface",
"configs"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_ip.py#L37-L90 | train |
saltstack/salt | salt/modules/win_ip.py | is_enabled | def is_enabled(iface):
'''
Returns ``True`` if interface is enabled, otherwise ``False``
CLI Example:
.. code-block:: bash
salt -G 'os_family:Windows' ip.is_enabled 'Local Area Connection #2'
'''
cmd = ['netsh', 'interface', 'show', 'interface', 'name={0}'.format(iface)]
iface_found = False
for line in __salt__['cmd.run'](cmd, python_shell=False).splitlines():
if 'Connect state:' in line:
iface_found = True
return line.split()[-1] == 'Connected'
if not iface_found:
raise CommandExecutionError(
'Interface \'{0}\' not found'.format(iface)
)
return False | python | def is_enabled(iface):
'''
Returns ``True`` if interface is enabled, otherwise ``False``
CLI Example:
.. code-block:: bash
salt -G 'os_family:Windows' ip.is_enabled 'Local Area Connection #2'
'''
cmd = ['netsh', 'interface', 'show', 'interface', 'name={0}'.format(iface)]
iface_found = False
for line in __salt__['cmd.run'](cmd, python_shell=False).splitlines():
if 'Connect state:' in line:
iface_found = True
return line.split()[-1] == 'Connected'
if not iface_found:
raise CommandExecutionError(
'Interface \'{0}\' not found'.format(iface)
)
return False | [
"def",
"is_enabled",
"(",
"iface",
")",
":",
"cmd",
"=",
"[",
"'netsh'",
",",
"'interface'",
",",
"'show'",
",",
"'interface'",
",",
"'name={0}'",
".",
"format",
"(",
"iface",
")",
"]",
"iface_found",
"=",
"False",
"for",
"line",
"in",
"__salt__",
"[",
... | Returns ``True`` if interface is enabled, otherwise ``False``
CLI Example:
.. code-block:: bash
salt -G 'os_family:Windows' ip.is_enabled 'Local Area Connection #2' | [
"Returns",
"True",
"if",
"interface",
"is",
"enabled",
"otherwise",
"False"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_ip.py#L133-L153 | train |
saltstack/salt | salt/modules/win_ip.py | enable | def enable(iface):
'''
Enable an interface
CLI Example:
.. code-block:: bash
salt -G 'os_family:Windows' ip.enable 'Local Area Connection #2'
'''
if is_enabled(iface):
return True
cmd = ['netsh', 'interface', 'set', 'interface',
'name={0}'.format(iface),
'admin=ENABLED']
__salt__['cmd.run'](cmd, python_shell=False)
return is_enabled(iface) | python | def enable(iface):
'''
Enable an interface
CLI Example:
.. code-block:: bash
salt -G 'os_family:Windows' ip.enable 'Local Area Connection #2'
'''
if is_enabled(iface):
return True
cmd = ['netsh', 'interface', 'set', 'interface',
'name={0}'.format(iface),
'admin=ENABLED']
__salt__['cmd.run'](cmd, python_shell=False)
return is_enabled(iface) | [
"def",
"enable",
"(",
"iface",
")",
":",
"if",
"is_enabled",
"(",
"iface",
")",
":",
"return",
"True",
"cmd",
"=",
"[",
"'netsh'",
",",
"'interface'",
",",
"'set'",
",",
"'interface'",
",",
"'name={0}'",
".",
"format",
"(",
"iface",
")",
",",
"'admin=E... | Enable an interface
CLI Example:
.. code-block:: bash
salt -G 'os_family:Windows' ip.enable 'Local Area Connection #2' | [
"Enable",
"an",
"interface"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_ip.py#L169-L185 | train |
saltstack/salt | salt/modules/win_ip.py | disable | def disable(iface):
'''
Disable an interface
CLI Example:
.. code-block:: bash
salt -G 'os_family:Windows' ip.disable 'Local Area Connection #2'
'''
if is_disabled(iface):
return True
cmd = ['netsh', 'interface', 'set', 'interface',
'name={0}'.format(iface),
'admin=DISABLED']
__salt__['cmd.run'](cmd, python_shell=False)
return is_disabled(iface) | python | def disable(iface):
'''
Disable an interface
CLI Example:
.. code-block:: bash
salt -G 'os_family:Windows' ip.disable 'Local Area Connection #2'
'''
if is_disabled(iface):
return True
cmd = ['netsh', 'interface', 'set', 'interface',
'name={0}'.format(iface),
'admin=DISABLED']
__salt__['cmd.run'](cmd, python_shell=False)
return is_disabled(iface) | [
"def",
"disable",
"(",
"iface",
")",
":",
"if",
"is_disabled",
"(",
"iface",
")",
":",
"return",
"True",
"cmd",
"=",
"[",
"'netsh'",
",",
"'interface'",
",",
"'set'",
",",
"'interface'",
",",
"'name={0}'",
".",
"format",
"(",
"iface",
")",
",",
"'admin... | Disable an interface
CLI Example:
.. code-block:: bash
salt -G 'os_family:Windows' ip.disable 'Local Area Connection #2' | [
"Disable",
"an",
"interface"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_ip.py#L188-L204 | train |
saltstack/salt | salt/modules/win_ip.py | get_subnet_length | def get_subnet_length(mask):
'''
Convenience function to convert the netmask to the CIDR subnet length
CLI Example:
.. code-block:: bash
salt -G 'os_family:Windows' ip.get_subnet_length 255.255.255.0
'''
if not salt.utils.validate.net.netmask(mask):
raise SaltInvocationError(
'\'{0}\' is not a valid netmask'.format(mask)
)
return salt.utils.network.get_net_size(mask) | python | def get_subnet_length(mask):
'''
Convenience function to convert the netmask to the CIDR subnet length
CLI Example:
.. code-block:: bash
salt -G 'os_family:Windows' ip.get_subnet_length 255.255.255.0
'''
if not salt.utils.validate.net.netmask(mask):
raise SaltInvocationError(
'\'{0}\' is not a valid netmask'.format(mask)
)
return salt.utils.network.get_net_size(mask) | [
"def",
"get_subnet_length",
"(",
"mask",
")",
":",
"if",
"not",
"salt",
".",
"utils",
".",
"validate",
".",
"net",
".",
"netmask",
"(",
"mask",
")",
":",
"raise",
"SaltInvocationError",
"(",
"'\\'{0}\\' is not a valid netmask'",
".",
"format",
"(",
"mask",
"... | Convenience function to convert the netmask to the CIDR subnet length
CLI Example:
.. code-block:: bash
salt -G 'os_family:Windows' ip.get_subnet_length 255.255.255.0 | [
"Convenience",
"function",
"to",
"convert",
"the",
"netmask",
"to",
"the",
"CIDR",
"subnet",
"length"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_ip.py#L207-L221 | train |
saltstack/salt | salt/modules/win_ip.py | set_static_ip | def set_static_ip(iface, addr, gateway=None, append=False):
'''
Set static IP configuration on a Windows NIC
iface
The name of the interface to manage
addr
IP address with subnet length (ex. ``10.1.2.3/24``). The
:mod:`ip.get_subnet_length <salt.modules.win_ip.get_subnet_length>`
function can be used to calculate the subnet length from a netmask.
gateway : None
If specified, the default gateway will be set to this value.
append : False
If ``True``, this IP address will be added to the interface. Default is
``False``, which overrides any existing configuration for the interface
and sets ``addr`` as the only address on the interface.
CLI Example:
.. code-block:: bash
salt -G 'os_family:Windows' ip.set_static_ip 'Local Area Connection' 10.1.2.3/24 gateway=10.1.2.1
salt -G 'os_family:Windows' ip.set_static_ip 'Local Area Connection' 10.1.2.4/24 append=True
'''
def _find_addr(iface, addr, timeout=1):
ip, cidr = addr.rsplit('/', 1)
netmask = salt.utils.network.cidr_to_ipv4_netmask(cidr)
for idx in range(timeout):
for addrinfo in get_interface(iface).get('ip_addrs', []):
if addrinfo['IP Address'] == ip \
and addrinfo['Netmask'] == netmask:
return addrinfo
time.sleep(1)
return {}
if not salt.utils.validate.net.ipv4_addr(addr):
raise SaltInvocationError('Invalid address \'{0}\''.format(addr))
if gateway and not salt.utils.validate.net.ipv4_addr(addr):
raise SaltInvocationError(
'Invalid default gateway \'{0}\''.format(gateway)
)
if '/' not in addr:
addr += '/32'
if append and _find_addr(iface, addr):
raise CommandExecutionError(
'Address \'{0}\' already exists on interface '
'\'{1}\''.format(addr, iface)
)
cmd = ['netsh', 'interface', 'ip']
if append:
cmd.append('add')
else:
cmd.append('set')
cmd.extend(['address', 'name={0}'.format(iface)])
if not append:
cmd.append('source=static')
cmd.append('address={0}'.format(addr))
if gateway:
cmd.append('gateway={0}'.format(gateway))
result = __salt__['cmd.run_all'](cmd, python_shell=False)
if result['retcode'] != 0:
raise CommandExecutionError(
'Unable to set IP address: {0}'.format(result['stderr'])
)
new_addr = _find_addr(iface, addr, timeout=10)
if not new_addr:
return {}
ret = {'Address Info': new_addr}
if gateway:
ret['Default Gateway'] = gateway
return ret | python | def set_static_ip(iface, addr, gateway=None, append=False):
'''
Set static IP configuration on a Windows NIC
iface
The name of the interface to manage
addr
IP address with subnet length (ex. ``10.1.2.3/24``). The
:mod:`ip.get_subnet_length <salt.modules.win_ip.get_subnet_length>`
function can be used to calculate the subnet length from a netmask.
gateway : None
If specified, the default gateway will be set to this value.
append : False
If ``True``, this IP address will be added to the interface. Default is
``False``, which overrides any existing configuration for the interface
and sets ``addr`` as the only address on the interface.
CLI Example:
.. code-block:: bash
salt -G 'os_family:Windows' ip.set_static_ip 'Local Area Connection' 10.1.2.3/24 gateway=10.1.2.1
salt -G 'os_family:Windows' ip.set_static_ip 'Local Area Connection' 10.1.2.4/24 append=True
'''
def _find_addr(iface, addr, timeout=1):
ip, cidr = addr.rsplit('/', 1)
netmask = salt.utils.network.cidr_to_ipv4_netmask(cidr)
for idx in range(timeout):
for addrinfo in get_interface(iface).get('ip_addrs', []):
if addrinfo['IP Address'] == ip \
and addrinfo['Netmask'] == netmask:
return addrinfo
time.sleep(1)
return {}
if not salt.utils.validate.net.ipv4_addr(addr):
raise SaltInvocationError('Invalid address \'{0}\''.format(addr))
if gateway and not salt.utils.validate.net.ipv4_addr(addr):
raise SaltInvocationError(
'Invalid default gateway \'{0}\''.format(gateway)
)
if '/' not in addr:
addr += '/32'
if append and _find_addr(iface, addr):
raise CommandExecutionError(
'Address \'{0}\' already exists on interface '
'\'{1}\''.format(addr, iface)
)
cmd = ['netsh', 'interface', 'ip']
if append:
cmd.append('add')
else:
cmd.append('set')
cmd.extend(['address', 'name={0}'.format(iface)])
if not append:
cmd.append('source=static')
cmd.append('address={0}'.format(addr))
if gateway:
cmd.append('gateway={0}'.format(gateway))
result = __salt__['cmd.run_all'](cmd, python_shell=False)
if result['retcode'] != 0:
raise CommandExecutionError(
'Unable to set IP address: {0}'.format(result['stderr'])
)
new_addr = _find_addr(iface, addr, timeout=10)
if not new_addr:
return {}
ret = {'Address Info': new_addr}
if gateway:
ret['Default Gateway'] = gateway
return ret | [
"def",
"set_static_ip",
"(",
"iface",
",",
"addr",
",",
"gateway",
"=",
"None",
",",
"append",
"=",
"False",
")",
":",
"def",
"_find_addr",
"(",
"iface",
",",
"addr",
",",
"timeout",
"=",
"1",
")",
":",
"ip",
",",
"cidr",
"=",
"addr",
".",
"rsplit"... | Set static IP configuration on a Windows NIC
iface
The name of the interface to manage
addr
IP address with subnet length (ex. ``10.1.2.3/24``). The
:mod:`ip.get_subnet_length <salt.modules.win_ip.get_subnet_length>`
function can be used to calculate the subnet length from a netmask.
gateway : None
If specified, the default gateway will be set to this value.
append : False
If ``True``, this IP address will be added to the interface. Default is
``False``, which overrides any existing configuration for the interface
and sets ``addr`` as the only address on the interface.
CLI Example:
.. code-block:: bash
salt -G 'os_family:Windows' ip.set_static_ip 'Local Area Connection' 10.1.2.3/24 gateway=10.1.2.1
salt -G 'os_family:Windows' ip.set_static_ip 'Local Area Connection' 10.1.2.4/24 append=True | [
"Set",
"static",
"IP",
"configuration",
"on",
"a",
"Windows",
"NIC"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_ip.py#L224-L304 | train |
saltstack/salt | salt/modules/win_ip.py | set_static_dns | def set_static_dns(iface, *addrs):
'''
Set static DNS configuration on a Windows NIC
Args:
iface (str): The name of the interface to set
addrs (*):
One or more DNS servers to be added. To clear the list of DNS
servers pass an empty list (``[]``). If undefined or ``None`` no
changes will be made.
Returns:
dict: A dictionary containing the new DNS settings
CLI Example:
.. code-block:: bash
salt -G 'os_family:Windows' ip.set_static_dns 'Local Area Connection' '192.168.1.1'
salt -G 'os_family:Windows' ip.set_static_dns 'Local Area Connection' '192.168.1.252' '192.168.1.253'
'''
if addrs is () or str(addrs[0]).lower() == 'none':
return {'Interface': iface, 'DNS Server': 'No Changes'}
# Clear the list of DNS servers if [] is passed
if str(addrs[0]).lower() == '[]':
log.debug('Clearing list of DNS servers')
cmd = ['netsh', 'interface', 'ip', 'set', 'dns',
'name={0}'.format(iface),
'source=static',
'address=none']
__salt__['cmd.run'](cmd, python_shell=False)
return {'Interface': iface, 'DNS Server': []}
addr_index = 1
for addr in addrs:
if addr_index == 1:
cmd = ['netsh', 'interface', 'ip', 'set', 'dns',
'name={0}'.format(iface),
'source=static',
'address={0}'.format(addr),
'register=primary']
__salt__['cmd.run'](cmd, python_shell=False)
addr_index = addr_index + 1
else:
cmd = ['netsh', 'interface', 'ip', 'add', 'dns',
'name={0}'.format(iface),
'address={0}'.format(addr),
'index={0}'.format(addr_index)]
__salt__['cmd.run'](cmd, python_shell=False)
addr_index = addr_index + 1
return {'Interface': iface, 'DNS Server': addrs} | python | def set_static_dns(iface, *addrs):
'''
Set static DNS configuration on a Windows NIC
Args:
iface (str): The name of the interface to set
addrs (*):
One or more DNS servers to be added. To clear the list of DNS
servers pass an empty list (``[]``). If undefined or ``None`` no
changes will be made.
Returns:
dict: A dictionary containing the new DNS settings
CLI Example:
.. code-block:: bash
salt -G 'os_family:Windows' ip.set_static_dns 'Local Area Connection' '192.168.1.1'
salt -G 'os_family:Windows' ip.set_static_dns 'Local Area Connection' '192.168.1.252' '192.168.1.253'
'''
if addrs is () or str(addrs[0]).lower() == 'none':
return {'Interface': iface, 'DNS Server': 'No Changes'}
# Clear the list of DNS servers if [] is passed
if str(addrs[0]).lower() == '[]':
log.debug('Clearing list of DNS servers')
cmd = ['netsh', 'interface', 'ip', 'set', 'dns',
'name={0}'.format(iface),
'source=static',
'address=none']
__salt__['cmd.run'](cmd, python_shell=False)
return {'Interface': iface, 'DNS Server': []}
addr_index = 1
for addr in addrs:
if addr_index == 1:
cmd = ['netsh', 'interface', 'ip', 'set', 'dns',
'name={0}'.format(iface),
'source=static',
'address={0}'.format(addr),
'register=primary']
__salt__['cmd.run'](cmd, python_shell=False)
addr_index = addr_index + 1
else:
cmd = ['netsh', 'interface', 'ip', 'add', 'dns',
'name={0}'.format(iface),
'address={0}'.format(addr),
'index={0}'.format(addr_index)]
__salt__['cmd.run'](cmd, python_shell=False)
addr_index = addr_index + 1
return {'Interface': iface, 'DNS Server': addrs} | [
"def",
"set_static_dns",
"(",
"iface",
",",
"*",
"addrs",
")",
":",
"if",
"addrs",
"is",
"(",
")",
"or",
"str",
"(",
"addrs",
"[",
"0",
"]",
")",
".",
"lower",
"(",
")",
"==",
"'none'",
":",
"return",
"{",
"'Interface'",
":",
"iface",
",",
"'DNS ... | Set static DNS configuration on a Windows NIC
Args:
iface (str): The name of the interface to set
addrs (*):
One or more DNS servers to be added. To clear the list of DNS
servers pass an empty list (``[]``). If undefined or ``None`` no
changes will be made.
Returns:
dict: A dictionary containing the new DNS settings
CLI Example:
.. code-block:: bash
salt -G 'os_family:Windows' ip.set_static_dns 'Local Area Connection' '192.168.1.1'
salt -G 'os_family:Windows' ip.set_static_dns 'Local Area Connection' '192.168.1.252' '192.168.1.253' | [
"Set",
"static",
"DNS",
"configuration",
"on",
"a",
"Windows",
"NIC"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_ip.py#L322-L373 | train |
saltstack/salt | salt/modules/win_ip.py | get_default_gateway | def get_default_gateway():
'''
Set DNS source to DHCP on Windows
CLI Example:
.. code-block:: bash
salt -G 'os_family:Windows' ip.get_default_gateway
'''
try:
return next(iter(
x.split()[-1] for x in __salt__['cmd.run'](
['netsh', 'interface', 'ip', 'show', 'config'],
python_shell=False
).splitlines()
if 'Default Gateway:' in x
))
except StopIteration:
raise CommandExecutionError('Unable to find default gateway') | python | def get_default_gateway():
'''
Set DNS source to DHCP on Windows
CLI Example:
.. code-block:: bash
salt -G 'os_family:Windows' ip.get_default_gateway
'''
try:
return next(iter(
x.split()[-1] for x in __salt__['cmd.run'](
['netsh', 'interface', 'ip', 'show', 'config'],
python_shell=False
).splitlines()
if 'Default Gateway:' in x
))
except StopIteration:
raise CommandExecutionError('Unable to find default gateway') | [
"def",
"get_default_gateway",
"(",
")",
":",
"try",
":",
"return",
"next",
"(",
"iter",
"(",
"x",
".",
"split",
"(",
")",
"[",
"-",
"1",
"]",
"for",
"x",
"in",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"[",
"'netsh'",
",",
"'interface'",
",",
"'ip'",... | Set DNS source to DHCP on Windows
CLI Example:
.. code-block:: bash
salt -G 'os_family:Windows' ip.get_default_gateway | [
"Set",
"DNS",
"source",
"to",
"DHCP",
"on",
"Windows"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_ip.py#L406-L425 | train |
saltstack/salt | salt/modules/mac_group.py | add | def add(name, gid=None, **kwargs):
'''
Add the specified group
CLI Example:
.. code-block:: bash
salt '*' group.add foo 3456
'''
### NOTE: **kwargs isn't used here but needs to be included in this
### function for compatibility with the group.present state
if info(name):
raise CommandExecutionError(
'Group \'{0}\' already exists'.format(name)
)
if salt.utils.stringutils.contains_whitespace(name):
raise SaltInvocationError('Group name cannot contain whitespace')
if name.startswith('_'):
raise SaltInvocationError(
'Salt will not create groups beginning with underscores'
)
if gid is not None and not isinstance(gid, int):
raise SaltInvocationError('gid must be an integer')
# check if gid is already in use
gid_list = _list_gids()
if six.text_type(gid) in gid_list:
raise CommandExecutionError(
'gid \'{0}\' already exists'.format(gid)
)
cmd = ['dseditgroup', '-o', 'create']
if gid:
cmd.extend(['-i', gid])
cmd.append(name)
return __salt__['cmd.retcode'](cmd, python_shell=False) == 0 | python | def add(name, gid=None, **kwargs):
'''
Add the specified group
CLI Example:
.. code-block:: bash
salt '*' group.add foo 3456
'''
### NOTE: **kwargs isn't used here but needs to be included in this
### function for compatibility with the group.present state
if info(name):
raise CommandExecutionError(
'Group \'{0}\' already exists'.format(name)
)
if salt.utils.stringutils.contains_whitespace(name):
raise SaltInvocationError('Group name cannot contain whitespace')
if name.startswith('_'):
raise SaltInvocationError(
'Salt will not create groups beginning with underscores'
)
if gid is not None and not isinstance(gid, int):
raise SaltInvocationError('gid must be an integer')
# check if gid is already in use
gid_list = _list_gids()
if six.text_type(gid) in gid_list:
raise CommandExecutionError(
'gid \'{0}\' already exists'.format(gid)
)
cmd = ['dseditgroup', '-o', 'create']
if gid:
cmd.extend(['-i', gid])
cmd.append(name)
return __salt__['cmd.retcode'](cmd, python_shell=False) == 0 | [
"def",
"add",
"(",
"name",
",",
"gid",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"### NOTE: **kwargs isn't used here but needs to be included in this",
"### function for compatibility with the group.present state",
"if",
"info",
"(",
"name",
")",
":",
"raise",
"Co... | Add the specified group
CLI Example:
.. code-block:: bash
salt '*' group.add foo 3456 | [
"Add",
"the",
"specified",
"group"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_group.py#L37-L72 | train |
saltstack/salt | salt/modules/mac_group.py | _list_gids | def _list_gids():
'''
Return a list of gids in use
'''
output = __salt__['cmd.run'](
['dscacheutil', '-q', 'group'],
output_loglevel='quiet',
python_shell=False
)
ret = set()
for line in salt.utils.itertools.split(output, '\n'):
if line.startswith('gid:'):
ret.update(line.split()[1:])
return sorted(ret) | python | def _list_gids():
'''
Return a list of gids in use
'''
output = __salt__['cmd.run'](
['dscacheutil', '-q', 'group'],
output_loglevel='quiet',
python_shell=False
)
ret = set()
for line in salt.utils.itertools.split(output, '\n'):
if line.startswith('gid:'):
ret.update(line.split()[1:])
return sorted(ret) | [
"def",
"_list_gids",
"(",
")",
":",
"output",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"[",
"'dscacheutil'",
",",
"'-q'",
",",
"'group'",
"]",
",",
"output_loglevel",
"=",
"'quiet'",
",",
"python_shell",
"=",
"False",
")",
"ret",
"=",
"set",
"(",
"... | Return a list of gids in use | [
"Return",
"a",
"list",
"of",
"gids",
"in",
"use"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_group.py#L75-L88 | train |
saltstack/salt | salt/modules/mac_group.py | delete | def delete(name):
'''
Remove the named group
CLI Example:
.. code-block:: bash
salt '*' group.delete foo
'''
if salt.utils.stringutils.contains_whitespace(name):
raise SaltInvocationError('Group name cannot contain whitespace')
if name.startswith('_'):
raise SaltInvocationError(
'Salt will not remove groups beginning with underscores'
)
if not info(name):
return True
cmd = ['dseditgroup', '-o', 'delete', name]
return __salt__['cmd.retcode'](cmd, python_shell=False) == 0 | python | def delete(name):
'''
Remove the named group
CLI Example:
.. code-block:: bash
salt '*' group.delete foo
'''
if salt.utils.stringutils.contains_whitespace(name):
raise SaltInvocationError('Group name cannot contain whitespace')
if name.startswith('_'):
raise SaltInvocationError(
'Salt will not remove groups beginning with underscores'
)
if not info(name):
return True
cmd = ['dseditgroup', '-o', 'delete', name]
return __salt__['cmd.retcode'](cmd, python_shell=False) == 0 | [
"def",
"delete",
"(",
"name",
")",
":",
"if",
"salt",
".",
"utils",
".",
"stringutils",
".",
"contains_whitespace",
"(",
"name",
")",
":",
"raise",
"SaltInvocationError",
"(",
"'Group name cannot contain whitespace'",
")",
"if",
"name",
".",
"startswith",
"(",
... | Remove the named group
CLI Example:
.. code-block:: bash
salt '*' group.delete foo | [
"Remove",
"the",
"named",
"group"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_group.py#L91-L110 | train |
saltstack/salt | salt/modules/mac_group.py | members | def members(name, members_list):
'''
Replaces members of the group with a provided list.
.. versionadded:: 2016.3.0
CLI Example:
salt '*' group.members foo 'user1,user2,user3,...'
Replaces a membership list for a local group 'foo'.
'''
retcode = 1
grp_info = __salt__['group.info'](name)
if grp_info and name in grp_info['name']:
cmd = '/usr/bin/dscl . -delete /Groups/{0} GroupMembership'.format(name)
retcode = __salt__['cmd.retcode'](cmd) == 0
for user in members_list.split(','):
cmd = '/usr/bin/dscl . -merge /Groups/{0} GroupMembership {1}'.format(name, user)
retcode = __salt__['cmd.retcode'](cmd)
if not retcode == 0:
break
# provided list is '': users previously deleted from group
else:
retcode = 0
return retcode == 0 | python | def members(name, members_list):
'''
Replaces members of the group with a provided list.
.. versionadded:: 2016.3.0
CLI Example:
salt '*' group.members foo 'user1,user2,user3,...'
Replaces a membership list for a local group 'foo'.
'''
retcode = 1
grp_info = __salt__['group.info'](name)
if grp_info and name in grp_info['name']:
cmd = '/usr/bin/dscl . -delete /Groups/{0} GroupMembership'.format(name)
retcode = __salt__['cmd.retcode'](cmd) == 0
for user in members_list.split(','):
cmd = '/usr/bin/dscl . -merge /Groups/{0} GroupMembership {1}'.format(name, user)
retcode = __salt__['cmd.retcode'](cmd)
if not retcode == 0:
break
# provided list is '': users previously deleted from group
else:
retcode = 0
return retcode == 0 | [
"def",
"members",
"(",
"name",
",",
"members_list",
")",
":",
"retcode",
"=",
"1",
"grp_info",
"=",
"__salt__",
"[",
"'group.info'",
"]",
"(",
"name",
")",
"if",
"grp_info",
"and",
"name",
"in",
"grp_info",
"[",
"'name'",
"]",
":",
"cmd",
"=",
"'/usr/b... | Replaces members of the group with a provided list.
.. versionadded:: 2016.3.0
CLI Example:
salt '*' group.members foo 'user1,user2,user3,...'
Replaces a membership list for a local group 'foo'. | [
"Replaces",
"members",
"of",
"the",
"group",
"with",
"a",
"provided",
"list",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_group.py#L149-L175 | train |
saltstack/salt | salt/modules/mac_group.py | info | def info(name):
'''
Return information about a group
CLI Example:
.. code-block:: bash
salt '*' group.info foo
'''
if salt.utils.stringutils.contains_whitespace(name):
raise SaltInvocationError('Group name cannot contain whitespace')
try:
# getgrnam seems to cache weirdly, so don't use it
grinfo = next(iter(x for x in grp.getgrall() if x.gr_name == name))
except StopIteration:
return {}
else:
return _format_info(grinfo) | python | def info(name):
'''
Return information about a group
CLI Example:
.. code-block:: bash
salt '*' group.info foo
'''
if salt.utils.stringutils.contains_whitespace(name):
raise SaltInvocationError('Group name cannot contain whitespace')
try:
# getgrnam seems to cache weirdly, so don't use it
grinfo = next(iter(x for x in grp.getgrall() if x.gr_name == name))
except StopIteration:
return {}
else:
return _format_info(grinfo) | [
"def",
"info",
"(",
"name",
")",
":",
"if",
"salt",
".",
"utils",
".",
"stringutils",
".",
"contains_whitespace",
"(",
"name",
")",
":",
"raise",
"SaltInvocationError",
"(",
"'Group name cannot contain whitespace'",
")",
"try",
":",
"# getgrnam seems to cache weirdl... | Return information about a group
CLI Example:
.. code-block:: bash
salt '*' group.info foo | [
"Return",
"information",
"about",
"a",
"group"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_group.py#L178-L196 | train |
saltstack/salt | salt/modules/mac_group.py | _format_info | def _format_info(data):
'''
Return formatted information in a pretty way.
'''
return {'name': data.gr_name,
'gid': data.gr_gid,
'passwd': data.gr_passwd,
'members': data.gr_mem} | python | def _format_info(data):
'''
Return formatted information in a pretty way.
'''
return {'name': data.gr_name,
'gid': data.gr_gid,
'passwd': data.gr_passwd,
'members': data.gr_mem} | [
"def",
"_format_info",
"(",
"data",
")",
":",
"return",
"{",
"'name'",
":",
"data",
".",
"gr_name",
",",
"'gid'",
":",
"data",
".",
"gr_gid",
",",
"'passwd'",
":",
"data",
".",
"gr_passwd",
",",
"'members'",
":",
"data",
".",
"gr_mem",
"}"
] | Return formatted information in a pretty way. | [
"Return",
"formatted",
"information",
"in",
"a",
"pretty",
"way",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_group.py#L199-L206 | train |
saltstack/salt | salt/modules/mac_group.py | getent | def getent(refresh=False):
'''
Return info on all groups
CLI Example:
.. code-block:: bash
salt '*' group.getent
'''
if 'group.getent' in __context__ and not refresh:
return __context__['group.getent']
ret = []
for grinfo in grp.getgrall():
if not grinfo.gr_name.startswith('_'):
ret.append(_format_info(grinfo))
__context__['group.getent'] = ret
return ret | python | def getent(refresh=False):
'''
Return info on all groups
CLI Example:
.. code-block:: bash
salt '*' group.getent
'''
if 'group.getent' in __context__ and not refresh:
return __context__['group.getent']
ret = []
for grinfo in grp.getgrall():
if not grinfo.gr_name.startswith('_'):
ret.append(_format_info(grinfo))
__context__['group.getent'] = ret
return ret | [
"def",
"getent",
"(",
"refresh",
"=",
"False",
")",
":",
"if",
"'group.getent'",
"in",
"__context__",
"and",
"not",
"refresh",
":",
"return",
"__context__",
"[",
"'group.getent'",
"]",
"ret",
"=",
"[",
"]",
"for",
"grinfo",
"in",
"grp",
".",
"getgrall",
... | Return info on all groups
CLI Example:
.. code-block:: bash
salt '*' group.getent | [
"Return",
"info",
"on",
"all",
"groups"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_group.py#L209-L227 | train |
saltstack/salt | salt/modules/mac_group.py | chgid | def chgid(name, gid):
'''
Change the gid for a named group
CLI Example:
.. code-block:: bash
salt '*' group.chgid foo 4376
'''
if not isinstance(gid, int):
raise SaltInvocationError('gid must be an integer')
pre_gid = __salt__['file.group_to_gid'](name)
pre_info = info(name)
if not pre_info:
raise CommandExecutionError(
'Group \'{0}\' does not exist'.format(name)
)
if gid == pre_info['gid']:
return True
cmd = ['dseditgroup', '-o', 'edit', '-i', gid, name]
return __salt__['cmd.retcode'](cmd, python_shell=False) == 0 | python | def chgid(name, gid):
'''
Change the gid for a named group
CLI Example:
.. code-block:: bash
salt '*' group.chgid foo 4376
'''
if not isinstance(gid, int):
raise SaltInvocationError('gid must be an integer')
pre_gid = __salt__['file.group_to_gid'](name)
pre_info = info(name)
if not pre_info:
raise CommandExecutionError(
'Group \'{0}\' does not exist'.format(name)
)
if gid == pre_info['gid']:
return True
cmd = ['dseditgroup', '-o', 'edit', '-i', gid, name]
return __salt__['cmd.retcode'](cmd, python_shell=False) == 0 | [
"def",
"chgid",
"(",
"name",
",",
"gid",
")",
":",
"if",
"not",
"isinstance",
"(",
"gid",
",",
"int",
")",
":",
"raise",
"SaltInvocationError",
"(",
"'gid must be an integer'",
")",
"pre_gid",
"=",
"__salt__",
"[",
"'file.group_to_gid'",
"]",
"(",
"name",
... | Change the gid for a named group
CLI Example:
.. code-block:: bash
salt '*' group.chgid foo 4376 | [
"Change",
"the",
"gid",
"for",
"a",
"named",
"group"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_group.py#L230-L251 | train |
saltstack/salt | salt/utils/etcd_util.py | EtcdClient.tree | def tree(self, path):
'''
.. versionadded:: 2014.7.0
Recurse through etcd and return all values
'''
ret = {}
try:
items = self.read(path)
except (etcd.EtcdKeyNotFound, ValueError):
return None
except etcd.EtcdConnectionFailed:
log.error("etcd: failed to perform 'tree' operation on path %s due to connection error", path)
return None
for item in items.children:
comps = six.text_type(item.key).split('/')
if item.dir is True:
if item.key == path:
continue
ret[comps[-1]] = self.tree(item.key)
else:
ret[comps[-1]] = item.value
return ret | python | def tree(self, path):
'''
.. versionadded:: 2014.7.0
Recurse through etcd and return all values
'''
ret = {}
try:
items = self.read(path)
except (etcd.EtcdKeyNotFound, ValueError):
return None
except etcd.EtcdConnectionFailed:
log.error("etcd: failed to perform 'tree' operation on path %s due to connection error", path)
return None
for item in items.children:
comps = six.text_type(item.key).split('/')
if item.dir is True:
if item.key == path:
continue
ret[comps[-1]] = self.tree(item.key)
else:
ret[comps[-1]] = item.value
return ret | [
"def",
"tree",
"(",
"self",
",",
"path",
")",
":",
"ret",
"=",
"{",
"}",
"try",
":",
"items",
"=",
"self",
".",
"read",
"(",
"path",
")",
"except",
"(",
"etcd",
".",
"EtcdKeyNotFound",
",",
"ValueError",
")",
":",
"return",
"None",
"except",
"etcd"... | .. versionadded:: 2014.7.0
Recurse through etcd and return all values | [
"..",
"versionadded",
"::",
"2014",
".",
"7",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/etcd_util.py#L355-L378 | train |
saltstack/salt | salt/pillar/cobbler.py | ext_pillar | def ext_pillar(minion_id,
pillar, # pylint: disable=W0613
key=None,
only=()):
'''
Read pillar data from Cobbler via its API.
'''
url = __opts__['cobbler.url']
user = __opts__['cobbler.user']
password = __opts__['cobbler.password']
log.info("Querying cobbler at %r for information for %r", url, minion_id)
try:
server = salt.ext.six.moves.xmlrpc_client.Server(url, allow_none=True)
if user:
server.login(user, password)
result = server.get_blended_data(None, minion_id)
except Exception:
log.exception(
'Could not connect to cobbler.'
)
return {}
if only:
result = dict((k, result[k]) for k in only if k in result)
if key:
result = {key: result}
return result | python | def ext_pillar(minion_id,
pillar, # pylint: disable=W0613
key=None,
only=()):
'''
Read pillar data from Cobbler via its API.
'''
url = __opts__['cobbler.url']
user = __opts__['cobbler.user']
password = __opts__['cobbler.password']
log.info("Querying cobbler at %r for information for %r", url, minion_id)
try:
server = salt.ext.six.moves.xmlrpc_client.Server(url, allow_none=True)
if user:
server.login(user, password)
result = server.get_blended_data(None, minion_id)
except Exception:
log.exception(
'Could not connect to cobbler.'
)
return {}
if only:
result = dict((k, result[k]) for k in only if k in result)
if key:
result = {key: result}
return result | [
"def",
"ext_pillar",
"(",
"minion_id",
",",
"pillar",
",",
"# pylint: disable=W0613",
"key",
"=",
"None",
",",
"only",
"=",
"(",
")",
")",
":",
"url",
"=",
"__opts__",
"[",
"'cobbler.url'",
"]",
"user",
"=",
"__opts__",
"[",
"'cobbler.user'",
"]",
"passwor... | Read pillar data from Cobbler via its API. | [
"Read",
"pillar",
"data",
"from",
"Cobbler",
"via",
"its",
"API",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/cobbler.py#L44-L72 | train |
saltstack/salt | salt/states/rvm.py | _check_and_install_ruby | def _check_and_install_ruby(ret, ruby, default=False, user=None, opts=None, env=None):
'''
Verify that ruby is installed, install if unavailable
'''
ret = _check_ruby(ret, ruby, user=user)
if not ret['result']:
if __salt__['rvm.install_ruby'](ruby, runas=user, opts=opts, env=env):
ret['result'] = True
ret['changes'][ruby] = 'Installed'
ret['comment'] = 'Successfully installed ruby.'
ret['default'] = False
else:
ret['result'] = False
ret['comment'] = 'Could not install ruby.'
return ret
if default:
__salt__['rvm.set_default'](ruby, runas=user)
return ret | python | def _check_and_install_ruby(ret, ruby, default=False, user=None, opts=None, env=None):
'''
Verify that ruby is installed, install if unavailable
'''
ret = _check_ruby(ret, ruby, user=user)
if not ret['result']:
if __salt__['rvm.install_ruby'](ruby, runas=user, opts=opts, env=env):
ret['result'] = True
ret['changes'][ruby] = 'Installed'
ret['comment'] = 'Successfully installed ruby.'
ret['default'] = False
else:
ret['result'] = False
ret['comment'] = 'Could not install ruby.'
return ret
if default:
__salt__['rvm.set_default'](ruby, runas=user)
return ret | [
"def",
"_check_and_install_ruby",
"(",
"ret",
",",
"ruby",
",",
"default",
"=",
"False",
",",
"user",
"=",
"None",
",",
"opts",
"=",
"None",
",",
"env",
"=",
"None",
")",
":",
"ret",
"=",
"_check_ruby",
"(",
"ret",
",",
"ruby",
",",
"user",
"=",
"u... | Verify that ruby is installed, install if unavailable | [
"Verify",
"that",
"ruby",
"is",
"installed",
"install",
"if",
"unavailable"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/rvm.py#L119-L138 | train |
saltstack/salt | salt/states/rvm.py | _check_ruby | def _check_ruby(ret, ruby, user=None):
'''
Check that ruby is installed
'''
match_version = True
match_micro_version = False
micro_version_regex = re.compile(r'-([0-9]{4}\.[0-9]{2}|p[0-9]+)$')
if micro_version_regex.search(ruby):
match_micro_version = True
if re.search('^[a-z]+$', ruby):
match_version = False
ruby = re.sub('^ruby-', '', ruby)
for impl, version, default in __salt__['rvm.list'](runas=user):
if impl != 'ruby':
version = '{impl}-{version}'.format(impl=impl, version=version)
if not match_micro_version:
version = micro_version_regex.sub('', version)
if not match_version:
version = re.sub('-.*', '', version)
if version == ruby:
ret['result'] = True
ret['comment'] = 'Requested ruby exists.'
ret['default'] = default
break
return ret | python | def _check_ruby(ret, ruby, user=None):
'''
Check that ruby is installed
'''
match_version = True
match_micro_version = False
micro_version_regex = re.compile(r'-([0-9]{4}\.[0-9]{2}|p[0-9]+)$')
if micro_version_regex.search(ruby):
match_micro_version = True
if re.search('^[a-z]+$', ruby):
match_version = False
ruby = re.sub('^ruby-', '', ruby)
for impl, version, default in __salt__['rvm.list'](runas=user):
if impl != 'ruby':
version = '{impl}-{version}'.format(impl=impl, version=version)
if not match_micro_version:
version = micro_version_regex.sub('', version)
if not match_version:
version = re.sub('-.*', '', version)
if version == ruby:
ret['result'] = True
ret['comment'] = 'Requested ruby exists.'
ret['default'] = default
break
return ret | [
"def",
"_check_ruby",
"(",
"ret",
",",
"ruby",
",",
"user",
"=",
"None",
")",
":",
"match_version",
"=",
"True",
"match_micro_version",
"=",
"False",
"micro_version_regex",
"=",
"re",
".",
"compile",
"(",
"r'-([0-9]{4}\\.[0-9]{2}|p[0-9]+)$'",
")",
"if",
"micro_v... | Check that ruby is installed | [
"Check",
"that",
"ruby",
"is",
"installed"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/rvm.py#L141-L166 | train |
saltstack/salt | salt/states/rvm.py | installed | def installed(name, default=False, user=None, opts=None, env=None):
'''
Verify that the specified ruby is installed with RVM. RVM is
installed when necessary.
name
The version of ruby to install
default : False
Whether to make this ruby the default.
user: None
The user to run rvm as.
env: None
A list of environment variables to set (ie, RUBY_CONFIGURE_OPTS)
opts: None
A list of option flags to pass to RVM (ie -C, --patch)
.. versionadded:: 0.17.0
'''
ret = {'name': name, 'result': None, 'comment': '', 'changes': {}}
if __opts__['test']:
ret['comment'] = 'Ruby {0} is set to be installed'.format(name)
return ret
ret = _check_rvm(ret, user)
if ret['result'] is False:
if not __salt__['rvm.install'](runas=user):
ret['comment'] = 'RVM failed to install.'
return ret
else:
return _check_and_install_ruby(ret, name, default, user=user, opts=opts, env=env)
else:
return _check_and_install_ruby(ret, name, default, user=user, opts=opts, env=env) | python | def installed(name, default=False, user=None, opts=None, env=None):
'''
Verify that the specified ruby is installed with RVM. RVM is
installed when necessary.
name
The version of ruby to install
default : False
Whether to make this ruby the default.
user: None
The user to run rvm as.
env: None
A list of environment variables to set (ie, RUBY_CONFIGURE_OPTS)
opts: None
A list of option flags to pass to RVM (ie -C, --patch)
.. versionadded:: 0.17.0
'''
ret = {'name': name, 'result': None, 'comment': '', 'changes': {}}
if __opts__['test']:
ret['comment'] = 'Ruby {0} is set to be installed'.format(name)
return ret
ret = _check_rvm(ret, user)
if ret['result'] is False:
if not __salt__['rvm.install'](runas=user):
ret['comment'] = 'RVM failed to install.'
return ret
else:
return _check_and_install_ruby(ret, name, default, user=user, opts=opts, env=env)
else:
return _check_and_install_ruby(ret, name, default, user=user, opts=opts, env=env) | [
"def",
"installed",
"(",
"name",
",",
"default",
"=",
"False",
",",
"user",
"=",
"None",
",",
"opts",
"=",
"None",
",",
"env",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"None",
",",
"'comment'",
":",
"''... | Verify that the specified ruby is installed with RVM. RVM is
installed when necessary.
name
The version of ruby to install
default : False
Whether to make this ruby the default.
user: None
The user to run rvm as.
env: None
A list of environment variables to set (ie, RUBY_CONFIGURE_OPTS)
opts: None
A list of option flags to pass to RVM (ie -C, --patch)
.. versionadded:: 0.17.0 | [
"Verify",
"that",
"the",
"specified",
"ruby",
"is",
"installed",
"with",
"RVM",
".",
"RVM",
"is",
"installed",
"when",
"necessary",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/rvm.py#L169-L205 | train |
saltstack/salt | salt/states/rvm.py | gemset_present | def gemset_present(name, ruby='default', user=None):
'''
Verify that the gemset is present.
name
The name of the gemset.
ruby: default
The ruby version this gemset belongs to.
user: None
The user to run rvm as.
.. versionadded:: 0.17.0
'''
ret = {'name': name, 'result': None, 'comment': '', 'changes': {}}
ret = _check_rvm(ret, user)
if ret['result'] is False:
return ret
if '@' in name:
ruby, name = name.split('@')
ret = _check_ruby(ret, ruby)
if not ret['result']:
ret['result'] = False
ret['comment'] = 'Requested ruby implementation was not found.'
return ret
if name in __salt__['rvm.gemset_list'](ruby, runas=user):
ret['result'] = True
ret['comment'] = 'Gemset already exists.'
else:
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Set to install gemset {0}'.format(name)
return ret
if __salt__['rvm.gemset_create'](ruby, name, runas=user):
ret['result'] = True
ret['comment'] = 'Gemset successfully created.'
ret['changes'][name] = 'created'
else:
ret['result'] = False
ret['comment'] = 'Gemset could not be created.'
return ret | python | def gemset_present(name, ruby='default', user=None):
'''
Verify that the gemset is present.
name
The name of the gemset.
ruby: default
The ruby version this gemset belongs to.
user: None
The user to run rvm as.
.. versionadded:: 0.17.0
'''
ret = {'name': name, 'result': None, 'comment': '', 'changes': {}}
ret = _check_rvm(ret, user)
if ret['result'] is False:
return ret
if '@' in name:
ruby, name = name.split('@')
ret = _check_ruby(ret, ruby)
if not ret['result']:
ret['result'] = False
ret['comment'] = 'Requested ruby implementation was not found.'
return ret
if name in __salt__['rvm.gemset_list'](ruby, runas=user):
ret['result'] = True
ret['comment'] = 'Gemset already exists.'
else:
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Set to install gemset {0}'.format(name)
return ret
if __salt__['rvm.gemset_create'](ruby, name, runas=user):
ret['result'] = True
ret['comment'] = 'Gemset successfully created.'
ret['changes'][name] = 'created'
else:
ret['result'] = False
ret['comment'] = 'Gemset could not be created.'
return ret | [
"def",
"gemset_present",
"(",
"name",
",",
"ruby",
"=",
"'default'",
",",
"user",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"None",
",",
"'comment'",
":",
"''",
",",
"'changes'",
":",
"{",
"}",
"}",
"ret",... | Verify that the gemset is present.
name
The name of the gemset.
ruby: default
The ruby version this gemset belongs to.
user: None
The user to run rvm as.
.. versionadded:: 0.17.0 | [
"Verify",
"that",
"the",
"gemset",
"is",
"present",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/rvm.py#L208-L253 | train |
saltstack/salt | salt/states/postgres_tablespace.py | present | def present(name,
directory,
options=None,
owner=None,
user=None,
maintenance_db=None,
db_password=None,
db_host=None,
db_port=None,
db_user=None):
'''
Ensure that the named tablespace is present with the specified properties.
For more information about all of these options run ``man 7
create_tablespace``.
name
The name of the tablespace to create/manage.
directory
The directory where the tablespace will be located, must already exist
options
A dictionary of options to specify for the tablespace.
Currently, the only tablespace options supported are ``seq_page_cost``
and ``random_page_cost``. Default values are shown in the example below:
.. code-block:: yaml
my_space:
postgres_tablespace.present:
- directory: /srv/my_tablespace
- options:
seq_page_cost: 1.0
random_page_cost: 4.0
owner
The database user that will be the owner of the tablespace.
Defaults to the user executing the command (i.e. the `user` option)
user
System user all operations should be performed on behalf of
maintenance_db
Database to act on
db_user
Database username if different from config or default
db_password
User password if any password for a specified user
db_host
Database host if different from config or default
db_port
Database port if different from config or default
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': 'Tablespace {0} is already present'.format(name)}
dbargs = {
'maintenance_db': maintenance_db,
'runas': user,
'host': db_host,
'user': db_user,
'port': db_port,
'password': db_password,
}
tblspaces = __salt__['postgres.tablespace_list'](**dbargs)
if name not in tblspaces:
# not there, create it
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Tablespace {0} is set to be created'.format(name)
return ret
if __salt__['postgres.tablespace_create'](name, directory, options,
owner, **dbargs):
ret['comment'] = 'The tablespace {0} has been created'.format(name)
ret['changes'][name] = 'Present'
return ret
# already exists, make sure it's got the right config
if tblspaces[name]['Location'] != directory and not __opts__['test']:
ret['comment'] = """Tablespace {0} is not at the right location. This is
unfixable without dropping and recreating the tablespace.""".format(
name)
ret['result'] = False
return ret
if owner and not tblspaces[name]['Owner'] == owner:
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Tablespace {0} owner to be altered'.format(name)
if (__salt__['postgres.tablespace_alter'](name, new_owner=owner)
and not __opts__['test']):
ret['comment'] = 'Tablespace {0} owner changed'.format(name)
ret['changes'][name] = {'owner': owner}
ret['result'] = True
if options:
# options comes from postgres as a sort of json(ish) string, but it
# can't really be parsed out, but it's in a fairly consistent format
# that we should be able to string check:
# {seq_page_cost=1.1,random_page_cost=3.9}
# TODO remove options that exist if possible
for k, v in iteritems(options):
# if 'seq_page_cost=1.1' not in '{seq_page_cost=1.1,...}'
if '{0}={1}'.format(k, v) not in tblspaces[name]['Opts']:
if __opts__['test']:
ret['result'] = None
ret['comment'] = """Tablespace {0} options to be
altered""".format(name)
break # we know it's going to be altered, no reason to cont
if __salt__['postgres.tablespace_alter'](name,
set_option={k: v}):
ret['comment'] = 'Tablespace {0} opts changed'.format(name)
dictupdate.update(ret['changes'], {name: {'options': {k: v}}})
ret['result'] = True
return ret | python | def present(name,
directory,
options=None,
owner=None,
user=None,
maintenance_db=None,
db_password=None,
db_host=None,
db_port=None,
db_user=None):
'''
Ensure that the named tablespace is present with the specified properties.
For more information about all of these options run ``man 7
create_tablespace``.
name
The name of the tablespace to create/manage.
directory
The directory where the tablespace will be located, must already exist
options
A dictionary of options to specify for the tablespace.
Currently, the only tablespace options supported are ``seq_page_cost``
and ``random_page_cost``. Default values are shown in the example below:
.. code-block:: yaml
my_space:
postgres_tablespace.present:
- directory: /srv/my_tablespace
- options:
seq_page_cost: 1.0
random_page_cost: 4.0
owner
The database user that will be the owner of the tablespace.
Defaults to the user executing the command (i.e. the `user` option)
user
System user all operations should be performed on behalf of
maintenance_db
Database to act on
db_user
Database username if different from config or default
db_password
User password if any password for a specified user
db_host
Database host if different from config or default
db_port
Database port if different from config or default
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': 'Tablespace {0} is already present'.format(name)}
dbargs = {
'maintenance_db': maintenance_db,
'runas': user,
'host': db_host,
'user': db_user,
'port': db_port,
'password': db_password,
}
tblspaces = __salt__['postgres.tablespace_list'](**dbargs)
if name not in tblspaces:
# not there, create it
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Tablespace {0} is set to be created'.format(name)
return ret
if __salt__['postgres.tablespace_create'](name, directory, options,
owner, **dbargs):
ret['comment'] = 'The tablespace {0} has been created'.format(name)
ret['changes'][name] = 'Present'
return ret
# already exists, make sure it's got the right config
if tblspaces[name]['Location'] != directory and not __opts__['test']:
ret['comment'] = """Tablespace {0} is not at the right location. This is
unfixable without dropping and recreating the tablespace.""".format(
name)
ret['result'] = False
return ret
if owner and not tblspaces[name]['Owner'] == owner:
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Tablespace {0} owner to be altered'.format(name)
if (__salt__['postgres.tablespace_alter'](name, new_owner=owner)
and not __opts__['test']):
ret['comment'] = 'Tablespace {0} owner changed'.format(name)
ret['changes'][name] = {'owner': owner}
ret['result'] = True
if options:
# options comes from postgres as a sort of json(ish) string, but it
# can't really be parsed out, but it's in a fairly consistent format
# that we should be able to string check:
# {seq_page_cost=1.1,random_page_cost=3.9}
# TODO remove options that exist if possible
for k, v in iteritems(options):
# if 'seq_page_cost=1.1' not in '{seq_page_cost=1.1,...}'
if '{0}={1}'.format(k, v) not in tblspaces[name]['Opts']:
if __opts__['test']:
ret['result'] = None
ret['comment'] = """Tablespace {0} options to be
altered""".format(name)
break # we know it's going to be altered, no reason to cont
if __salt__['postgres.tablespace_alter'](name,
set_option={k: v}):
ret['comment'] = 'Tablespace {0} opts changed'.format(name)
dictupdate.update(ret['changes'], {name: {'options': {k: v}}})
ret['result'] = True
return ret | [
"def",
"present",
"(",
"name",
",",
"directory",
",",
"options",
"=",
"None",
",",
"owner",
"=",
"None",
",",
"user",
"=",
"None",
",",
"maintenance_db",
"=",
"None",
",",
"db_password",
"=",
"None",
",",
"db_host",
"=",
"None",
",",
"db_port",
"=",
... | Ensure that the named tablespace is present with the specified properties.
For more information about all of these options run ``man 7
create_tablespace``.
name
The name of the tablespace to create/manage.
directory
The directory where the tablespace will be located, must already exist
options
A dictionary of options to specify for the tablespace.
Currently, the only tablespace options supported are ``seq_page_cost``
and ``random_page_cost``. Default values are shown in the example below:
.. code-block:: yaml
my_space:
postgres_tablespace.present:
- directory: /srv/my_tablespace
- options:
seq_page_cost: 1.0
random_page_cost: 4.0
owner
The database user that will be the owner of the tablespace.
Defaults to the user executing the command (i.e. the `user` option)
user
System user all operations should be performed on behalf of
maintenance_db
Database to act on
db_user
Database username if different from config or default
db_password
User password if any password for a specified user
db_host
Database host if different from config or default
db_port
Database port if different from config or default | [
"Ensure",
"that",
"the",
"named",
"tablespace",
"is",
"present",
"with",
"the",
"specified",
"properties",
".",
"For",
"more",
"information",
"about",
"all",
"of",
"these",
"options",
"run",
"man",
"7",
"create_tablespace",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/postgres_tablespace.py#L38-L158 | train |
saltstack/salt | salt/pillar/sqlcipher.py | ext_pillar | def ext_pillar(minion_id,
pillar,
*args,
**kwargs):
'''
Execute queries against SQLCipher, merge and return as a dict
'''
return SQLCipherExtPillar().fetch(minion_id, pillar, *args, **kwargs) | python | def ext_pillar(minion_id,
pillar,
*args,
**kwargs):
'''
Execute queries against SQLCipher, merge and return as a dict
'''
return SQLCipherExtPillar().fetch(minion_id, pillar, *args, **kwargs) | [
"def",
"ext_pillar",
"(",
"minion_id",
",",
"pillar",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"SQLCipherExtPillar",
"(",
")",
".",
"fetch",
"(",
"minion_id",
",",
"pillar",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Execute queries against SQLCipher, merge and return as a dict | [
"Execute",
"queries",
"against",
"SQLCipher",
"merge",
"and",
"return",
"as",
"a",
"dict"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/sqlcipher.py#L130-L137 | train |
saltstack/salt | salt/pillar/sqlcipher.py | SQLCipherExtPillar._get_cursor | def _get_cursor(self):
'''
Yield a SQLCipher cursor
'''
_options = self._get_options()
conn = sqlcipher.connect(_options.get('database'),
timeout=float(_options.get('timeout')))
conn.execute('pragma key="{0}"'.format(_options.get('pass')))
cursor = conn.cursor()
try:
yield cursor
except sqlcipher.Error as err:
log.exception('Error in ext_pillar SQLCipher: %s', err.args)
finally:
conn.close() | python | def _get_cursor(self):
'''
Yield a SQLCipher cursor
'''
_options = self._get_options()
conn = sqlcipher.connect(_options.get('database'),
timeout=float(_options.get('timeout')))
conn.execute('pragma key="{0}"'.format(_options.get('pass')))
cursor = conn.cursor()
try:
yield cursor
except sqlcipher.Error as err:
log.exception('Error in ext_pillar SQLCipher: %s', err.args)
finally:
conn.close() | [
"def",
"_get_cursor",
"(",
"self",
")",
":",
"_options",
"=",
"self",
".",
"_get_options",
"(",
")",
"conn",
"=",
"sqlcipher",
".",
"connect",
"(",
"_options",
".",
"get",
"(",
"'database'",
")",
",",
"timeout",
"=",
"float",
"(",
"_options",
".",
"get... | Yield a SQLCipher cursor | [
"Yield",
"a",
"SQLCipher",
"cursor"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/sqlcipher.py#L113-L127 | train |
saltstack/salt | salt/modules/ldap3.py | _convert_exception | def _convert_exception(e):
'''Convert an ldap backend exception to an LDAPError and raise it.'''
args = ('exception in ldap backend: {0}'.format(repr(e)), e)
if six.PY2:
six.reraise(LDAPError, args, sys.exc_info()[2])
else:
six.raise_from(LDAPError(*args), e) | python | def _convert_exception(e):
'''Convert an ldap backend exception to an LDAPError and raise it.'''
args = ('exception in ldap backend: {0}'.format(repr(e)), e)
if six.PY2:
six.reraise(LDAPError, args, sys.exc_info()[2])
else:
six.raise_from(LDAPError(*args), e) | [
"def",
"_convert_exception",
"(",
"e",
")",
":",
"args",
"=",
"(",
"'exception in ldap backend: {0}'",
".",
"format",
"(",
"repr",
"(",
"e",
")",
")",
",",
"e",
")",
"if",
"six",
".",
"PY2",
":",
"six",
".",
"reraise",
"(",
"LDAPError",
",",
"args",
... | Convert an ldap backend exception to an LDAPError and raise it. | [
"Convert",
"an",
"ldap",
"backend",
"exception",
"to",
"an",
"LDAPError",
"and",
"raise",
"it",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ldap3.py#L53-L59 | train |
saltstack/salt | salt/modules/ldap3.py | _bind | def _bind(l, bind=None):
'''Bind helper.'''
if bind is None:
return
method = bind.get('method', 'simple')
if method is None:
return
elif method == 'simple':
l.simple_bind_s(bind.get('dn', ''), bind.get('password', ''))
elif method == 'sasl':
sasl_class = getattr(ldap.sasl,
bind.get('mechanism', 'EXTERNAL').lower())
creds = bind.get('credentials', None)
if creds is None:
creds = {}
auth = sasl_class(*creds.get('args', []), **creds.get('kwargs', {}))
l.sasl_interactive_bind_s(bind.get('dn', ''), auth)
else:
raise ValueError('unsupported bind method "' + method
+ '"; supported bind methods: simple sasl') | python | def _bind(l, bind=None):
'''Bind helper.'''
if bind is None:
return
method = bind.get('method', 'simple')
if method is None:
return
elif method == 'simple':
l.simple_bind_s(bind.get('dn', ''), bind.get('password', ''))
elif method == 'sasl':
sasl_class = getattr(ldap.sasl,
bind.get('mechanism', 'EXTERNAL').lower())
creds = bind.get('credentials', None)
if creds is None:
creds = {}
auth = sasl_class(*creds.get('args', []), **creds.get('kwargs', {}))
l.sasl_interactive_bind_s(bind.get('dn', ''), auth)
else:
raise ValueError('unsupported bind method "' + method
+ '"; supported bind methods: simple sasl') | [
"def",
"_bind",
"(",
"l",
",",
"bind",
"=",
"None",
")",
":",
"if",
"bind",
"is",
"None",
":",
"return",
"method",
"=",
"bind",
".",
"get",
"(",
"'method'",
",",
"'simple'",
")",
"if",
"method",
"is",
"None",
":",
"return",
"elif",
"method",
"==",
... | Bind helper. | [
"Bind",
"helper",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ldap3.py#L62-L81 | train |
saltstack/salt | salt/modules/ldap3.py | connect | def connect(connect_spec=None):
'''Connect and optionally bind to an LDAP server.
:param connect_spec:
This can be an LDAP connection object returned by a previous
call to :py:func:`connect` (in which case the argument is
simply returned), ``None`` (in which case an empty dict is
used), or a dict with the following keys:
* ``'backend'``
Optional; default depends on which Python LDAP modules are
installed. Name of the Python LDAP module to use. Only
``'ldap'`` is supported at the moment.
* ``'url'``
Optional; defaults to ``'ldapi:///'``. URL to the LDAP
server.
* ``'bind'``
Optional; defaults to ``None``. Describes how to bind an
identity to the LDAP connection. If ``None``, an
anonymous connection is made. Valid keys:
* ``'method'``
Optional; defaults to ``None``. The authentication
method to use. Valid values include but are not
necessarily limited to ``'simple'``, ``'sasl'``, and
``None``. If ``None``, an anonymous connection is
made. Available methods depend on the chosen backend.
* ``'mechanism'``
Optional; defaults to ``'EXTERNAL'``. The SASL
mechanism to use. Ignored unless the method is
``'sasl'``. Available methods depend on the chosen
backend and the server's capabilities.
* ``'credentials'``
Optional; defaults to ``None``. An object specific to
the chosen SASL mechanism and backend that represents
the authentication credentials. Ignored unless the
method is ``'sasl'``.
For the ``'ldap'`` backend, this is a dictionary. If
``None``, an empty dict is used. Keys:
* ``'args'``
Optional; defaults to an empty list. A list of
arguments to pass to the SASL mechanism
constructor. See the SASL mechanism constructor
documentation in the ``ldap.sasl`` Python module.
* ``'kwargs'``
Optional; defaults to an empty dict. A dict of
keyword arguments to pass to the SASL mechanism
constructor. See the SASL mechanism constructor
documentation in the ``ldap.sasl`` Python module.
* ``'dn'``
Optional; defaults to an empty string. The
distinguished name to bind.
* ``'password'``
Optional; defaults to an empty string. Password for
binding. Ignored if the method is ``'sasl'``.
* ``'tls'``
Optional; defaults to ``None``. A backend-specific object
containing settings to override default TLS behavior.
For the ``'ldap'`` backend, this is a dictionary. Not all
settings in this dictionary are supported by all versions
of ``python-ldap`` or the underlying TLS library. If
``None``, an empty dict is used. Possible keys:
* ``'starttls'``
If present, initiate a TLS connection using StartTLS.
(The value associated with this key is ignored.)
* ``'cacertdir'``
Set the path of the directory containing CA
certificates.
* ``'cacertfile'``
Set the pathname of the CA certificate file.
* ``'certfile'``
Set the pathname of the certificate file.
* ``'cipher_suite'``
Set the allowed cipher suite.
* ``'crlcheck'``
Set the CRL evaluation strategy. Valid values are
``'none'``, ``'peer'``, and ``'all'``.
* ``'crlfile'``
Set the pathname of the CRL file.
* ``'dhfile'``
Set the pathname of the file containing the parameters
for Diffie-Hellman ephemeral key exchange.
* ``'keyfile'``
Set the pathname of the certificate key file.
* ``'newctx'``
If present, instruct the underlying TLS library to
create a new TLS context. (The value associated with
this key is ignored.)
* ``'protocol_min'``
Set the minimum protocol version.
* ``'random_file'``
Set the pathname of the random file when
``/dev/random`` and ``/dev/urandom`` are not
available.
* ``'require_cert'``
Set the certificate validation policy. Valid values
are ``'never'``, ``'hard'``, ``'demand'``,
``'allow'``, and ``'try'``.
* ``'opts'``
Optional; defaults to ``None``. A backend-specific object
containing options for the backend.
For the ``'ldap'`` backend, this is a dictionary of
OpenLDAP options to set. If ``None``, an empty dict is
used. Each key is a the name of an OpenLDAP option
constant without the ``'LDAP_OPT_'`` prefix, then
converted to lower case.
:returns:
an object representing an LDAP connection that can be used as
the ``connect_spec`` argument to any of the functions in this
module (to avoid the overhead of making and terminating
multiple connections).
This object should be used as a context manager. It is safe
to nest ``with`` statements.
CLI example:
.. code-block:: bash
salt '*' ldap3.connect "{
'url': 'ldaps://ldap.example.com/',
'bind': {
'method': 'simple',
'dn': 'cn=admin,dc=example,dc=com',
'password': 'secret'}
}"
'''
if isinstance(connect_spec, _connect_ctx):
return connect_spec
if connect_spec is None:
connect_spec = {}
backend_name = connect_spec.get('backend', 'ldap')
if backend_name not in available_backends:
raise ValueError('unsupported backend or required Python module'
+ ' unavailable: {0}'.format(backend_name))
url = connect_spec.get('url', 'ldapi:///')
try:
l = ldap.initialize(url)
l.protocol_version = ldap.VERSION3
# set up tls
tls = connect_spec.get('tls', None)
if tls is None:
tls = {}
vars = {}
for k, v in six.iteritems(tls):
if k in ('starttls', 'newctx'):
vars[k] = True
elif k in ('crlcheck', 'require_cert'):
l.set_option(getattr(ldap, 'OPT_X_TLS_' + k.upper()),
getattr(ldap, 'OPT_X_TLS_' + v.upper()))
else:
l.set_option(getattr(ldap, 'OPT_X_TLS_' + k.upper()), v)
if vars.get('starttls', False):
l.start_tls_s()
if vars.get('newctx', False):
l.set_option(ldap.OPT_X_TLS_NEWCTX, 0)
# set up other options
l.set_option(ldap.OPT_REFERRALS, 0)
opts = connect_spec.get('opts', None)
if opts is None:
opts = {}
for k, v in six.iteritems(opts):
opt = getattr(ldap, 'OPT_' + k.upper())
l.set_option(opt, v)
_bind(l, connect_spec.get('bind', None))
except ldap.LDAPError as e:
_convert_exception(e)
return _connect_ctx(l) | python | def connect(connect_spec=None):
'''Connect and optionally bind to an LDAP server.
:param connect_spec:
This can be an LDAP connection object returned by a previous
call to :py:func:`connect` (in which case the argument is
simply returned), ``None`` (in which case an empty dict is
used), or a dict with the following keys:
* ``'backend'``
Optional; default depends on which Python LDAP modules are
installed. Name of the Python LDAP module to use. Only
``'ldap'`` is supported at the moment.
* ``'url'``
Optional; defaults to ``'ldapi:///'``. URL to the LDAP
server.
* ``'bind'``
Optional; defaults to ``None``. Describes how to bind an
identity to the LDAP connection. If ``None``, an
anonymous connection is made. Valid keys:
* ``'method'``
Optional; defaults to ``None``. The authentication
method to use. Valid values include but are not
necessarily limited to ``'simple'``, ``'sasl'``, and
``None``. If ``None``, an anonymous connection is
made. Available methods depend on the chosen backend.
* ``'mechanism'``
Optional; defaults to ``'EXTERNAL'``. The SASL
mechanism to use. Ignored unless the method is
``'sasl'``. Available methods depend on the chosen
backend and the server's capabilities.
* ``'credentials'``
Optional; defaults to ``None``. An object specific to
the chosen SASL mechanism and backend that represents
the authentication credentials. Ignored unless the
method is ``'sasl'``.
For the ``'ldap'`` backend, this is a dictionary. If
``None``, an empty dict is used. Keys:
* ``'args'``
Optional; defaults to an empty list. A list of
arguments to pass to the SASL mechanism
constructor. See the SASL mechanism constructor
documentation in the ``ldap.sasl`` Python module.
* ``'kwargs'``
Optional; defaults to an empty dict. A dict of
keyword arguments to pass to the SASL mechanism
constructor. See the SASL mechanism constructor
documentation in the ``ldap.sasl`` Python module.
* ``'dn'``
Optional; defaults to an empty string. The
distinguished name to bind.
* ``'password'``
Optional; defaults to an empty string. Password for
binding. Ignored if the method is ``'sasl'``.
* ``'tls'``
Optional; defaults to ``None``. A backend-specific object
containing settings to override default TLS behavior.
For the ``'ldap'`` backend, this is a dictionary. Not all
settings in this dictionary are supported by all versions
of ``python-ldap`` or the underlying TLS library. If
``None``, an empty dict is used. Possible keys:
* ``'starttls'``
If present, initiate a TLS connection using StartTLS.
(The value associated with this key is ignored.)
* ``'cacertdir'``
Set the path of the directory containing CA
certificates.
* ``'cacertfile'``
Set the pathname of the CA certificate file.
* ``'certfile'``
Set the pathname of the certificate file.
* ``'cipher_suite'``
Set the allowed cipher suite.
* ``'crlcheck'``
Set the CRL evaluation strategy. Valid values are
``'none'``, ``'peer'``, and ``'all'``.
* ``'crlfile'``
Set the pathname of the CRL file.
* ``'dhfile'``
Set the pathname of the file containing the parameters
for Diffie-Hellman ephemeral key exchange.
* ``'keyfile'``
Set the pathname of the certificate key file.
* ``'newctx'``
If present, instruct the underlying TLS library to
create a new TLS context. (The value associated with
this key is ignored.)
* ``'protocol_min'``
Set the minimum protocol version.
* ``'random_file'``
Set the pathname of the random file when
``/dev/random`` and ``/dev/urandom`` are not
available.
* ``'require_cert'``
Set the certificate validation policy. Valid values
are ``'never'``, ``'hard'``, ``'demand'``,
``'allow'``, and ``'try'``.
* ``'opts'``
Optional; defaults to ``None``. A backend-specific object
containing options for the backend.
For the ``'ldap'`` backend, this is a dictionary of
OpenLDAP options to set. If ``None``, an empty dict is
used. Each key is a the name of an OpenLDAP option
constant without the ``'LDAP_OPT_'`` prefix, then
converted to lower case.
:returns:
an object representing an LDAP connection that can be used as
the ``connect_spec`` argument to any of the functions in this
module (to avoid the overhead of making and terminating
multiple connections).
This object should be used as a context manager. It is safe
to nest ``with`` statements.
CLI example:
.. code-block:: bash
salt '*' ldap3.connect "{
'url': 'ldaps://ldap.example.com/',
'bind': {
'method': 'simple',
'dn': 'cn=admin,dc=example,dc=com',
'password': 'secret'}
}"
'''
if isinstance(connect_spec, _connect_ctx):
return connect_spec
if connect_spec is None:
connect_spec = {}
backend_name = connect_spec.get('backend', 'ldap')
if backend_name not in available_backends:
raise ValueError('unsupported backend or required Python module'
+ ' unavailable: {0}'.format(backend_name))
url = connect_spec.get('url', 'ldapi:///')
try:
l = ldap.initialize(url)
l.protocol_version = ldap.VERSION3
# set up tls
tls = connect_spec.get('tls', None)
if tls is None:
tls = {}
vars = {}
for k, v in six.iteritems(tls):
if k in ('starttls', 'newctx'):
vars[k] = True
elif k in ('crlcheck', 'require_cert'):
l.set_option(getattr(ldap, 'OPT_X_TLS_' + k.upper()),
getattr(ldap, 'OPT_X_TLS_' + v.upper()))
else:
l.set_option(getattr(ldap, 'OPT_X_TLS_' + k.upper()), v)
if vars.get('starttls', False):
l.start_tls_s()
if vars.get('newctx', False):
l.set_option(ldap.OPT_X_TLS_NEWCTX, 0)
# set up other options
l.set_option(ldap.OPT_REFERRALS, 0)
opts = connect_spec.get('opts', None)
if opts is None:
opts = {}
for k, v in six.iteritems(opts):
opt = getattr(ldap, 'OPT_' + k.upper())
l.set_option(opt, v)
_bind(l, connect_spec.get('bind', None))
except ldap.LDAPError as e:
_convert_exception(e)
return _connect_ctx(l) | [
"def",
"connect",
"(",
"connect_spec",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"connect_spec",
",",
"_connect_ctx",
")",
":",
"return",
"connect_spec",
"if",
"connect_spec",
"is",
"None",
":",
"connect_spec",
"=",
"{",
"}",
"backend_name",
"=",
"conn... | Connect and optionally bind to an LDAP server.
:param connect_spec:
This can be an LDAP connection object returned by a previous
call to :py:func:`connect` (in which case the argument is
simply returned), ``None`` (in which case an empty dict is
used), or a dict with the following keys:
* ``'backend'``
Optional; default depends on which Python LDAP modules are
installed. Name of the Python LDAP module to use. Only
``'ldap'`` is supported at the moment.
* ``'url'``
Optional; defaults to ``'ldapi:///'``. URL to the LDAP
server.
* ``'bind'``
Optional; defaults to ``None``. Describes how to bind an
identity to the LDAP connection. If ``None``, an
anonymous connection is made. Valid keys:
* ``'method'``
Optional; defaults to ``None``. The authentication
method to use. Valid values include but are not
necessarily limited to ``'simple'``, ``'sasl'``, and
``None``. If ``None``, an anonymous connection is
made. Available methods depend on the chosen backend.
* ``'mechanism'``
Optional; defaults to ``'EXTERNAL'``. The SASL
mechanism to use. Ignored unless the method is
``'sasl'``. Available methods depend on the chosen
backend and the server's capabilities.
* ``'credentials'``
Optional; defaults to ``None``. An object specific to
the chosen SASL mechanism and backend that represents
the authentication credentials. Ignored unless the
method is ``'sasl'``.
For the ``'ldap'`` backend, this is a dictionary. If
``None``, an empty dict is used. Keys:
* ``'args'``
Optional; defaults to an empty list. A list of
arguments to pass to the SASL mechanism
constructor. See the SASL mechanism constructor
documentation in the ``ldap.sasl`` Python module.
* ``'kwargs'``
Optional; defaults to an empty dict. A dict of
keyword arguments to pass to the SASL mechanism
constructor. See the SASL mechanism constructor
documentation in the ``ldap.sasl`` Python module.
* ``'dn'``
Optional; defaults to an empty string. The
distinguished name to bind.
* ``'password'``
Optional; defaults to an empty string. Password for
binding. Ignored if the method is ``'sasl'``.
* ``'tls'``
Optional; defaults to ``None``. A backend-specific object
containing settings to override default TLS behavior.
For the ``'ldap'`` backend, this is a dictionary. Not all
settings in this dictionary are supported by all versions
of ``python-ldap`` or the underlying TLS library. If
``None``, an empty dict is used. Possible keys:
* ``'starttls'``
If present, initiate a TLS connection using StartTLS.
(The value associated with this key is ignored.)
* ``'cacertdir'``
Set the path of the directory containing CA
certificates.
* ``'cacertfile'``
Set the pathname of the CA certificate file.
* ``'certfile'``
Set the pathname of the certificate file.
* ``'cipher_suite'``
Set the allowed cipher suite.
* ``'crlcheck'``
Set the CRL evaluation strategy. Valid values are
``'none'``, ``'peer'``, and ``'all'``.
* ``'crlfile'``
Set the pathname of the CRL file.
* ``'dhfile'``
Set the pathname of the file containing the parameters
for Diffie-Hellman ephemeral key exchange.
* ``'keyfile'``
Set the pathname of the certificate key file.
* ``'newctx'``
If present, instruct the underlying TLS library to
create a new TLS context. (The value associated with
this key is ignored.)
* ``'protocol_min'``
Set the minimum protocol version.
* ``'random_file'``
Set the pathname of the random file when
``/dev/random`` and ``/dev/urandom`` are not
available.
* ``'require_cert'``
Set the certificate validation policy. Valid values
are ``'never'``, ``'hard'``, ``'demand'``,
``'allow'``, and ``'try'``.
* ``'opts'``
Optional; defaults to ``None``. A backend-specific object
containing options for the backend.
For the ``'ldap'`` backend, this is a dictionary of
OpenLDAP options to set. If ``None``, an empty dict is
used. Each key is a the name of an OpenLDAP option
constant without the ``'LDAP_OPT_'`` prefix, then
converted to lower case.
:returns:
an object representing an LDAP connection that can be used as
the ``connect_spec`` argument to any of the functions in this
module (to avoid the overhead of making and terminating
multiple connections).
This object should be used as a context manager. It is safe
to nest ``with`` statements.
CLI example:
.. code-block:: bash
salt '*' ldap3.connect "{
'url': 'ldaps://ldap.example.com/',
'bind': {
'method': 'simple',
'dn': 'cn=admin,dc=example,dc=com',
'password': 'secret'}
}" | [
"Connect",
"and",
"optionally",
"bind",
"to",
"an",
"LDAP",
"server",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ldap3.py#L109-L306 | train |
saltstack/salt | salt/modules/ldap3.py | search | def search(connect_spec, base, scope='subtree', filterstr='(objectClass=*)',
attrlist=None, attrsonly=0):
'''Search an LDAP database.
:param connect_spec:
See the documentation for the ``connect_spec`` parameter for
:py:func:`connect`.
:param base:
Distinguished name of the entry at which to start the search.
:param scope:
One of the following:
* ``'subtree'``
Search the base and all of its descendants.
* ``'base'``
Search only the base itself.
* ``'onelevel'``
Search only the base's immediate children.
:param filterstr:
String representation of the filter to apply in the search.
:param attrlist:
Limit the returned attributes to those in the specified list.
If ``None``, all attributes of each entry are returned.
:param attrsonly:
If non-zero, don't return any attribute values.
:returns:
a dict of results. The dict is empty if there are no results.
The dict maps each returned entry's distinguished name to a
dict that maps each of the matching attribute names to a list
of its values.
CLI example:
.. code-block:: bash
salt '*' ldap3.search "{
'url': 'ldaps://ldap.example.com/',
'bind': {
'method': 'simple',
'dn': 'cn=admin,dc=example,dc=com',
'password': 'secret',
},
}" "base='dc=example,dc=com'"
'''
l = connect(connect_spec)
scope = getattr(ldap, 'SCOPE_' + scope.upper())
try:
results = l.c.search_s(base, scope, filterstr, attrlist, attrsonly)
except ldap.NO_SUCH_OBJECT:
results = []
except ldap.LDAPError as e:
_convert_exception(e)
return dict(results) | python | def search(connect_spec, base, scope='subtree', filterstr='(objectClass=*)',
attrlist=None, attrsonly=0):
'''Search an LDAP database.
:param connect_spec:
See the documentation for the ``connect_spec`` parameter for
:py:func:`connect`.
:param base:
Distinguished name of the entry at which to start the search.
:param scope:
One of the following:
* ``'subtree'``
Search the base and all of its descendants.
* ``'base'``
Search only the base itself.
* ``'onelevel'``
Search only the base's immediate children.
:param filterstr:
String representation of the filter to apply in the search.
:param attrlist:
Limit the returned attributes to those in the specified list.
If ``None``, all attributes of each entry are returned.
:param attrsonly:
If non-zero, don't return any attribute values.
:returns:
a dict of results. The dict is empty if there are no results.
The dict maps each returned entry's distinguished name to a
dict that maps each of the matching attribute names to a list
of its values.
CLI example:
.. code-block:: bash
salt '*' ldap3.search "{
'url': 'ldaps://ldap.example.com/',
'bind': {
'method': 'simple',
'dn': 'cn=admin,dc=example,dc=com',
'password': 'secret',
},
}" "base='dc=example,dc=com'"
'''
l = connect(connect_spec)
scope = getattr(ldap, 'SCOPE_' + scope.upper())
try:
results = l.c.search_s(base, scope, filterstr, attrlist, attrsonly)
except ldap.NO_SUCH_OBJECT:
results = []
except ldap.LDAPError as e:
_convert_exception(e)
return dict(results) | [
"def",
"search",
"(",
"connect_spec",
",",
"base",
",",
"scope",
"=",
"'subtree'",
",",
"filterstr",
"=",
"'(objectClass=*)'",
",",
"attrlist",
"=",
"None",
",",
"attrsonly",
"=",
"0",
")",
":",
"l",
"=",
"connect",
"(",
"connect_spec",
")",
"scope",
"="... | Search an LDAP database.
:param connect_spec:
See the documentation for the ``connect_spec`` parameter for
:py:func:`connect`.
:param base:
Distinguished name of the entry at which to start the search.
:param scope:
One of the following:
* ``'subtree'``
Search the base and all of its descendants.
* ``'base'``
Search only the base itself.
* ``'onelevel'``
Search only the base's immediate children.
:param filterstr:
String representation of the filter to apply in the search.
:param attrlist:
Limit the returned attributes to those in the specified list.
If ``None``, all attributes of each entry are returned.
:param attrsonly:
If non-zero, don't return any attribute values.
:returns:
a dict of results. The dict is empty if there are no results.
The dict maps each returned entry's distinguished name to a
dict that maps each of the matching attribute names to a list
of its values.
CLI example:
.. code-block:: bash
salt '*' ldap3.search "{
'url': 'ldaps://ldap.example.com/',
'bind': {
'method': 'simple',
'dn': 'cn=admin,dc=example,dc=com',
'password': 'secret',
},
}" "base='dc=example,dc=com'" | [
"Search",
"an",
"LDAP",
"database",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ldap3.py#L309-L369 | train |
saltstack/salt | salt/modules/ldap3.py | add | def add(connect_spec, dn, attributes):
'''Add an entry to an LDAP database.
:param connect_spec:
See the documentation for the ``connect_spec`` parameter for
:py:func:`connect`.
:param dn:
Distinguished name of the entry.
:param attributes:
Non-empty dict mapping each of the new entry's attributes to a
non-empty iterable of values.
:returns:
``True`` if successful, raises an exception otherwise.
CLI example:
.. code-block:: bash
salt '*' ldap3.add "{
'url': 'ldaps://ldap.example.com/',
'bind': {
'method': 'simple',
'password': 'secret',
},
}" "dn='dc=example,dc=com'" "attributes={'example': 'values'}"
'''
l = connect(connect_spec)
# convert the "iterable of values" to lists in case that's what
# addModlist() expects (also to ensure that the caller's objects
# are not modified)
attributes = dict(((attr, salt.utils.data.encode(list(vals)))
for attr, vals in six.iteritems(attributes)))
log.info('adding entry: dn: %s attributes: %s', repr(dn), repr(attributes))
if 'unicodePwd' in attributes:
attributes['unicodePwd'] = [_format_unicode_password(x) for x in attributes['unicodePwd']]
modlist = ldap.modlist.addModlist(attributes),
try:
l.c.add_s(dn, modlist)
except ldap.LDAPError as e:
_convert_exception(e)
return True | python | def add(connect_spec, dn, attributes):
'''Add an entry to an LDAP database.
:param connect_spec:
See the documentation for the ``connect_spec`` parameter for
:py:func:`connect`.
:param dn:
Distinguished name of the entry.
:param attributes:
Non-empty dict mapping each of the new entry's attributes to a
non-empty iterable of values.
:returns:
``True`` if successful, raises an exception otherwise.
CLI example:
.. code-block:: bash
salt '*' ldap3.add "{
'url': 'ldaps://ldap.example.com/',
'bind': {
'method': 'simple',
'password': 'secret',
},
}" "dn='dc=example,dc=com'" "attributes={'example': 'values'}"
'''
l = connect(connect_spec)
# convert the "iterable of values" to lists in case that's what
# addModlist() expects (also to ensure that the caller's objects
# are not modified)
attributes = dict(((attr, salt.utils.data.encode(list(vals)))
for attr, vals in six.iteritems(attributes)))
log.info('adding entry: dn: %s attributes: %s', repr(dn), repr(attributes))
if 'unicodePwd' in attributes:
attributes['unicodePwd'] = [_format_unicode_password(x) for x in attributes['unicodePwd']]
modlist = ldap.modlist.addModlist(attributes),
try:
l.c.add_s(dn, modlist)
except ldap.LDAPError as e:
_convert_exception(e)
return True | [
"def",
"add",
"(",
"connect_spec",
",",
"dn",
",",
"attributes",
")",
":",
"l",
"=",
"connect",
"(",
"connect_spec",
")",
"# convert the \"iterable of values\" to lists in case that's what",
"# addModlist() expects (also to ensure that the caller's objects",
"# are not modified)"... | Add an entry to an LDAP database.
:param connect_spec:
See the documentation for the ``connect_spec`` parameter for
:py:func:`connect`.
:param dn:
Distinguished name of the entry.
:param attributes:
Non-empty dict mapping each of the new entry's attributes to a
non-empty iterable of values.
:returns:
``True`` if successful, raises an exception otherwise.
CLI example:
.. code-block:: bash
salt '*' ldap3.add "{
'url': 'ldaps://ldap.example.com/',
'bind': {
'method': 'simple',
'password': 'secret',
},
}" "dn='dc=example,dc=com'" "attributes={'example': 'values'}" | [
"Add",
"an",
"entry",
"to",
"an",
"LDAP",
"database",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ldap3.py#L372-L417 | train |
saltstack/salt | salt/modules/ldap3.py | delete | def delete(connect_spec, dn):
'''Delete an entry from an LDAP database.
:param connect_spec:
See the documentation for the ``connect_spec`` parameter for
:py:func:`connect`.
:param dn:
Distinguished name of the entry.
:returns:
``True`` if successful, raises an exception otherwise.
CLI example:
.. code-block:: bash
salt '*' ldap3.delete "{
'url': 'ldaps://ldap.example.com/',
'bind': {
'method': 'simple',
'password': 'secret'}
}" dn='cn=admin,dc=example,dc=com'
'''
l = connect(connect_spec)
log.info('deleting entry: dn: %s', repr(dn))
try:
l.c.delete_s(dn)
except ldap.LDAPError as e:
_convert_exception(e)
return True | python | def delete(connect_spec, dn):
'''Delete an entry from an LDAP database.
:param connect_spec:
See the documentation for the ``connect_spec`` parameter for
:py:func:`connect`.
:param dn:
Distinguished name of the entry.
:returns:
``True`` if successful, raises an exception otherwise.
CLI example:
.. code-block:: bash
salt '*' ldap3.delete "{
'url': 'ldaps://ldap.example.com/',
'bind': {
'method': 'simple',
'password': 'secret'}
}" dn='cn=admin,dc=example,dc=com'
'''
l = connect(connect_spec)
log.info('deleting entry: dn: %s', repr(dn))
try:
l.c.delete_s(dn)
except ldap.LDAPError as e:
_convert_exception(e)
return True | [
"def",
"delete",
"(",
"connect_spec",
",",
"dn",
")",
":",
"l",
"=",
"connect",
"(",
"connect_spec",
")",
"log",
".",
"info",
"(",
"'deleting entry: dn: %s'",
",",
"repr",
"(",
"dn",
")",
")",
"try",
":",
"l",
".",
"c",
".",
"delete_s",
"(",
"dn",
... | Delete an entry from an LDAP database.
:param connect_spec:
See the documentation for the ``connect_spec`` parameter for
:py:func:`connect`.
:param dn:
Distinguished name of the entry.
:returns:
``True`` if successful, raises an exception otherwise.
CLI example:
.. code-block:: bash
salt '*' ldap3.delete "{
'url': 'ldaps://ldap.example.com/',
'bind': {
'method': 'simple',
'password': 'secret'}
}" dn='cn=admin,dc=example,dc=com' | [
"Delete",
"an",
"entry",
"from",
"an",
"LDAP",
"database",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ldap3.py#L420-L450 | train |
saltstack/salt | salt/modules/ldap3.py | modify | def modify(connect_spec, dn, directives):
'''Modify an entry in an LDAP database.
:param connect_spec:
See the documentation for the ``connect_spec`` parameter for
:py:func:`connect`.
:param dn:
Distinguished name of the entry.
:param directives:
Iterable of directives that indicate how to modify the entry.
Each directive is a tuple of the form ``(op, attr, vals)``,
where:
* ``op`` identifies the modification operation to perform.
One of:
* ``'add'`` to add one or more values to the attribute
* ``'delete'`` to delete some or all of the values from the
attribute. If no values are specified with this
operation, all of the attribute's values are deleted.
Otherwise, only the named values are deleted.
* ``'replace'`` to replace all of the attribute's values
with zero or more new values
* ``attr`` names the attribute to modify
* ``vals`` is an iterable of values to add or delete
:returns:
``True`` if successful, raises an exception otherwise.
CLI example:
.. code-block:: bash
salt '*' ldap3.modify "{
'url': 'ldaps://ldap.example.com/',
'bind': {
'method': 'simple',
'password': 'secret'}
}" dn='cn=admin,dc=example,dc=com'
directives="('add', 'example', ['example_val'])"
'''
l = connect(connect_spec)
# convert the "iterable of values" to lists in case that's what
# modify_s() expects (also to ensure that the caller's objects are
# not modified)
modlist = [(getattr(ldap, 'MOD_' + op.upper()), attr, list(vals))
for op, attr, vals in directives]
for idx, mod in enumerate(modlist):
if mod[1] == 'unicodePwd':
modlist[idx] = (mod[0], mod[1],
[_format_unicode_password(x) for x in mod[2]])
modlist = salt.utils.data.decode(modlist, to_str=True, preserve_tuples=True)
try:
l.c.modify_s(dn, modlist)
except ldap.LDAPError as e:
_convert_exception(e)
return True | python | def modify(connect_spec, dn, directives):
'''Modify an entry in an LDAP database.
:param connect_spec:
See the documentation for the ``connect_spec`` parameter for
:py:func:`connect`.
:param dn:
Distinguished name of the entry.
:param directives:
Iterable of directives that indicate how to modify the entry.
Each directive is a tuple of the form ``(op, attr, vals)``,
where:
* ``op`` identifies the modification operation to perform.
One of:
* ``'add'`` to add one or more values to the attribute
* ``'delete'`` to delete some or all of the values from the
attribute. If no values are specified with this
operation, all of the attribute's values are deleted.
Otherwise, only the named values are deleted.
* ``'replace'`` to replace all of the attribute's values
with zero or more new values
* ``attr`` names the attribute to modify
* ``vals`` is an iterable of values to add or delete
:returns:
``True`` if successful, raises an exception otherwise.
CLI example:
.. code-block:: bash
salt '*' ldap3.modify "{
'url': 'ldaps://ldap.example.com/',
'bind': {
'method': 'simple',
'password': 'secret'}
}" dn='cn=admin,dc=example,dc=com'
directives="('add', 'example', ['example_val'])"
'''
l = connect(connect_spec)
# convert the "iterable of values" to lists in case that's what
# modify_s() expects (also to ensure that the caller's objects are
# not modified)
modlist = [(getattr(ldap, 'MOD_' + op.upper()), attr, list(vals))
for op, attr, vals in directives]
for idx, mod in enumerate(modlist):
if mod[1] == 'unicodePwd':
modlist[idx] = (mod[0], mod[1],
[_format_unicode_password(x) for x in mod[2]])
modlist = salt.utils.data.decode(modlist, to_str=True, preserve_tuples=True)
try:
l.c.modify_s(dn, modlist)
except ldap.LDAPError as e:
_convert_exception(e)
return True | [
"def",
"modify",
"(",
"connect_spec",
",",
"dn",
",",
"directives",
")",
":",
"l",
"=",
"connect",
"(",
"connect_spec",
")",
"# convert the \"iterable of values\" to lists in case that's what",
"# modify_s() expects (also to ensure that the caller's objects are",
"# not modified)... | Modify an entry in an LDAP database.
:param connect_spec:
See the documentation for the ``connect_spec`` parameter for
:py:func:`connect`.
:param dn:
Distinguished name of the entry.
:param directives:
Iterable of directives that indicate how to modify the entry.
Each directive is a tuple of the form ``(op, attr, vals)``,
where:
* ``op`` identifies the modification operation to perform.
One of:
* ``'add'`` to add one or more values to the attribute
* ``'delete'`` to delete some or all of the values from the
attribute. If no values are specified with this
operation, all of the attribute's values are deleted.
Otherwise, only the named values are deleted.
* ``'replace'`` to replace all of the attribute's values
with zero or more new values
* ``attr`` names the attribute to modify
* ``vals`` is an iterable of values to add or delete
:returns:
``True`` if successful, raises an exception otherwise.
CLI example:
.. code-block:: bash
salt '*' ldap3.modify "{
'url': 'ldaps://ldap.example.com/',
'bind': {
'method': 'simple',
'password': 'secret'}
}" dn='cn=admin,dc=example,dc=com'
directives="('add', 'example', ['example_val'])" | [
"Modify",
"an",
"entry",
"in",
"an",
"LDAP",
"database",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ldap3.py#L453-L517 | train |
saltstack/salt | salt/modules/ldap3.py | change | def change(connect_spec, dn, before, after):
'''Modify an entry in an LDAP database.
This does the same thing as :py:func:`modify`, but with a simpler
interface. Instead of taking a list of directives, it takes a
before and after view of an entry, determines the differences
between the two, computes the directives, and executes them.
Any attribute value present in ``before`` but missing in ``after``
is deleted. Any attribute value present in ``after`` but missing
in ``before`` is added. Any attribute value in the database that
is not mentioned in either ``before`` or ``after`` is not altered.
Any attribute value that is present in both ``before`` and
``after`` is ignored, regardless of whether that attribute value
exists in the database.
:param connect_spec:
See the documentation for the ``connect_spec`` parameter for
:py:func:`connect`.
:param dn:
Distinguished name of the entry.
:param before:
The expected state of the entry before modification. This is
a dict mapping each attribute name to an iterable of values.
:param after:
The desired state of the entry after modification. This is a
dict mapping each attribute name to an iterable of values.
:returns:
``True`` if successful, raises an exception otherwise.
CLI example:
.. code-block:: bash
salt '*' ldap3.change "{
'url': 'ldaps://ldap.example.com/',
'bind': {
'method': 'simple',
'password': 'secret'}
}" dn='cn=admin,dc=example,dc=com'
before="{'example_value': 'before_val'}"
after="{'example_value': 'after_val'}"
'''
l = connect(connect_spec)
# convert the "iterable of values" to lists in case that's what
# modifyModlist() expects (also to ensure that the caller's dicts
# are not modified)
before = dict(((attr, salt.utils.data.encode(list(vals)))
for attr, vals in six.iteritems(before)))
after = dict(((attr, salt.utils.data.encode(list(vals)))
for attr, vals in six.iteritems(after)))
if 'unicodePwd' in after:
after['unicodePwd'] = [_format_unicode_password(x) for x in after['unicodePwd']]
modlist = ldap.modlist.modifyModlist(before, after)
try:
l.c.modify_s(dn, modlist)
except ldap.LDAPError as e:
_convert_exception(e)
return True | python | def change(connect_spec, dn, before, after):
'''Modify an entry in an LDAP database.
This does the same thing as :py:func:`modify`, but with a simpler
interface. Instead of taking a list of directives, it takes a
before and after view of an entry, determines the differences
between the two, computes the directives, and executes them.
Any attribute value present in ``before`` but missing in ``after``
is deleted. Any attribute value present in ``after`` but missing
in ``before`` is added. Any attribute value in the database that
is not mentioned in either ``before`` or ``after`` is not altered.
Any attribute value that is present in both ``before`` and
``after`` is ignored, regardless of whether that attribute value
exists in the database.
:param connect_spec:
See the documentation for the ``connect_spec`` parameter for
:py:func:`connect`.
:param dn:
Distinguished name of the entry.
:param before:
The expected state of the entry before modification. This is
a dict mapping each attribute name to an iterable of values.
:param after:
The desired state of the entry after modification. This is a
dict mapping each attribute name to an iterable of values.
:returns:
``True`` if successful, raises an exception otherwise.
CLI example:
.. code-block:: bash
salt '*' ldap3.change "{
'url': 'ldaps://ldap.example.com/',
'bind': {
'method': 'simple',
'password': 'secret'}
}" dn='cn=admin,dc=example,dc=com'
before="{'example_value': 'before_val'}"
after="{'example_value': 'after_val'}"
'''
l = connect(connect_spec)
# convert the "iterable of values" to lists in case that's what
# modifyModlist() expects (also to ensure that the caller's dicts
# are not modified)
before = dict(((attr, salt.utils.data.encode(list(vals)))
for attr, vals in six.iteritems(before)))
after = dict(((attr, salt.utils.data.encode(list(vals)))
for attr, vals in six.iteritems(after)))
if 'unicodePwd' in after:
after['unicodePwd'] = [_format_unicode_password(x) for x in after['unicodePwd']]
modlist = ldap.modlist.modifyModlist(before, after)
try:
l.c.modify_s(dn, modlist)
except ldap.LDAPError as e:
_convert_exception(e)
return True | [
"def",
"change",
"(",
"connect_spec",
",",
"dn",
",",
"before",
",",
"after",
")",
":",
"l",
"=",
"connect",
"(",
"connect_spec",
")",
"# convert the \"iterable of values\" to lists in case that's what",
"# modifyModlist() expects (also to ensure that the caller's dicts",
"# ... | Modify an entry in an LDAP database.
This does the same thing as :py:func:`modify`, but with a simpler
interface. Instead of taking a list of directives, it takes a
before and after view of an entry, determines the differences
between the two, computes the directives, and executes them.
Any attribute value present in ``before`` but missing in ``after``
is deleted. Any attribute value present in ``after`` but missing
in ``before`` is added. Any attribute value in the database that
is not mentioned in either ``before`` or ``after`` is not altered.
Any attribute value that is present in both ``before`` and
``after`` is ignored, regardless of whether that attribute value
exists in the database.
:param connect_spec:
See the documentation for the ``connect_spec`` parameter for
:py:func:`connect`.
:param dn:
Distinguished name of the entry.
:param before:
The expected state of the entry before modification. This is
a dict mapping each attribute name to an iterable of values.
:param after:
The desired state of the entry after modification. This is a
dict mapping each attribute name to an iterable of values.
:returns:
``True`` if successful, raises an exception otherwise.
CLI example:
.. code-block:: bash
salt '*' ldap3.change "{
'url': 'ldaps://ldap.example.com/',
'bind': {
'method': 'simple',
'password': 'secret'}
}" dn='cn=admin,dc=example,dc=com'
before="{'example_value': 'before_val'}"
after="{'example_value': 'after_val'}" | [
"Modify",
"an",
"entry",
"in",
"an",
"LDAP",
"database",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ldap3.py#L520-L585 | train |
saltstack/salt | salt/states/grafana.py | _parse_profile | def _parse_profile(profile):
'''
From a pillar key, or a dictionary, return index and host keys.
'''
if isinstance(profile, string_types):
_profile = __salt__['config.option'](profile)
if not _profile:
msg = 'Pillar key for profile {0} not found.'.format(profile)
raise SaltInvocationError(msg)
else:
_profile = profile
hosts = _profile.get('hosts')
index = _profile.get('index')
return (hosts, index) | python | def _parse_profile(profile):
'''
From a pillar key, or a dictionary, return index and host keys.
'''
if isinstance(profile, string_types):
_profile = __salt__['config.option'](profile)
if not _profile:
msg = 'Pillar key for profile {0} not found.'.format(profile)
raise SaltInvocationError(msg)
else:
_profile = profile
hosts = _profile.get('hosts')
index = _profile.get('index')
return (hosts, index) | [
"def",
"_parse_profile",
"(",
"profile",
")",
":",
"if",
"isinstance",
"(",
"profile",
",",
"string_types",
")",
":",
"_profile",
"=",
"__salt__",
"[",
"'config.option'",
"]",
"(",
"profile",
")",
"if",
"not",
"_profile",
":",
"msg",
"=",
"'Pillar key for pr... | From a pillar key, or a dictionary, return index and host keys. | [
"From",
"a",
"pillar",
"key",
"or",
"a",
"dictionary",
"return",
"index",
"and",
"host",
"keys",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/grafana.py#L189-L202 | train |
saltstack/salt | salt/states/grafana.py | _rows_differ | def _rows_differ(row, _row):
'''
Check if grafana dashboard row and _row differ
'''
row_copy = copy.deepcopy(row)
_row_copy = copy.deepcopy(_row)
# Strip id from all panels in both rows, since they are always generated.
for panel in row_copy['panels']:
if 'id' in panel:
del panel['id']
for _panel in _row_copy['panels']:
if 'id' in _panel:
del _panel['id']
diff = DictDiffer(row_copy, _row_copy)
return diff.changed() or diff.added() or diff.removed() | python | def _rows_differ(row, _row):
'''
Check if grafana dashboard row and _row differ
'''
row_copy = copy.deepcopy(row)
_row_copy = copy.deepcopy(_row)
# Strip id from all panels in both rows, since they are always generated.
for panel in row_copy['panels']:
if 'id' in panel:
del panel['id']
for _panel in _row_copy['panels']:
if 'id' in _panel:
del _panel['id']
diff = DictDiffer(row_copy, _row_copy)
return diff.changed() or diff.added() or diff.removed() | [
"def",
"_rows_differ",
"(",
"row",
",",
"_row",
")",
":",
"row_copy",
"=",
"copy",
".",
"deepcopy",
"(",
"row",
")",
"_row_copy",
"=",
"copy",
".",
"deepcopy",
"(",
"_row",
")",
"# Strip id from all panels in both rows, since they are always generated.",
"for",
"p... | Check if grafana dashboard row and _row differ | [
"Check",
"if",
"grafana",
"dashboard",
"row",
"and",
"_row",
"differ"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/grafana.py#L205-L219 | train |
saltstack/salt | salt/states/grafana.py | dashboard_present | def dashboard_present(
name,
dashboard=None,
dashboard_from_pillar=None,
rows=None,
rows_from_pillar=None,
profile='grafana'):
'''
Ensure the grafana dashboard exists and is managed.
name
Name of the grafana dashboard.
dashboard
A dict that defines a dashboard that should be managed.
dashboard_from_pillar
A pillar key that contains a grafana dashboard dict. Mutually exclusive
with dashboard.
rows
A list of grafana rows.
rows_from_pillar
A list of pillar keys that contain lists of grafana dashboard rows.
Rows defined in the pillars will be appended to the rows defined in the
state.
profile
A pillar key or dict that contains a list of hosts and an
elasticsearch index to use.
'''
ret = {'name': name, 'result': None, 'comment': '', 'changes': {}}
if not profile:
raise SaltInvocationError('profile is a required argument.')
if dashboard and dashboard_from_pillar:
raise SaltInvocationError('dashboard and dashboard_from_pillar are'
' mutually exclusive arguments.')
hosts, index = _parse_profile(profile)
if not index:
raise SaltInvocationError('index is a required key in the profile.')
if not dashboard:
dashboard = __salt__['pillar.get'](dashboard_from_pillar)
if not rows:
rows = []
if rows_from_pillar:
for key in rows_from_pillar:
pillar_rows = __salt__['pillar.get'](key)
# Pillar contains a list of rows
if isinstance(pillar_rows, list):
for row in pillar_rows:
rows.append(row)
# Pillar contains a single row
else:
rows.append(pillar_rows)
exists = __salt__['elasticsearch.exists'](
index=index, id=name, doc_type='dashboard', hosts=hosts
)
if exists:
_dashboard = __salt__['elasticsearch.get'](
index=index, id=name, doc_type='dashboard', hosts=hosts
)
_dashboard = _dashboard.get('_source', {}).get('dashboard')
_dashboard = salt.utils.json.loads(_dashboard)
else:
if not dashboard:
raise SaltInvocationError('Grafana dashboard does not exist and no'
' dashboard template was provided.')
if __opts__['test']:
ret['comment'] = 'Dashboard {0} is set to be created.'.format(
name
)
ret['result'] = None
return ret
_dashboard = dashboard
update_rows = []
_ids = []
_data = {}
for _n, _row in enumerate(_dashboard['rows']):
# Collect the unique ids
for _panel in _row['panels']:
if 'id' in _panel:
_ids.append(_panel['id'])
# Collect all of the titles in the existing dashboard
if 'title' in _row:
_data[_row['title']] = _n
_ids.sort()
if not _ids:
_ids = [1]
for row in rows:
if 'title' not in row:
raise SaltInvocationError('title is a required key for rows.')
# Each panel needs to have a unique ID
for panel in row['panels']:
_ids.append(_ids[-1] + 1)
panel['id'] = _ids[-1]
title = row['title']
# If the title doesn't exist, we need to add this row
if title not in _data:
update_rows.append(title)
_dashboard['rows'].append(row)
continue
# For existing titles, replace the row if it differs
_n = _data[title]
if _rows_differ(row, _dashboard['rows'][_n]):
_dashboard['rows'][_n] = row
update_rows.append(title)
if not update_rows:
ret['result'] = True
ret['comment'] = 'Dashboard {0} is up to date'.format(name)
return ret
if __opts__['test']:
msg = 'Dashboard {0} is set to be updated.'.format(name)
if update_rows:
msg = '{0} The following rows set to be updated: {1}'.format(
msg, update_rows
)
ret['comment'] = msg
return ret
body = {
'user': 'guest',
'group': 'guest',
'title': name,
'dashboard': salt.utils.json.dumps(_dashboard)
}
updated = __salt__['elasticsearch.index'](
index=index, doc_type='dashboard', body=body, id=name,
hosts=hosts
)
if updated:
ret['result'] = True
ret['changes']['changed'] = name
msg = 'Updated dashboard {0}.'.format(name)
if update_rows:
msg = '{0} The following rows were updated: {1}'.format(
msg, update_rows
)
ret['comment'] = msg
else:
ret['result'] = False
msg = 'Failed to update dashboard {0}.'.format(name)
ret['comment'] = msg
return ret | python | def dashboard_present(
name,
dashboard=None,
dashboard_from_pillar=None,
rows=None,
rows_from_pillar=None,
profile='grafana'):
'''
Ensure the grafana dashboard exists and is managed.
name
Name of the grafana dashboard.
dashboard
A dict that defines a dashboard that should be managed.
dashboard_from_pillar
A pillar key that contains a grafana dashboard dict. Mutually exclusive
with dashboard.
rows
A list of grafana rows.
rows_from_pillar
A list of pillar keys that contain lists of grafana dashboard rows.
Rows defined in the pillars will be appended to the rows defined in the
state.
profile
A pillar key or dict that contains a list of hosts and an
elasticsearch index to use.
'''
ret = {'name': name, 'result': None, 'comment': '', 'changes': {}}
if not profile:
raise SaltInvocationError('profile is a required argument.')
if dashboard and dashboard_from_pillar:
raise SaltInvocationError('dashboard and dashboard_from_pillar are'
' mutually exclusive arguments.')
hosts, index = _parse_profile(profile)
if not index:
raise SaltInvocationError('index is a required key in the profile.')
if not dashboard:
dashboard = __salt__['pillar.get'](dashboard_from_pillar)
if not rows:
rows = []
if rows_from_pillar:
for key in rows_from_pillar:
pillar_rows = __salt__['pillar.get'](key)
# Pillar contains a list of rows
if isinstance(pillar_rows, list):
for row in pillar_rows:
rows.append(row)
# Pillar contains a single row
else:
rows.append(pillar_rows)
exists = __salt__['elasticsearch.exists'](
index=index, id=name, doc_type='dashboard', hosts=hosts
)
if exists:
_dashboard = __salt__['elasticsearch.get'](
index=index, id=name, doc_type='dashboard', hosts=hosts
)
_dashboard = _dashboard.get('_source', {}).get('dashboard')
_dashboard = salt.utils.json.loads(_dashboard)
else:
if not dashboard:
raise SaltInvocationError('Grafana dashboard does not exist and no'
' dashboard template was provided.')
if __opts__['test']:
ret['comment'] = 'Dashboard {0} is set to be created.'.format(
name
)
ret['result'] = None
return ret
_dashboard = dashboard
update_rows = []
_ids = []
_data = {}
for _n, _row in enumerate(_dashboard['rows']):
# Collect the unique ids
for _panel in _row['panels']:
if 'id' in _panel:
_ids.append(_panel['id'])
# Collect all of the titles in the existing dashboard
if 'title' in _row:
_data[_row['title']] = _n
_ids.sort()
if not _ids:
_ids = [1]
for row in rows:
if 'title' not in row:
raise SaltInvocationError('title is a required key for rows.')
# Each panel needs to have a unique ID
for panel in row['panels']:
_ids.append(_ids[-1] + 1)
panel['id'] = _ids[-1]
title = row['title']
# If the title doesn't exist, we need to add this row
if title not in _data:
update_rows.append(title)
_dashboard['rows'].append(row)
continue
# For existing titles, replace the row if it differs
_n = _data[title]
if _rows_differ(row, _dashboard['rows'][_n]):
_dashboard['rows'][_n] = row
update_rows.append(title)
if not update_rows:
ret['result'] = True
ret['comment'] = 'Dashboard {0} is up to date'.format(name)
return ret
if __opts__['test']:
msg = 'Dashboard {0} is set to be updated.'.format(name)
if update_rows:
msg = '{0} The following rows set to be updated: {1}'.format(
msg, update_rows
)
ret['comment'] = msg
return ret
body = {
'user': 'guest',
'group': 'guest',
'title': name,
'dashboard': salt.utils.json.dumps(_dashboard)
}
updated = __salt__['elasticsearch.index'](
index=index, doc_type='dashboard', body=body, id=name,
hosts=hosts
)
if updated:
ret['result'] = True
ret['changes']['changed'] = name
msg = 'Updated dashboard {0}.'.format(name)
if update_rows:
msg = '{0} The following rows were updated: {1}'.format(
msg, update_rows
)
ret['comment'] = msg
else:
ret['result'] = False
msg = 'Failed to update dashboard {0}.'.format(name)
ret['comment'] = msg
return ret | [
"def",
"dashboard_present",
"(",
"name",
",",
"dashboard",
"=",
"None",
",",
"dashboard_from_pillar",
"=",
"None",
",",
"rows",
"=",
"None",
",",
"rows_from_pillar",
"=",
"None",
",",
"profile",
"=",
"'grafana'",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
... | Ensure the grafana dashboard exists and is managed.
name
Name of the grafana dashboard.
dashboard
A dict that defines a dashboard that should be managed.
dashboard_from_pillar
A pillar key that contains a grafana dashboard dict. Mutually exclusive
with dashboard.
rows
A list of grafana rows.
rows_from_pillar
A list of pillar keys that contain lists of grafana dashboard rows.
Rows defined in the pillars will be appended to the rows defined in the
state.
profile
A pillar key or dict that contains a list of hosts and an
elasticsearch index to use. | [
"Ensure",
"the",
"grafana",
"dashboard",
"exists",
"and",
"is",
"managed",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/grafana.py#L222-L369 | train |
saltstack/salt | salt/states/grafana.py | dashboard_absent | def dashboard_absent(
name,
hosts=None,
profile='grafana'):
'''
Ensure the named grafana dashboard is deleted.
name
Name of the grafana dashboard.
profile
A pillar key or dict that contains a list of hosts and an
elasticsearch index to use.
'''
ret = {'name': name, 'result': None, 'comment': '', 'changes': {}}
hosts, index = _parse_profile(profile)
if not index:
raise SaltInvocationError('index is a required key in the profile.')
exists = __salt__['elasticsearch.exists'](
index=index, id=name, doc_type='dashboard', hosts=hosts
)
if exists:
if __opts__['test']:
ret['comment'] = 'Dashboard {0} is set to be removed.'.format(
name
)
return ret
deleted = __salt__['elasticsearch.delete'](
index=index, doc_type='dashboard', id=name, hosts=hosts
)
if deleted:
ret['result'] = True
ret['changes']['old'] = name
ret['changes']['new'] = None
else:
ret['result'] = False
ret['comment'] = 'Failed to delete {0} dashboard.'.format(name)
else:
ret['result'] = True
ret['comment'] = 'Dashboard {0} does not exist.'.format(name)
return ret | python | def dashboard_absent(
name,
hosts=None,
profile='grafana'):
'''
Ensure the named grafana dashboard is deleted.
name
Name of the grafana dashboard.
profile
A pillar key or dict that contains a list of hosts and an
elasticsearch index to use.
'''
ret = {'name': name, 'result': None, 'comment': '', 'changes': {}}
hosts, index = _parse_profile(profile)
if not index:
raise SaltInvocationError('index is a required key in the profile.')
exists = __salt__['elasticsearch.exists'](
index=index, id=name, doc_type='dashboard', hosts=hosts
)
if exists:
if __opts__['test']:
ret['comment'] = 'Dashboard {0} is set to be removed.'.format(
name
)
return ret
deleted = __salt__['elasticsearch.delete'](
index=index, doc_type='dashboard', id=name, hosts=hosts
)
if deleted:
ret['result'] = True
ret['changes']['old'] = name
ret['changes']['new'] = None
else:
ret['result'] = False
ret['comment'] = 'Failed to delete {0} dashboard.'.format(name)
else:
ret['result'] = True
ret['comment'] = 'Dashboard {0} does not exist.'.format(name)
return ret | [
"def",
"dashboard_absent",
"(",
"name",
",",
"hosts",
"=",
"None",
",",
"profile",
"=",
"'grafana'",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"None",
",",
"'comment'",
":",
"''",
",",
"'changes'",
":",
"{",
"}",
"}",
... | Ensure the named grafana dashboard is deleted.
name
Name of the grafana dashboard.
profile
A pillar key or dict that contains a list of hosts and an
elasticsearch index to use. | [
"Ensure",
"the",
"named",
"grafana",
"dashboard",
"is",
"deleted",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/grafana.py#L372-L416 | train |
saltstack/salt | salt/utils/jinja.py | ensure_sequence_filter | def ensure_sequence_filter(data):
'''
Ensure sequenced data.
**sequence**
ensure that parsed data is a sequence
.. code-block:: jinja
{% set my_string = "foo" %}
{% set my_list = ["bar", ] %}
{% set my_dict = {"baz": "qux"} %}
{{ my_string|sequence|first }}
{{ my_list|sequence|first }}
{{ my_dict|sequence|first }}
will be rendered as:
.. code-block:: yaml
foo
bar
baz
'''
if not isinstance(data, (list, tuple, set, dict)):
return [data]
return data | python | def ensure_sequence_filter(data):
'''
Ensure sequenced data.
**sequence**
ensure that parsed data is a sequence
.. code-block:: jinja
{% set my_string = "foo" %}
{% set my_list = ["bar", ] %}
{% set my_dict = {"baz": "qux"} %}
{{ my_string|sequence|first }}
{{ my_list|sequence|first }}
{{ my_dict|sequence|first }}
will be rendered as:
.. code-block:: yaml
foo
bar
baz
'''
if not isinstance(data, (list, tuple, set, dict)):
return [data]
return data | [
"def",
"ensure_sequence_filter",
"(",
"data",
")",
":",
"if",
"not",
"isinstance",
"(",
"data",
",",
"(",
"list",
",",
"tuple",
",",
"set",
",",
"dict",
")",
")",
":",
"return",
"[",
"data",
"]",
"return",
"data"
] | Ensure sequenced data.
**sequence**
ensure that parsed data is a sequence
.. code-block:: jinja
{% set my_string = "foo" %}
{% set my_list = ["bar", ] %}
{% set my_dict = {"baz": "qux"} %}
{{ my_string|sequence|first }}
{{ my_list|sequence|first }}
{{ my_dict|sequence|first }}
will be rendered as:
.. code-block:: yaml
foo
bar
baz | [
"Ensure",
"sequenced",
"data",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/jinja.py#L252-L281 | train |
saltstack/salt | salt/utils/jinja.py | to_bool | def to_bool(val):
'''
Returns the logical value.
.. code-block:: jinja
{{ 'yes' | to_bool }}
will be rendered as:
.. code-block:: text
True
'''
if val is None:
return False
if isinstance(val, bool):
return val
if isinstance(val, (six.text_type, six.string_types)):
return val.lower() in ('yes', '1', 'true')
if isinstance(val, six.integer_types):
return val > 0
if not isinstance(val, collections.Hashable):
return bool(val)
return False | python | def to_bool(val):
'''
Returns the logical value.
.. code-block:: jinja
{{ 'yes' | to_bool }}
will be rendered as:
.. code-block:: text
True
'''
if val is None:
return False
if isinstance(val, bool):
return val
if isinstance(val, (six.text_type, six.string_types)):
return val.lower() in ('yes', '1', 'true')
if isinstance(val, six.integer_types):
return val > 0
if not isinstance(val, collections.Hashable):
return bool(val)
return False | [
"def",
"to_bool",
"(",
"val",
")",
":",
"if",
"val",
"is",
"None",
":",
"return",
"False",
"if",
"isinstance",
"(",
"val",
",",
"bool",
")",
":",
"return",
"val",
"if",
"isinstance",
"(",
"val",
",",
"(",
"six",
".",
"text_type",
",",
"six",
".",
... | Returns the logical value.
.. code-block:: jinja
{{ 'yes' | to_bool }}
will be rendered as:
.. code-block:: text
True | [
"Returns",
"the",
"logical",
"value",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/jinja.py#L285-L309 | train |
saltstack/salt | salt/utils/jinja.py | tojson | def tojson(val, indent=None):
'''
Implementation of tojson filter (only present in Jinja 2.9 and later). If
Jinja 2.9 or later is installed, then the upstream version of this filter
will be used.
'''
options = {'ensure_ascii': True}
if indent is not None:
options['indent'] = indent
return (
salt.utils.json.dumps(
val, **options
).replace('<', '\\u003c')
.replace('>', '\\u003e')
.replace('&', '\\u0026')
.replace("'", '\\u0027')
) | python | def tojson(val, indent=None):
'''
Implementation of tojson filter (only present in Jinja 2.9 and later). If
Jinja 2.9 or later is installed, then the upstream version of this filter
will be used.
'''
options = {'ensure_ascii': True}
if indent is not None:
options['indent'] = indent
return (
salt.utils.json.dumps(
val, **options
).replace('<', '\\u003c')
.replace('>', '\\u003e')
.replace('&', '\\u0026')
.replace("'", '\\u0027')
) | [
"def",
"tojson",
"(",
"val",
",",
"indent",
"=",
"None",
")",
":",
"options",
"=",
"{",
"'ensure_ascii'",
":",
"True",
"}",
"if",
"indent",
"is",
"not",
"None",
":",
"options",
"[",
"'indent'",
"]",
"=",
"indent",
"return",
"(",
"salt",
".",
"utils",... | Implementation of tojson filter (only present in Jinja 2.9 and later). If
Jinja 2.9 or later is installed, then the upstream version of this filter
will be used. | [
"Implementation",
"of",
"tojson",
"filter",
"(",
"only",
"present",
"in",
"Jinja",
"2",
".",
"9",
"and",
"later",
")",
".",
"If",
"Jinja",
"2",
".",
"9",
"or",
"later",
"is",
"installed",
"then",
"the",
"upstream",
"version",
"of",
"this",
"filter",
"w... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/jinja.py#L313-L329 | train |
saltstack/salt | salt/utils/jinja.py | regex_search | def regex_search(txt, rgx, ignorecase=False, multiline=False):
'''
Searches for a pattern in the text.
.. code-block:: jinja
{% set my_text = 'abcd' %}
{{ my_text | regex_search('^(.*)BC(.*)$', ignorecase=True) }}
will be rendered as:
.. code-block:: text
('a', 'd')
'''
flag = 0
if ignorecase:
flag |= re.I
if multiline:
flag |= re.M
obj = re.search(rgx, txt, flag)
if not obj:
return
return obj.groups() | python | def regex_search(txt, rgx, ignorecase=False, multiline=False):
'''
Searches for a pattern in the text.
.. code-block:: jinja
{% set my_text = 'abcd' %}
{{ my_text | regex_search('^(.*)BC(.*)$', ignorecase=True) }}
will be rendered as:
.. code-block:: text
('a', 'd')
'''
flag = 0
if ignorecase:
flag |= re.I
if multiline:
flag |= re.M
obj = re.search(rgx, txt, flag)
if not obj:
return
return obj.groups() | [
"def",
"regex_search",
"(",
"txt",
",",
"rgx",
",",
"ignorecase",
"=",
"False",
",",
"multiline",
"=",
"False",
")",
":",
"flag",
"=",
"0",
"if",
"ignorecase",
":",
"flag",
"|=",
"re",
".",
"I",
"if",
"multiline",
":",
"flag",
"|=",
"re",
".",
"M",... | Searches for a pattern in the text.
.. code-block:: jinja
{% set my_text = 'abcd' %}
{{ my_text | regex_search('^(.*)BC(.*)$', ignorecase=True) }}
will be rendered as:
.. code-block:: text
('a', 'd') | [
"Searches",
"for",
"a",
"pattern",
"in",
"the",
"text",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/jinja.py#L357-L380 | train |
saltstack/salt | salt/utils/jinja.py | regex_match | def regex_match(txt, rgx, ignorecase=False, multiline=False):
'''
Searches for a pattern in the text.
.. code-block:: jinja
{% set my_text = 'abcd' %}
{{ my_text | regex_match('^(.*)BC(.*)$', ignorecase=True) }}
will be rendered as:
.. code-block:: text
('a', 'd')
'''
flag = 0
if ignorecase:
flag |= re.I
if multiline:
flag |= re.M
obj = re.match(rgx, txt, flag)
if not obj:
return
return obj.groups() | python | def regex_match(txt, rgx, ignorecase=False, multiline=False):
'''
Searches for a pattern in the text.
.. code-block:: jinja
{% set my_text = 'abcd' %}
{{ my_text | regex_match('^(.*)BC(.*)$', ignorecase=True) }}
will be rendered as:
.. code-block:: text
('a', 'd')
'''
flag = 0
if ignorecase:
flag |= re.I
if multiline:
flag |= re.M
obj = re.match(rgx, txt, flag)
if not obj:
return
return obj.groups() | [
"def",
"regex_match",
"(",
"txt",
",",
"rgx",
",",
"ignorecase",
"=",
"False",
",",
"multiline",
"=",
"False",
")",
":",
"flag",
"=",
"0",
"if",
"ignorecase",
":",
"flag",
"|=",
"re",
".",
"I",
"if",
"multiline",
":",
"flag",
"|=",
"re",
".",
"M",
... | Searches for a pattern in the text.
.. code-block:: jinja
{% set my_text = 'abcd' %}
{{ my_text | regex_match('^(.*)BC(.*)$', ignorecase=True) }}
will be rendered as:
.. code-block:: text
('a', 'd') | [
"Searches",
"for",
"a",
"pattern",
"in",
"the",
"text",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/jinja.py#L384-L407 | train |
saltstack/salt | salt/utils/jinja.py | regex_replace | def regex_replace(txt, rgx, val, ignorecase=False, multiline=False):
r'''
Searches for a pattern and replaces with a sequence of characters.
.. code-block:: jinja
{% set my_text = 'lets replace spaces' %}
{{ my_text | regex_replace('\s+', '__') }}
will be rendered as:
.. code-block:: text
lets__replace__spaces
'''
flag = 0
if ignorecase:
flag |= re.I
if multiline:
flag |= re.M
compiled_rgx = re.compile(rgx, flag)
return compiled_rgx.sub(val, txt) | python | def regex_replace(txt, rgx, val, ignorecase=False, multiline=False):
r'''
Searches for a pattern and replaces with a sequence of characters.
.. code-block:: jinja
{% set my_text = 'lets replace spaces' %}
{{ my_text | regex_replace('\s+', '__') }}
will be rendered as:
.. code-block:: text
lets__replace__spaces
'''
flag = 0
if ignorecase:
flag |= re.I
if multiline:
flag |= re.M
compiled_rgx = re.compile(rgx, flag)
return compiled_rgx.sub(val, txt) | [
"def",
"regex_replace",
"(",
"txt",
",",
"rgx",
",",
"val",
",",
"ignorecase",
"=",
"False",
",",
"multiline",
"=",
"False",
")",
":",
"flag",
"=",
"0",
"if",
"ignorecase",
":",
"flag",
"|=",
"re",
".",
"I",
"if",
"multiline",
":",
"flag",
"|=",
"r... | r'''
Searches for a pattern and replaces with a sequence of characters.
.. code-block:: jinja
{% set my_text = 'lets replace spaces' %}
{{ my_text | regex_replace('\s+', '__') }}
will be rendered as:
.. code-block:: text
lets__replace__spaces | [
"r",
"Searches",
"for",
"a",
"pattern",
"and",
"replaces",
"with",
"a",
"sequence",
"of",
"characters",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/jinja.py#L411-L432 | train |
saltstack/salt | salt/utils/jinja.py | uuid_ | def uuid_(val):
'''
Returns a UUID corresponding to the value passed as argument.
.. code-block:: jinja
{{ 'example' | uuid }}
will be rendered as:
.. code-block:: text
f4efeff8-c219-578a-bad7-3dc280612ec8
'''
return six.text_type(
uuid.uuid5(
GLOBAL_UUID,
salt.utils.stringutils.to_str(val)
)
) | python | def uuid_(val):
'''
Returns a UUID corresponding to the value passed as argument.
.. code-block:: jinja
{{ 'example' | uuid }}
will be rendered as:
.. code-block:: text
f4efeff8-c219-578a-bad7-3dc280612ec8
'''
return six.text_type(
uuid.uuid5(
GLOBAL_UUID,
salt.utils.stringutils.to_str(val)
)
) | [
"def",
"uuid_",
"(",
"val",
")",
":",
"return",
"six",
".",
"text_type",
"(",
"uuid",
".",
"uuid5",
"(",
"GLOBAL_UUID",
",",
"salt",
".",
"utils",
".",
"stringutils",
".",
"to_str",
"(",
"val",
")",
")",
")"
] | Returns a UUID corresponding to the value passed as argument.
.. code-block:: jinja
{{ 'example' | uuid }}
will be rendered as:
.. code-block:: text
f4efeff8-c219-578a-bad7-3dc280612ec8 | [
"Returns",
"a",
"UUID",
"corresponding",
"to",
"the",
"value",
"passed",
"as",
"argument",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/jinja.py#L436-L455 | train |
saltstack/salt | salt/utils/jinja.py | unique | def unique(values):
'''
Removes duplicates from a list.
.. code-block:: jinja
{% set my_list = ['a', 'b', 'c', 'a', 'b'] -%}
{{ my_list | unique }}
will be rendered as:
.. code-block:: text
['a', 'b', 'c']
'''
ret = None
if isinstance(values, collections.Hashable):
ret = set(values)
else:
ret = []
for value in values:
if value not in ret:
ret.append(value)
return ret | python | def unique(values):
'''
Removes duplicates from a list.
.. code-block:: jinja
{% set my_list = ['a', 'b', 'c', 'a', 'b'] -%}
{{ my_list | unique }}
will be rendered as:
.. code-block:: text
['a', 'b', 'c']
'''
ret = None
if isinstance(values, collections.Hashable):
ret = set(values)
else:
ret = []
for value in values:
if value not in ret:
ret.append(value)
return ret | [
"def",
"unique",
"(",
"values",
")",
":",
"ret",
"=",
"None",
"if",
"isinstance",
"(",
"values",
",",
"collections",
".",
"Hashable",
")",
":",
"ret",
"=",
"set",
"(",
"values",
")",
"else",
":",
"ret",
"=",
"[",
"]",
"for",
"value",
"in",
"values"... | Removes duplicates from a list.
.. code-block:: jinja
{% set my_list = ['a', 'b', 'c', 'a', 'b'] -%}
{{ my_list | unique }}
will be rendered as:
.. code-block:: text
['a', 'b', 'c'] | [
"Removes",
"duplicates",
"from",
"a",
"list",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/jinja.py#L462-L485 | train |
saltstack/salt | salt/utils/jinja.py | lst_avg | def lst_avg(lst):
'''
Returns the average value of a list.
.. code-block:: jinja
{% my_list = [1,2,3,4] -%}
{{ set my_list | avg }}
will be rendered as:
.. code-block:: yaml
2.5
'''
salt.utils.versions.warn_until(
'Neon',
'This results of this function are currently being rounded.'
'Beginning in the Salt Neon release, results will no longer be '
'rounded and this warning will be removed.',
stacklevel=3
)
if not isinstance(lst, collections.Hashable):
return float(sum(lst)/len(lst))
return float(lst) | python | def lst_avg(lst):
'''
Returns the average value of a list.
.. code-block:: jinja
{% my_list = [1,2,3,4] -%}
{{ set my_list | avg }}
will be rendered as:
.. code-block:: yaml
2.5
'''
salt.utils.versions.warn_until(
'Neon',
'This results of this function are currently being rounded.'
'Beginning in the Salt Neon release, results will no longer be '
'rounded and this warning will be removed.',
stacklevel=3
)
if not isinstance(lst, collections.Hashable):
return float(sum(lst)/len(lst))
return float(lst) | [
"def",
"lst_avg",
"(",
"lst",
")",
":",
"salt",
".",
"utils",
".",
"versions",
".",
"warn_until",
"(",
"'Neon'",
",",
"'This results of this function are currently being rounded.'",
"'Beginning in the Salt Neon release, results will no longer be '",
"'rounded and this warning wil... | Returns the average value of a list.
.. code-block:: jinja
{% my_list = [1,2,3,4] -%}
{{ set my_list | avg }}
will be rendered as:
.. code-block:: yaml
2.5 | [
"Returns",
"the",
"average",
"value",
"of",
"a",
"list",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/jinja.py#L527-L552 | train |
saltstack/salt | salt/utils/jinja.py | union | def union(lst1, lst2):
'''
Returns the union of two lists.
.. code-block:: jinja
{% my_list = [1,2,3,4] -%}
{{ set my_list | union([2, 4, 6]) }}
will be rendered as:
.. code-block:: text
[1, 2, 3, 4, 6]
'''
if isinstance(lst1, collections.Hashable) and isinstance(lst2, collections.Hashable):
return set(lst1) | set(lst2)
return unique(lst1 + lst2) | python | def union(lst1, lst2):
'''
Returns the union of two lists.
.. code-block:: jinja
{% my_list = [1,2,3,4] -%}
{{ set my_list | union([2, 4, 6]) }}
will be rendered as:
.. code-block:: text
[1, 2, 3, 4, 6]
'''
if isinstance(lst1, collections.Hashable) and isinstance(lst2, collections.Hashable):
return set(lst1) | set(lst2)
return unique(lst1 + lst2) | [
"def",
"union",
"(",
"lst1",
",",
"lst2",
")",
":",
"if",
"isinstance",
"(",
"lst1",
",",
"collections",
".",
"Hashable",
")",
"and",
"isinstance",
"(",
"lst2",
",",
"collections",
".",
"Hashable",
")",
":",
"return",
"set",
"(",
"lst1",
")",
"|",
"s... | Returns the union of two lists.
.. code-block:: jinja
{% my_list = [1,2,3,4] -%}
{{ set my_list | union([2, 4, 6]) }}
will be rendered as:
.. code-block:: text
[1, 2, 3, 4, 6] | [
"Returns",
"the",
"union",
"of",
"two",
"lists",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/jinja.py#L556-L573 | train |
saltstack/salt | salt/utils/jinja.py | intersect | def intersect(lst1, lst2):
'''
Returns the intersection of two lists.
.. code-block:: jinja
{% my_list = [1,2,3,4] -%}
{{ set my_list | intersect([2, 4, 6]) }}
will be rendered as:
.. code-block:: text
[2, 4]
'''
if isinstance(lst1, collections.Hashable) and isinstance(lst2, collections.Hashable):
return set(lst1) & set(lst2)
return unique([ele for ele in lst1 if ele in lst2]) | python | def intersect(lst1, lst2):
'''
Returns the intersection of two lists.
.. code-block:: jinja
{% my_list = [1,2,3,4] -%}
{{ set my_list | intersect([2, 4, 6]) }}
will be rendered as:
.. code-block:: text
[2, 4]
'''
if isinstance(lst1, collections.Hashable) and isinstance(lst2, collections.Hashable):
return set(lst1) & set(lst2)
return unique([ele for ele in lst1 if ele in lst2]) | [
"def",
"intersect",
"(",
"lst1",
",",
"lst2",
")",
":",
"if",
"isinstance",
"(",
"lst1",
",",
"collections",
".",
"Hashable",
")",
"and",
"isinstance",
"(",
"lst2",
",",
"collections",
".",
"Hashable",
")",
":",
"return",
"set",
"(",
"lst1",
")",
"&",
... | Returns the intersection of two lists.
.. code-block:: jinja
{% my_list = [1,2,3,4] -%}
{{ set my_list | intersect([2, 4, 6]) }}
will be rendered as:
.. code-block:: text
[2, 4] | [
"Returns",
"the",
"intersection",
"of",
"two",
"lists",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/jinja.py#L577-L594 | train |
saltstack/salt | salt/utils/jinja.py | SaltCacheLoader.file_client | def file_client(self):
'''
Return a file client. Instantiates on first call.
'''
if not self._file_client:
self._file_client = salt.fileclient.get_file_client(
self.opts, self.pillar_rend)
return self._file_client | python | def file_client(self):
'''
Return a file client. Instantiates on first call.
'''
if not self._file_client:
self._file_client = salt.fileclient.get_file_client(
self.opts, self.pillar_rend)
return self._file_client | [
"def",
"file_client",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_file_client",
":",
"self",
".",
"_file_client",
"=",
"salt",
".",
"fileclient",
".",
"get_file_client",
"(",
"self",
".",
"opts",
",",
"self",
".",
"pillar_rend",
")",
"return",
"se... | Return a file client. Instantiates on first call. | [
"Return",
"a",
"file",
"client",
".",
"Instantiates",
"on",
"first",
"call",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/jinja.py#L76-L83 | train |
saltstack/salt | salt/utils/jinja.py | SaltCacheLoader.cache_file | def cache_file(self, template):
'''
Cache a file from the salt master
'''
saltpath = salt.utils.url.create(template)
self.file_client().get_file(saltpath, '', True, self.saltenv) | python | def cache_file(self, template):
'''
Cache a file from the salt master
'''
saltpath = salt.utils.url.create(template)
self.file_client().get_file(saltpath, '', True, self.saltenv) | [
"def",
"cache_file",
"(",
"self",
",",
"template",
")",
":",
"saltpath",
"=",
"salt",
".",
"utils",
".",
"url",
".",
"create",
"(",
"template",
")",
"self",
".",
"file_client",
"(",
")",
".",
"get_file",
"(",
"saltpath",
",",
"''",
",",
"True",
",",
... | Cache a file from the salt master | [
"Cache",
"a",
"file",
"from",
"the",
"salt",
"master"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/jinja.py#L85-L90 | train |
saltstack/salt | salt/utils/jinja.py | SaltCacheLoader.check_cache | def check_cache(self, template):
'''
Cache a file only once
'''
if template not in self.cached:
self.cache_file(template)
self.cached.append(template) | python | def check_cache(self, template):
'''
Cache a file only once
'''
if template not in self.cached:
self.cache_file(template)
self.cached.append(template) | [
"def",
"check_cache",
"(",
"self",
",",
"template",
")",
":",
"if",
"template",
"not",
"in",
"self",
".",
"cached",
":",
"self",
".",
"cache_file",
"(",
"template",
")",
"self",
".",
"cached",
".",
"append",
"(",
"template",
")"
] | Cache a file only once | [
"Cache",
"a",
"file",
"only",
"once"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/jinja.py#L92-L98 | train |
saltstack/salt | salt/utils/jinja.py | SaltCacheLoader.get_source | def get_source(self, environment, template):
'''
Salt-specific loader to find imported jinja files.
Jinja imports will be interpreted as originating from the top
of each of the directories in the searchpath when the template
name does not begin with './' or '../'. When a template name
begins with './' or '../' then the import will be relative to
the importing file.
'''
# FIXME: somewhere do seprataor replacement: '\\' => '/'
_template = template
if template.split('/', 1)[0] in ('..', '.'):
is_relative = True
else:
is_relative = False
# checks for relative '..' paths that step-out of file_roots
if is_relative:
# Starts with a relative path indicator
if not environment or 'tpldir' not in environment.globals:
log.warning(
'Relative path "%s" cannot be resolved without an environment',
template
)
raise TemplateNotFound
base_path = environment.globals['tpldir']
_template = os.path.normpath('/'.join((base_path, _template)))
if _template.split('/', 1)[0] == '..':
log.warning(
'Discarded template path "%s": attempts to'
' ascend outside of salt://', template
)
raise TemplateNotFound(template)
self.check_cache(_template)
if environment and template:
tpldir = os.path.dirname(_template).replace('\\', '/')
tplfile = _template
if is_relative:
tpldir = environment.globals.get('tpldir', tpldir)
tplfile = template
tpldata = {
'tplfile': tplfile,
'tpldir': '.' if tpldir == '' else tpldir,
'tpldot': tpldir.replace('/', '.'),
}
environment.globals.update(tpldata)
# pylint: disable=cell-var-from-loop
for spath in self.searchpath:
filepath = os.path.join(spath, _template)
try:
with salt.utils.files.fopen(filepath, 'rb') as ifile:
contents = ifile.read().decode(self.encoding)
mtime = os.path.getmtime(filepath)
def uptodate():
try:
return os.path.getmtime(filepath) == mtime
except OSError:
return False
return contents, filepath, uptodate
except IOError:
# there is no file under current path
continue
# pylint: enable=cell-var-from-loop
# there is no template file within searchpaths
raise TemplateNotFound(template) | python | def get_source(self, environment, template):
'''
Salt-specific loader to find imported jinja files.
Jinja imports will be interpreted as originating from the top
of each of the directories in the searchpath when the template
name does not begin with './' or '../'. When a template name
begins with './' or '../' then the import will be relative to
the importing file.
'''
# FIXME: somewhere do seprataor replacement: '\\' => '/'
_template = template
if template.split('/', 1)[0] in ('..', '.'):
is_relative = True
else:
is_relative = False
# checks for relative '..' paths that step-out of file_roots
if is_relative:
# Starts with a relative path indicator
if not environment or 'tpldir' not in environment.globals:
log.warning(
'Relative path "%s" cannot be resolved without an environment',
template
)
raise TemplateNotFound
base_path = environment.globals['tpldir']
_template = os.path.normpath('/'.join((base_path, _template)))
if _template.split('/', 1)[0] == '..':
log.warning(
'Discarded template path "%s": attempts to'
' ascend outside of salt://', template
)
raise TemplateNotFound(template)
self.check_cache(_template)
if environment and template:
tpldir = os.path.dirname(_template).replace('\\', '/')
tplfile = _template
if is_relative:
tpldir = environment.globals.get('tpldir', tpldir)
tplfile = template
tpldata = {
'tplfile': tplfile,
'tpldir': '.' if tpldir == '' else tpldir,
'tpldot': tpldir.replace('/', '.'),
}
environment.globals.update(tpldata)
# pylint: disable=cell-var-from-loop
for spath in self.searchpath:
filepath = os.path.join(spath, _template)
try:
with salt.utils.files.fopen(filepath, 'rb') as ifile:
contents = ifile.read().decode(self.encoding)
mtime = os.path.getmtime(filepath)
def uptodate():
try:
return os.path.getmtime(filepath) == mtime
except OSError:
return False
return contents, filepath, uptodate
except IOError:
# there is no file under current path
continue
# pylint: enable=cell-var-from-loop
# there is no template file within searchpaths
raise TemplateNotFound(template) | [
"def",
"get_source",
"(",
"self",
",",
"environment",
",",
"template",
")",
":",
"# FIXME: somewhere do seprataor replacement: '\\\\' => '/'",
"_template",
"=",
"template",
"if",
"template",
".",
"split",
"(",
"'/'",
",",
"1",
")",
"[",
"0",
"]",
"in",
"(",
"'... | Salt-specific loader to find imported jinja files.
Jinja imports will be interpreted as originating from the top
of each of the directories in the searchpath when the template
name does not begin with './' or '../'. When a template name
begins with './' or '../' then the import will be relative to
the importing file. | [
"Salt",
"-",
"specific",
"loader",
"to",
"find",
"imported",
"jinja",
"files",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/jinja.py#L100-L171 | train |
saltstack/salt | salt/utils/jinja.py | SerializerExtension.finalizer | def finalizer(self, data):
'''
Ensure that printed mappings are YAML friendly.
'''
def explore(data):
if isinstance(data, (dict, OrderedDict)):
return PrintableDict(
[(key, explore(value)) for key, value in six.iteritems(data)]
)
elif isinstance(data, (list, tuple, set)):
return data.__class__([explore(value) for value in data])
return data
return explore(data) | python | def finalizer(self, data):
'''
Ensure that printed mappings are YAML friendly.
'''
def explore(data):
if isinstance(data, (dict, OrderedDict)):
return PrintableDict(
[(key, explore(value)) for key, value in six.iteritems(data)]
)
elif isinstance(data, (list, tuple, set)):
return data.__class__([explore(value) for value in data])
return data
return explore(data) | [
"def",
"finalizer",
"(",
"self",
",",
"data",
")",
":",
"def",
"explore",
"(",
"data",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"(",
"dict",
",",
"OrderedDict",
")",
")",
":",
"return",
"PrintableDict",
"(",
"[",
"(",
"key",
",",
"explore",
... | Ensure that printed mappings are YAML friendly. | [
"Ensure",
"that",
"printed",
"mappings",
"are",
"YAML",
"friendly",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/jinja.py#L840-L852 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.