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/proxy/onyx.py | add_config | def add_config(lines):
'''
Add one or more config lines to the switch running config
.. code-block:: bash
salt '*' onyx.cmd add_config 'snmp-server community TESTSTRINGHERE rw'
.. note::
For more than one config added per command, lines should be a list.
'''
if not isinstance(lines, list):
lines = [lines]
try:
enable()
configure_terminal()
for line in lines:
sendline(line)
configure_terminal_exit()
disable()
except TerminalException as e:
log.error(e)
return False
return True | python | def add_config(lines):
'''
Add one or more config lines to the switch running config
.. code-block:: bash
salt '*' onyx.cmd add_config 'snmp-server community TESTSTRINGHERE rw'
.. note::
For more than one config added per command, lines should be a list.
'''
if not isinstance(lines, list):
lines = [lines]
try:
enable()
configure_terminal()
for line in lines:
sendline(line)
configure_terminal_exit()
disable()
except TerminalException as e:
log.error(e)
return False
return True | [
"def",
"add_config",
"(",
"lines",
")",
":",
"if",
"not",
"isinstance",
"(",
"lines",
",",
"list",
")",
":",
"lines",
"=",
"[",
"lines",
"]",
"try",
":",
"enable",
"(",
")",
"configure_terminal",
"(",
")",
"for",
"line",
"in",
"lines",
":",
"sendline... | Add one or more config lines to the switch running config
.. code-block:: bash
salt '*' onyx.cmd add_config 'snmp-server community TESTSTRINGHERE rw'
.. note::
For more than one config added per command, lines should be a list. | [
"Add",
"one",
"or",
"more",
"config",
"lines",
"to",
"the",
"switch",
"running",
"config"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/onyx.py#L394-L418 | train |
saltstack/salt | salt/proxy/onyx.py | delete_config | def delete_config(lines):
'''
Delete one or more config lines to the switch running config
.. code-block:: bash
salt '*' onyx.cmd delete_config 'snmp-server community TESTSTRINGHERE group network-operator'
.. note::
For more than one config deleted per command, lines should be a list.
'''
if not isinstance(lines, list):
lines = [lines]
try:
sendline('config terminal')
for line in lines:
sendline(' '.join(['no', line]))
sendline('end')
sendline('copy running-config startup-config')
except TerminalException as e:
log.error(e)
return False
return True | python | def delete_config(lines):
'''
Delete one or more config lines to the switch running config
.. code-block:: bash
salt '*' onyx.cmd delete_config 'snmp-server community TESTSTRINGHERE group network-operator'
.. note::
For more than one config deleted per command, lines should be a list.
'''
if not isinstance(lines, list):
lines = [lines]
try:
sendline('config terminal')
for line in lines:
sendline(' '.join(['no', line]))
sendline('end')
sendline('copy running-config startup-config')
except TerminalException as e:
log.error(e)
return False
return True | [
"def",
"delete_config",
"(",
"lines",
")",
":",
"if",
"not",
"isinstance",
"(",
"lines",
",",
"list",
")",
":",
"lines",
"=",
"[",
"lines",
"]",
"try",
":",
"sendline",
"(",
"'config terminal'",
")",
"for",
"line",
"in",
"lines",
":",
"sendline",
"(",
... | Delete one or more config lines to the switch running config
.. code-block:: bash
salt '*' onyx.cmd delete_config 'snmp-server community TESTSTRINGHERE group network-operator'
.. note::
For more than one config deleted per command, lines should be a list. | [
"Delete",
"one",
"or",
"more",
"config",
"lines",
"to",
"the",
"switch",
"running",
"config"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/onyx.py#L421-L444 | train |
saltstack/salt | salt/proxy/onyx.py | find | def find(pattern):
'''
Find all instances where the pattern is in the running command
.. code-block:: bash
salt '*' onyx.cmd find '^snmp-server.*$'
.. note::
This uses the `re.MULTILINE` regex format for python, and runs the
regex against the whole show_run output.
'''
matcher = re.compile(pattern, re.MULTILINE)
return matcher.findall(show_run()) | python | def find(pattern):
'''
Find all instances where the pattern is in the running command
.. code-block:: bash
salt '*' onyx.cmd find '^snmp-server.*$'
.. note::
This uses the `re.MULTILINE` regex format for python, and runs the
regex against the whole show_run output.
'''
matcher = re.compile(pattern, re.MULTILINE)
return matcher.findall(show_run()) | [
"def",
"find",
"(",
"pattern",
")",
":",
"matcher",
"=",
"re",
".",
"compile",
"(",
"pattern",
",",
"re",
".",
"MULTILINE",
")",
"return",
"matcher",
".",
"findall",
"(",
"show_run",
"(",
")",
")"
] | Find all instances where the pattern is in the running command
.. code-block:: bash
salt '*' onyx.cmd find '^snmp-server.*$'
.. note::
This uses the `re.MULTILINE` regex format for python, and runs the
regex against the whole show_run output. | [
"Find",
"all",
"instances",
"where",
"the",
"pattern",
"is",
"in",
"the",
"running",
"command"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/onyx.py#L447-L460 | train |
saltstack/salt | salt/proxy/onyx.py | replace | def replace(old_value, new_value, full_match=False):
'''
Replace string or full line matches in switch's running config
If full_match is set to True, then the whole line will need to be matched
as part of the old value.
.. code-block:: bash
salt '*' onyx.cmd replace 'TESTSTRINGHERE' 'NEWTESTSTRINGHERE'
'''
if full_match is False:
matcher = re.compile('^.*{0}.*$'.format(re.escape(old_value)), re.MULTILINE)
repl = re.compile(re.escape(old_value))
else:
matcher = re.compile(old_value, re.MULTILINE)
repl = re.compile(old_value)
lines = {'old': [], 'new': []}
for line in matcher.finditer(show_run()):
lines['old'].append(line.group(0))
lines['new'].append(repl.sub(new_value, line.group(0)))
delete_config(lines['old'])
add_config(lines['new'])
return lines | python | def replace(old_value, new_value, full_match=False):
'''
Replace string or full line matches in switch's running config
If full_match is set to True, then the whole line will need to be matched
as part of the old value.
.. code-block:: bash
salt '*' onyx.cmd replace 'TESTSTRINGHERE' 'NEWTESTSTRINGHERE'
'''
if full_match is False:
matcher = re.compile('^.*{0}.*$'.format(re.escape(old_value)), re.MULTILINE)
repl = re.compile(re.escape(old_value))
else:
matcher = re.compile(old_value, re.MULTILINE)
repl = re.compile(old_value)
lines = {'old': [], 'new': []}
for line in matcher.finditer(show_run()):
lines['old'].append(line.group(0))
lines['new'].append(repl.sub(new_value, line.group(0)))
delete_config(lines['old'])
add_config(lines['new'])
return lines | [
"def",
"replace",
"(",
"old_value",
",",
"new_value",
",",
"full_match",
"=",
"False",
")",
":",
"if",
"full_match",
"is",
"False",
":",
"matcher",
"=",
"re",
".",
"compile",
"(",
"'^.*{0}.*$'",
".",
"format",
"(",
"re",
".",
"escape",
"(",
"old_value",
... | Replace string or full line matches in switch's running config
If full_match is set to True, then the whole line will need to be matched
as part of the old value.
.. code-block:: bash
salt '*' onyx.cmd replace 'TESTSTRINGHERE' 'NEWTESTSTRINGHERE' | [
"Replace",
"string",
"or",
"full",
"line",
"matches",
"in",
"switch",
"s",
"running",
"config"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/onyx.py#L463-L489 | train |
saltstack/salt | salt/states/postgres_group.py | present | def present(name,
createdb=None,
createroles=None,
encrypted=None,
superuser=None,
inherit=None,
login=None,
replication=None,
password=None,
refresh_password=None,
groups=None,
user=None,
maintenance_db=None,
db_password=None,
db_host=None,
db_port=None,
db_user=None):
'''
Ensure that the named group is present with the specified privileges
Please note that the user/group notion in postgresql is just abstract, we
have roles, where users can be seen as roles with the ``LOGIN`` privilege
and groups the others.
name
The name of the group to manage
createdb
Is the group allowed to create databases?
createroles
Is the group allowed to create other roles/users
encrypted
Should the password be encrypted in the system catalog?
login
Should the group have login perm
inherit
Should the group inherit permissions
superuser
Should the new group be a "superuser"
replication
Should the new group be allowed to initiate streaming replication
password
The group's password
It can be either a plain string or a md5 postgresql hashed password::
'md5{MD5OF({password}{role}}'
If encrypted is ``None`` or ``True``, the password will be automatically
encrypted to the previous format if it is not already done.
refresh_password
Password refresh flag
Boolean attribute to specify whether to password comparison check
should be performed.
If refresh_password is ``True``, the password will be automatically
updated without extra password change check.
This behaviour makes it possible to execute in environments without
superuser access available, e.g. Amazon RDS for PostgreSQL
groups
A string of comma separated groups the group should be in
user
System user all operations should be performed on behalf of
.. versionadded:: 0.17.0
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': 'Group {0} is already present'.format(name)}
# default to encrypted passwords
if encrypted is not False:
encrypted = postgres._DEFAULT_PASSWORDS_ENCRYPTION
# maybe encrypt if it's not already and necessary
password = postgres._maybe_encrypt_password(name,
password,
encrypted=encrypted)
db_args = {
'maintenance_db': maintenance_db,
'runas': user,
'host': db_host,
'user': db_user,
'port': db_port,
'password': db_password,
}
# check if group exists
mode = 'create'
group_attr = __salt__['postgres.role_get'](
name, return_password=not refresh_password, **db_args)
if group_attr is not None:
mode = 'update'
# The user is not present, make it!
cret = None
update = {}
if mode == 'update':
if (
createdb is not None
and group_attr['can create databases'] != createdb
):
update['createdb'] = createdb
if (
inherit is not None
and group_attr['inherits privileges'] != inherit
):
update['inherit'] = inherit
if login is not None and group_attr['can login'] != login:
update['login'] = login
if (
createroles is not None
and group_attr['can create roles'] != createroles
):
update['createroles'] = createroles
if (
replication is not None
and group_attr['replication'] != replication
):
update['replication'] = replication
if superuser is not None and group_attr['superuser'] != superuser:
update['superuser'] = superuser
if password is not None and (refresh_password or group_attr['password'] != password):
update['password'] = True
if mode == 'create' or (mode == 'update' and update):
if __opts__['test']:
if update:
ret['changes'][name] = update
ret['result'] = None
ret['comment'] = 'Group {0} is set to be {1}d'.format(name, mode)
return ret
cret = __salt__['postgres.group_{0}'.format(mode)](
groupname=name,
createdb=createdb,
createroles=createroles,
encrypted=encrypted,
login=login,
inherit=inherit,
superuser=superuser,
replication=replication,
rolepassword=password,
groups=groups,
**db_args)
else:
cret = None
if cret:
ret['comment'] = 'The group {0} has been {1}d'.format(name, mode)
if update:
ret['changes'][name] = update
elif cret is not None:
ret['comment'] = 'Failed to create group {0}'.format(name)
ret['result'] = False
else:
ret['result'] = True
return ret | python | def present(name,
createdb=None,
createroles=None,
encrypted=None,
superuser=None,
inherit=None,
login=None,
replication=None,
password=None,
refresh_password=None,
groups=None,
user=None,
maintenance_db=None,
db_password=None,
db_host=None,
db_port=None,
db_user=None):
'''
Ensure that the named group is present with the specified privileges
Please note that the user/group notion in postgresql is just abstract, we
have roles, where users can be seen as roles with the ``LOGIN`` privilege
and groups the others.
name
The name of the group to manage
createdb
Is the group allowed to create databases?
createroles
Is the group allowed to create other roles/users
encrypted
Should the password be encrypted in the system catalog?
login
Should the group have login perm
inherit
Should the group inherit permissions
superuser
Should the new group be a "superuser"
replication
Should the new group be allowed to initiate streaming replication
password
The group's password
It can be either a plain string or a md5 postgresql hashed password::
'md5{MD5OF({password}{role}}'
If encrypted is ``None`` or ``True``, the password will be automatically
encrypted to the previous format if it is not already done.
refresh_password
Password refresh flag
Boolean attribute to specify whether to password comparison check
should be performed.
If refresh_password is ``True``, the password will be automatically
updated without extra password change check.
This behaviour makes it possible to execute in environments without
superuser access available, e.g. Amazon RDS for PostgreSQL
groups
A string of comma separated groups the group should be in
user
System user all operations should be performed on behalf of
.. versionadded:: 0.17.0
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': 'Group {0} is already present'.format(name)}
# default to encrypted passwords
if encrypted is not False:
encrypted = postgres._DEFAULT_PASSWORDS_ENCRYPTION
# maybe encrypt if it's not already and necessary
password = postgres._maybe_encrypt_password(name,
password,
encrypted=encrypted)
db_args = {
'maintenance_db': maintenance_db,
'runas': user,
'host': db_host,
'user': db_user,
'port': db_port,
'password': db_password,
}
# check if group exists
mode = 'create'
group_attr = __salt__['postgres.role_get'](
name, return_password=not refresh_password, **db_args)
if group_attr is not None:
mode = 'update'
# The user is not present, make it!
cret = None
update = {}
if mode == 'update':
if (
createdb is not None
and group_attr['can create databases'] != createdb
):
update['createdb'] = createdb
if (
inherit is not None
and group_attr['inherits privileges'] != inherit
):
update['inherit'] = inherit
if login is not None and group_attr['can login'] != login:
update['login'] = login
if (
createroles is not None
and group_attr['can create roles'] != createroles
):
update['createroles'] = createroles
if (
replication is not None
and group_attr['replication'] != replication
):
update['replication'] = replication
if superuser is not None and group_attr['superuser'] != superuser:
update['superuser'] = superuser
if password is not None and (refresh_password or group_attr['password'] != password):
update['password'] = True
if mode == 'create' or (mode == 'update' and update):
if __opts__['test']:
if update:
ret['changes'][name] = update
ret['result'] = None
ret['comment'] = 'Group {0} is set to be {1}d'.format(name, mode)
return ret
cret = __salt__['postgres.group_{0}'.format(mode)](
groupname=name,
createdb=createdb,
createroles=createroles,
encrypted=encrypted,
login=login,
inherit=inherit,
superuser=superuser,
replication=replication,
rolepassword=password,
groups=groups,
**db_args)
else:
cret = None
if cret:
ret['comment'] = 'The group {0} has been {1}d'.format(name, mode)
if update:
ret['changes'][name] = update
elif cret is not None:
ret['comment'] = 'Failed to create group {0}'.format(name)
ret['result'] = False
else:
ret['result'] = True
return ret | [
"def",
"present",
"(",
"name",
",",
"createdb",
"=",
"None",
",",
"createroles",
"=",
"None",
",",
"encrypted",
"=",
"None",
",",
"superuser",
"=",
"None",
",",
"inherit",
"=",
"None",
",",
"login",
"=",
"None",
",",
"replication",
"=",
"None",
",",
... | Ensure that the named group is present with the specified privileges
Please note that the user/group notion in postgresql is just abstract, we
have roles, where users can be seen as roles with the ``LOGIN`` privilege
and groups the others.
name
The name of the group to manage
createdb
Is the group allowed to create databases?
createroles
Is the group allowed to create other roles/users
encrypted
Should the password be encrypted in the system catalog?
login
Should the group have login perm
inherit
Should the group inherit permissions
superuser
Should the new group be a "superuser"
replication
Should the new group be allowed to initiate streaming replication
password
The group's password
It can be either a plain string or a md5 postgresql hashed password::
'md5{MD5OF({password}{role}}'
If encrypted is ``None`` or ``True``, the password will be automatically
encrypted to the previous format if it is not already done.
refresh_password
Password refresh flag
Boolean attribute to specify whether to password comparison check
should be performed.
If refresh_password is ``True``, the password will be automatically
updated without extra password change check.
This behaviour makes it possible to execute in environments without
superuser access available, e.g. Amazon RDS for PostgreSQL
groups
A string of comma separated groups the group should be in
user
System user all operations should be performed on behalf of
.. versionadded:: 0.17.0
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",
"group",
"is",
"present",
"with",
"the",
"specified",
"privileges",
"Please",
"note",
"that",
"the",
"user",
"/",
"group",
"notion",
"in",
"postgresql",
"is",
"just",
"abstract",
"we",
"have",
"roles",
"where",
"users",
"can... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/postgres_group.py#L36-L213 | train |
saltstack/salt | salt/states/postgres_group.py | absent | def absent(name,
user=None,
maintenance_db=None,
db_password=None,
db_host=None,
db_port=None,
db_user=None):
'''
Ensure that the named group is absent
name
The groupname of the group to remove
user
System user all operations should be performed on behalf of
.. versionadded:: 0.17.0
db_user
database username if different from config or defaul
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': ''}
db_args = {
'maintenance_db': maintenance_db,
'runas': user,
'host': db_host,
'user': db_user,
'port': db_port,
'password': db_password,
}
# check if group exists and remove it
if __salt__['postgres.user_exists'](name, **db_args):
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Group {0} is set to be removed'.format(name)
return ret
if __salt__['postgres.group_remove'](name, **db_args):
ret['comment'] = 'Group {0} has been removed'.format(name)
ret['changes'][name] = 'Absent'
return ret
else:
ret['comment'] = 'Group {0} is not present, so it cannot ' \
'be removed'.format(name)
return ret | python | def absent(name,
user=None,
maintenance_db=None,
db_password=None,
db_host=None,
db_port=None,
db_user=None):
'''
Ensure that the named group is absent
name
The groupname of the group to remove
user
System user all operations should be performed on behalf of
.. versionadded:: 0.17.0
db_user
database username if different from config or defaul
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': ''}
db_args = {
'maintenance_db': maintenance_db,
'runas': user,
'host': db_host,
'user': db_user,
'port': db_port,
'password': db_password,
}
# check if group exists and remove it
if __salt__['postgres.user_exists'](name, **db_args):
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Group {0} is set to be removed'.format(name)
return ret
if __salt__['postgres.group_remove'](name, **db_args):
ret['comment'] = 'Group {0} has been removed'.format(name)
ret['changes'][name] = 'Absent'
return ret
else:
ret['comment'] = 'Group {0} is not present, so it cannot ' \
'be removed'.format(name)
return ret | [
"def",
"absent",
"(",
"name",
",",
"user",
"=",
"None",
",",
"maintenance_db",
"=",
"None",
",",
"db_password",
"=",
"None",
",",
"db_host",
"=",
"None",
",",
"db_port",
"=",
"None",
",",
"db_user",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
... | Ensure that the named group is absent
name
The groupname of the group to remove
user
System user all operations should be performed on behalf of
.. versionadded:: 0.17.0
db_user
database username if different from config or defaul
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",
"group",
"is",
"absent"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/postgres_group.py#L216-L273 | train |
saltstack/salt | salt/utils/docker/translate/helpers.py | get_port_def | def get_port_def(port_num, proto='tcp'):
'''
Given a port number and protocol, returns the port definition expected by
docker-py. For TCP ports this is simply an integer, for UDP ports this is
(port_num, 'udp').
port_num can also be a string in the format 'port_num/udp'. If so, the
"proto" argument will be ignored. The reason we need to be able to pass in
the protocol separately is because this function is sometimes invoked on
data derived from a port range (e.g. '2222-2223/udp'). In these cases the
protocol has already been stripped off and the port range resolved into the
start and end of the range, and get_port_def() is invoked once for each
port number in that range. So, rather than munge udp ports back into
strings before passing them to this function, the function will see if it
has a string and use the protocol from it if present.
This function does not catch the TypeError or ValueError which would be
raised if the port number is non-numeric. This function either needs to be
run on known good input, or should be run within a try/except that catches
these two exceptions.
'''
try:
port_num, _, port_num_proto = port_num.partition('/')
except AttributeError:
pass
else:
if port_num_proto:
proto = port_num_proto
try:
if proto.lower() == 'udp':
return int(port_num), 'udp'
except AttributeError:
pass
return int(port_num) | python | def get_port_def(port_num, proto='tcp'):
'''
Given a port number and protocol, returns the port definition expected by
docker-py. For TCP ports this is simply an integer, for UDP ports this is
(port_num, 'udp').
port_num can also be a string in the format 'port_num/udp'. If so, the
"proto" argument will be ignored. The reason we need to be able to pass in
the protocol separately is because this function is sometimes invoked on
data derived from a port range (e.g. '2222-2223/udp'). In these cases the
protocol has already been stripped off and the port range resolved into the
start and end of the range, and get_port_def() is invoked once for each
port number in that range. So, rather than munge udp ports back into
strings before passing them to this function, the function will see if it
has a string and use the protocol from it if present.
This function does not catch the TypeError or ValueError which would be
raised if the port number is non-numeric. This function either needs to be
run on known good input, or should be run within a try/except that catches
these two exceptions.
'''
try:
port_num, _, port_num_proto = port_num.partition('/')
except AttributeError:
pass
else:
if port_num_proto:
proto = port_num_proto
try:
if proto.lower() == 'udp':
return int(port_num), 'udp'
except AttributeError:
pass
return int(port_num) | [
"def",
"get_port_def",
"(",
"port_num",
",",
"proto",
"=",
"'tcp'",
")",
":",
"try",
":",
"port_num",
",",
"_",
",",
"port_num_proto",
"=",
"port_num",
".",
"partition",
"(",
"'/'",
")",
"except",
"AttributeError",
":",
"pass",
"else",
":",
"if",
"port_n... | Given a port number and protocol, returns the port definition expected by
docker-py. For TCP ports this is simply an integer, for UDP ports this is
(port_num, 'udp').
port_num can also be a string in the format 'port_num/udp'. If so, the
"proto" argument will be ignored. The reason we need to be able to pass in
the protocol separately is because this function is sometimes invoked on
data derived from a port range (e.g. '2222-2223/udp'). In these cases the
protocol has already been stripped off and the port range resolved into the
start and end of the range, and get_port_def() is invoked once for each
port number in that range. So, rather than munge udp ports back into
strings before passing them to this function, the function will see if it
has a string and use the protocol from it if present.
This function does not catch the TypeError or ValueError which would be
raised if the port number is non-numeric. This function either needs to be
run on known good input, or should be run within a try/except that catches
these two exceptions. | [
"Given",
"a",
"port",
"number",
"and",
"protocol",
"returns",
"the",
"port",
"definition",
"expected",
"by",
"docker",
"-",
"py",
".",
"For",
"TCP",
"ports",
"this",
"is",
"simply",
"an",
"integer",
"for",
"UDP",
"ports",
"this",
"is",
"(",
"port_num",
"... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/docker/translate/helpers.py#L26-L59 | train |
saltstack/salt | salt/utils/docker/translate/helpers.py | get_port_range | def get_port_range(port_def):
'''
Given a port number or range, return a start and end to that range. Port
ranges are defined as a string containing two numbers separated by a dash
(e.g. '4505-4506').
A ValueError will be raised if bad input is provided.
'''
if isinstance(port_def, six.integer_types):
# Single integer, start/end of range is the same
return port_def, port_def
try:
comps = [int(x) for x in split(port_def, '-')]
if len(comps) == 1:
range_start = range_end = comps[0]
else:
range_start, range_end = comps
if range_start > range_end:
raise ValueError('start > end')
except (TypeError, ValueError) as exc:
if exc.__str__() == 'start > end':
msg = (
'Start of port range ({0}) cannot be greater than end of '
'port range ({1})'.format(range_start, range_end)
)
else:
msg = '\'{0}\' is non-numeric or an invalid port range'.format(
port_def
)
raise ValueError(msg)
else:
return range_start, range_end | python | def get_port_range(port_def):
'''
Given a port number or range, return a start and end to that range. Port
ranges are defined as a string containing two numbers separated by a dash
(e.g. '4505-4506').
A ValueError will be raised if bad input is provided.
'''
if isinstance(port_def, six.integer_types):
# Single integer, start/end of range is the same
return port_def, port_def
try:
comps = [int(x) for x in split(port_def, '-')]
if len(comps) == 1:
range_start = range_end = comps[0]
else:
range_start, range_end = comps
if range_start > range_end:
raise ValueError('start > end')
except (TypeError, ValueError) as exc:
if exc.__str__() == 'start > end':
msg = (
'Start of port range ({0}) cannot be greater than end of '
'port range ({1})'.format(range_start, range_end)
)
else:
msg = '\'{0}\' is non-numeric or an invalid port range'.format(
port_def
)
raise ValueError(msg)
else:
return range_start, range_end | [
"def",
"get_port_range",
"(",
"port_def",
")",
":",
"if",
"isinstance",
"(",
"port_def",
",",
"six",
".",
"integer_types",
")",
":",
"# Single integer, start/end of range is the same",
"return",
"port_def",
",",
"port_def",
"try",
":",
"comps",
"=",
"[",
"int",
... | Given a port number or range, return a start and end to that range. Port
ranges are defined as a string containing two numbers separated by a dash
(e.g. '4505-4506').
A ValueError will be raised if bad input is provided. | [
"Given",
"a",
"port",
"number",
"or",
"range",
"return",
"a",
"start",
"and",
"end",
"to",
"that",
"range",
".",
"Port",
"ranges",
"are",
"defined",
"as",
"a",
"string",
"containing",
"two",
"numbers",
"separated",
"by",
"a",
"dash",
"(",
"e",
".",
"g"... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/docker/translate/helpers.py#L62-L93 | train |
saltstack/salt | salt/utils/docker/translate/helpers.py | map_vals | def map_vals(val, *names, **extra_opts):
'''
Many arguments come in as a list of VAL1:VAL2 pairs, but map to a list
of dicts in the format {NAME1: VAL1, NAME2: VAL2}. This function
provides common code to handle these instances.
'''
fill = extra_opts.pop('fill', NOTSET)
expected_num_elements = len(names)
val = translate_stringlist(val)
for idx, item in enumerate(val):
if not isinstance(item, dict):
elements = [x.strip() for x in item.split(':')]
num_elements = len(elements)
if num_elements < expected_num_elements:
if fill is NOTSET:
raise SaltInvocationError(
'\'{0}\' contains {1} value(s) (expected {2})'.format(
item, num_elements, expected_num_elements
)
)
elements.extend([fill] * (expected_num_elements - num_elements))
elif num_elements > expected_num_elements:
raise SaltInvocationError(
'\'{0}\' contains {1} value(s) (expected {2})'.format(
item,
num_elements,
expected_num_elements if fill is NOTSET
else 'up to {0}'.format(expected_num_elements)
)
)
val[idx] = dict(zip(names, elements))
return val | python | def map_vals(val, *names, **extra_opts):
'''
Many arguments come in as a list of VAL1:VAL2 pairs, but map to a list
of dicts in the format {NAME1: VAL1, NAME2: VAL2}. This function
provides common code to handle these instances.
'''
fill = extra_opts.pop('fill', NOTSET)
expected_num_elements = len(names)
val = translate_stringlist(val)
for idx, item in enumerate(val):
if not isinstance(item, dict):
elements = [x.strip() for x in item.split(':')]
num_elements = len(elements)
if num_elements < expected_num_elements:
if fill is NOTSET:
raise SaltInvocationError(
'\'{0}\' contains {1} value(s) (expected {2})'.format(
item, num_elements, expected_num_elements
)
)
elements.extend([fill] * (expected_num_elements - num_elements))
elif num_elements > expected_num_elements:
raise SaltInvocationError(
'\'{0}\' contains {1} value(s) (expected {2})'.format(
item,
num_elements,
expected_num_elements if fill is NOTSET
else 'up to {0}'.format(expected_num_elements)
)
)
val[idx] = dict(zip(names, elements))
return val | [
"def",
"map_vals",
"(",
"val",
",",
"*",
"names",
",",
"*",
"*",
"extra_opts",
")",
":",
"fill",
"=",
"extra_opts",
".",
"pop",
"(",
"'fill'",
",",
"NOTSET",
")",
"expected_num_elements",
"=",
"len",
"(",
"names",
")",
"val",
"=",
"translate_stringlist",... | Many arguments come in as a list of VAL1:VAL2 pairs, but map to a list
of dicts in the format {NAME1: VAL1, NAME2: VAL2}. This function
provides common code to handle these instances. | [
"Many",
"arguments",
"come",
"in",
"as",
"a",
"list",
"of",
"VAL1",
":",
"VAL2",
"pairs",
"but",
"map",
"to",
"a",
"list",
"of",
"dicts",
"in",
"the",
"format",
"{",
"NAME1",
":",
"VAL1",
"NAME2",
":",
"VAL2",
"}",
".",
"This",
"function",
"provides"... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/docker/translate/helpers.py#L96-L127 | train |
saltstack/salt | salt/utils/docker/translate/helpers.py | translate_command | def translate_command(val):
'''
Input should either be a single string, or a list of strings. This is used
for the two args that deal with commands ("command" and "entrypoint").
'''
if isinstance(val, six.string_types):
return val
elif isinstance(val, list):
for idx in range(len(val)):
if not isinstance(val[idx], six.string_types):
val[idx] = six.text_type(val[idx])
else:
# Make sure we have a string
val = six.text_type(val)
return val | python | def translate_command(val):
'''
Input should either be a single string, or a list of strings. This is used
for the two args that deal with commands ("command" and "entrypoint").
'''
if isinstance(val, six.string_types):
return val
elif isinstance(val, list):
for idx in range(len(val)):
if not isinstance(val[idx], six.string_types):
val[idx] = six.text_type(val[idx])
else:
# Make sure we have a string
val = six.text_type(val)
return val | [
"def",
"translate_command",
"(",
"val",
")",
":",
"if",
"isinstance",
"(",
"val",
",",
"six",
".",
"string_types",
")",
":",
"return",
"val",
"elif",
"isinstance",
"(",
"val",
",",
"list",
")",
":",
"for",
"idx",
"in",
"range",
"(",
"len",
"(",
"val"... | Input should either be a single string, or a list of strings. This is used
for the two args that deal with commands ("command" and "entrypoint"). | [
"Input",
"should",
"either",
"be",
"a",
"single",
"string",
"or",
"a",
"list",
"of",
"strings",
".",
"This",
"is",
"used",
"for",
"the",
"two",
"args",
"that",
"deal",
"with",
"commands",
"(",
"command",
"and",
"entrypoint",
")",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/docker/translate/helpers.py#L176-L190 | train |
saltstack/salt | salt/utils/docker/translate/helpers.py | translate_bytes | def translate_bytes(val):
'''
These values can be expressed as an integer number of bytes, or a string
expression (i.e. 100mb, 1gb, etc.).
'''
try:
val = int(val)
except (TypeError, ValueError):
if not isinstance(val, six.string_types):
val = six.text_type(val)
return val | python | def translate_bytes(val):
'''
These values can be expressed as an integer number of bytes, or a string
expression (i.e. 100mb, 1gb, etc.).
'''
try:
val = int(val)
except (TypeError, ValueError):
if not isinstance(val, six.string_types):
val = six.text_type(val)
return val | [
"def",
"translate_bytes",
"(",
"val",
")",
":",
"try",
":",
"val",
"=",
"int",
"(",
"val",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
":",
"if",
"not",
"isinstance",
"(",
"val",
",",
"six",
".",
"string_types",
")",
":",
"val",
"=",
"... | These values can be expressed as an integer number of bytes, or a string
expression (i.e. 100mb, 1gb, etc.). | [
"These",
"values",
"can",
"be",
"expressed",
"as",
"an",
"integer",
"number",
"of",
"bytes",
"or",
"a",
"string",
"expression",
"(",
"i",
".",
"e",
".",
"100mb",
"1gb",
"etc",
".",
")",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/docker/translate/helpers.py#L193-L203 | train |
saltstack/salt | salt/utils/docker/translate/helpers.py | translate_stringlist | def translate_stringlist(val):
'''
On the CLI, these are passed as multiple instances of a given CLI option.
In Salt, we accept these as a comma-delimited list but the API expects a
Python list. This function accepts input and returns it back as a Python
list of strings. If the input is a string which is a comma-separated list
of items, split that string and return it.
'''
if not isinstance(val, list):
try:
val = split(val)
except AttributeError:
val = split(six.text_type(val))
for idx in range(len(val)):
if not isinstance(val[idx], six.string_types):
val[idx] = six.text_type(val[idx])
return val | python | def translate_stringlist(val):
'''
On the CLI, these are passed as multiple instances of a given CLI option.
In Salt, we accept these as a comma-delimited list but the API expects a
Python list. This function accepts input and returns it back as a Python
list of strings. If the input is a string which is a comma-separated list
of items, split that string and return it.
'''
if not isinstance(val, list):
try:
val = split(val)
except AttributeError:
val = split(six.text_type(val))
for idx in range(len(val)):
if not isinstance(val[idx], six.string_types):
val[idx] = six.text_type(val[idx])
return val | [
"def",
"translate_stringlist",
"(",
"val",
")",
":",
"if",
"not",
"isinstance",
"(",
"val",
",",
"list",
")",
":",
"try",
":",
"val",
"=",
"split",
"(",
"val",
")",
"except",
"AttributeError",
":",
"val",
"=",
"split",
"(",
"six",
".",
"text_type",
"... | On the CLI, these are passed as multiple instances of a given CLI option.
In Salt, we accept these as a comma-delimited list but the API expects a
Python list. This function accepts input and returns it back as a Python
list of strings. If the input is a string which is a comma-separated list
of items, split that string and return it. | [
"On",
"the",
"CLI",
"these",
"are",
"passed",
"as",
"multiple",
"instances",
"of",
"a",
"given",
"CLI",
"option",
".",
"In",
"Salt",
"we",
"accept",
"these",
"as",
"a",
"comma",
"-",
"delimited",
"list",
"but",
"the",
"API",
"expects",
"a",
"Python",
"... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/docker/translate/helpers.py#L206-L222 | train |
saltstack/salt | salt/utils/docker/translate/helpers.py | translate_device_rates | def translate_device_rates(val, numeric_rate=True):
'''
CLI input is a list of PATH:RATE pairs, but the API expects a list of
dictionaries in the format [{'Path': path, 'Rate': rate}]
'''
val = map_vals(val, 'Path', 'Rate')
for idx in range(len(val)):
try:
is_abs = os.path.isabs(val[idx]['Path'])
except AttributeError:
is_abs = False
if not is_abs:
raise SaltInvocationError(
'Path \'{Path}\' is not absolute'.format(**val[idx])
)
# Attempt to convert to an integer. Will fail if rate was specified as
# a shorthand (e.g. 1mb), this is OK as we will check to make sure the
# value is an integer below if that is what is required.
try:
val[idx]['Rate'] = int(val[idx]['Rate'])
except (TypeError, ValueError):
pass
if numeric_rate:
try:
val[idx]['Rate'] = int(val[idx]['Rate'])
except ValueError:
raise SaltInvocationError(
'Rate \'{Rate}\' for path \'{Path}\' is '
'non-numeric'.format(**val[idx])
)
return val | python | def translate_device_rates(val, numeric_rate=True):
'''
CLI input is a list of PATH:RATE pairs, but the API expects a list of
dictionaries in the format [{'Path': path, 'Rate': rate}]
'''
val = map_vals(val, 'Path', 'Rate')
for idx in range(len(val)):
try:
is_abs = os.path.isabs(val[idx]['Path'])
except AttributeError:
is_abs = False
if not is_abs:
raise SaltInvocationError(
'Path \'{Path}\' is not absolute'.format(**val[idx])
)
# Attempt to convert to an integer. Will fail if rate was specified as
# a shorthand (e.g. 1mb), this is OK as we will check to make sure the
# value is an integer below if that is what is required.
try:
val[idx]['Rate'] = int(val[idx]['Rate'])
except (TypeError, ValueError):
pass
if numeric_rate:
try:
val[idx]['Rate'] = int(val[idx]['Rate'])
except ValueError:
raise SaltInvocationError(
'Rate \'{Rate}\' for path \'{Path}\' is '
'non-numeric'.format(**val[idx])
)
return val | [
"def",
"translate_device_rates",
"(",
"val",
",",
"numeric_rate",
"=",
"True",
")",
":",
"val",
"=",
"map_vals",
"(",
"val",
",",
"'Path'",
",",
"'Rate'",
")",
"for",
"idx",
"in",
"range",
"(",
"len",
"(",
"val",
")",
")",
":",
"try",
":",
"is_abs",
... | CLI input is a list of PATH:RATE pairs, but the API expects a list of
dictionaries in the format [{'Path': path, 'Rate': rate}] | [
"CLI",
"input",
"is",
"a",
"list",
"of",
"PATH",
":",
"RATE",
"pairs",
"but",
"the",
"API",
"expects",
"a",
"list",
"of",
"dictionaries",
"in",
"the",
"format",
"[",
"{",
"Path",
":",
"path",
"Rate",
":",
"rate",
"}",
"]"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/docker/translate/helpers.py#L225-L257 | train |
saltstack/salt | salt/utils/docker/translate/helpers.py | translate_key_val | def translate_key_val(val, delimiter='='):
'''
CLI input is a list of key/val pairs, but the API expects a dictionary in
the format {key: val}
'''
if isinstance(val, dict):
return val
val = translate_stringlist(val)
new_val = {}
for item in val:
try:
lvalue, rvalue = split(item, delimiter, 1)
except (AttributeError, TypeError, ValueError):
raise SaltInvocationError(
'\'{0}\' is not a key{1}value pair'.format(item, delimiter)
)
new_val[lvalue] = rvalue
return new_val | python | def translate_key_val(val, delimiter='='):
'''
CLI input is a list of key/val pairs, but the API expects a dictionary in
the format {key: val}
'''
if isinstance(val, dict):
return val
val = translate_stringlist(val)
new_val = {}
for item in val:
try:
lvalue, rvalue = split(item, delimiter, 1)
except (AttributeError, TypeError, ValueError):
raise SaltInvocationError(
'\'{0}\' is not a key{1}value pair'.format(item, delimiter)
)
new_val[lvalue] = rvalue
return new_val | [
"def",
"translate_key_val",
"(",
"val",
",",
"delimiter",
"=",
"'='",
")",
":",
"if",
"isinstance",
"(",
"val",
",",
"dict",
")",
":",
"return",
"val",
"val",
"=",
"translate_stringlist",
"(",
"val",
")",
"new_val",
"=",
"{",
"}",
"for",
"item",
"in",
... | CLI input is a list of key/val pairs, but the API expects a dictionary in
the format {key: val} | [
"CLI",
"input",
"is",
"a",
"list",
"of",
"key",
"/",
"val",
"pairs",
"but",
"the",
"API",
"expects",
"a",
"dictionary",
"in",
"the",
"format",
"{",
"key",
":",
"val",
"}"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/docker/translate/helpers.py#L260-L277 | train |
saltstack/salt | salt/utils/docker/translate/helpers.py | translate_labels | def translate_labels(val):
'''
Can either be a list of label names, or a list of name=value pairs. The API
can accept either a list of label names or a dictionary mapping names to
values, so the value we translate will be different depending on the input.
'''
if not isinstance(val, dict):
if not isinstance(val, list):
val = split(val)
new_val = {}
for item in val:
if isinstance(item, dict):
if len(item) != 1:
raise SaltInvocationError('Invalid label(s)')
key = next(iter(item))
val = item[key]
else:
try:
key, val = split(item, '=', 1)
except ValueError:
key = item
val = ''
if not isinstance(key, six.string_types):
key = six.text_type(key)
if not isinstance(val, six.string_types):
val = six.text_type(val)
new_val[key] = val
val = new_val
return val | python | def translate_labels(val):
'''
Can either be a list of label names, or a list of name=value pairs. The API
can accept either a list of label names or a dictionary mapping names to
values, so the value we translate will be different depending on the input.
'''
if not isinstance(val, dict):
if not isinstance(val, list):
val = split(val)
new_val = {}
for item in val:
if isinstance(item, dict):
if len(item) != 1:
raise SaltInvocationError('Invalid label(s)')
key = next(iter(item))
val = item[key]
else:
try:
key, val = split(item, '=', 1)
except ValueError:
key = item
val = ''
if not isinstance(key, six.string_types):
key = six.text_type(key)
if not isinstance(val, six.string_types):
val = six.text_type(val)
new_val[key] = val
val = new_val
return val | [
"def",
"translate_labels",
"(",
"val",
")",
":",
"if",
"not",
"isinstance",
"(",
"val",
",",
"dict",
")",
":",
"if",
"not",
"isinstance",
"(",
"val",
",",
"list",
")",
":",
"val",
"=",
"split",
"(",
"val",
")",
"new_val",
"=",
"{",
"}",
"for",
"i... | Can either be a list of label names, or a list of name=value pairs. The API
can accept either a list of label names or a dictionary mapping names to
values, so the value we translate will be different depending on the input. | [
"Can",
"either",
"be",
"a",
"list",
"of",
"label",
"names",
"or",
"a",
"list",
"of",
"name",
"=",
"value",
"pairs",
".",
"The",
"API",
"can",
"accept",
"either",
"a",
"list",
"of",
"label",
"names",
"or",
"a",
"dictionary",
"mapping",
"names",
"to",
... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/docker/translate/helpers.py#L280-L308 | train |
saltstack/salt | salt/states/firewall.py | check | def check(name, port=None, **kwargs):
'''
Checks if there is an open connection from the minion to the defined
host on a specific port.
name
host name or ip address to test connection to
port
The port to test the connection on
kwargs
Additional parameters, parameters allowed are:
proto (tcp or udp)
family (ipv4 or ipv6)
timeout
.. code-block:: yaml
testgoogle:
firewall.check:
- name: 'google.com'
- port: 80
- proto: 'tcp'
'''
# set name to host as required by the module
host = name
ret = {'name': name,
'result': True,
'changes': {},
'comment': ''}
if 'test' not in kwargs:
kwargs['test'] = __opts__.get('test', False)
# check the connection
if kwargs['test']:
ret['result'] = True
ret['comment'] = 'The connection will be tested'
else:
results = __salt__['network.connect'](host, port, **kwargs)
ret['result'] = results['result']
ret['comment'] = results['comment']
return ret | python | def check(name, port=None, **kwargs):
'''
Checks if there is an open connection from the minion to the defined
host on a specific port.
name
host name or ip address to test connection to
port
The port to test the connection on
kwargs
Additional parameters, parameters allowed are:
proto (tcp or udp)
family (ipv4 or ipv6)
timeout
.. code-block:: yaml
testgoogle:
firewall.check:
- name: 'google.com'
- port: 80
- proto: 'tcp'
'''
# set name to host as required by the module
host = name
ret = {'name': name,
'result': True,
'changes': {},
'comment': ''}
if 'test' not in kwargs:
kwargs['test'] = __opts__.get('test', False)
# check the connection
if kwargs['test']:
ret['result'] = True
ret['comment'] = 'The connection will be tested'
else:
results = __salt__['network.connect'](host, port, **kwargs)
ret['result'] = results['result']
ret['comment'] = results['comment']
return ret | [
"def",
"check",
"(",
"name",
",",
"port",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# set name to host as required by the module",
"host",
"=",
"name",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"True",
",",
"'changes'",
":",
"{... | Checks if there is an open connection from the minion to the defined
host on a specific port.
name
host name or ip address to test connection to
port
The port to test the connection on
kwargs
Additional parameters, parameters allowed are:
proto (tcp or udp)
family (ipv4 or ipv6)
timeout
.. code-block:: yaml
testgoogle:
firewall.check:
- name: 'google.com'
- port: 80
- proto: 'tcp' | [
"Checks",
"if",
"there",
"is",
"an",
"open",
"connection",
"from",
"the",
"minion",
"to",
"the",
"defined",
"host",
"on",
"a",
"specific",
"port",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/firewall.py#L19-L67 | train |
saltstack/salt | salt/states/selinux.py | _refine_mode | def _refine_mode(mode):
'''
Return a mode value that is predictable
'''
mode = six.text_type(mode).lower()
if any([mode.startswith('e'),
mode == '1',
mode == 'on']):
return 'Enforcing'
if any([mode.startswith('p'),
mode == '0',
mode == 'off']):
return 'Permissive'
if any([mode.startswith('d')]):
return 'Disabled'
return 'unknown' | python | def _refine_mode(mode):
'''
Return a mode value that is predictable
'''
mode = six.text_type(mode).lower()
if any([mode.startswith('e'),
mode == '1',
mode == 'on']):
return 'Enforcing'
if any([mode.startswith('p'),
mode == '0',
mode == 'off']):
return 'Permissive'
if any([mode.startswith('d')]):
return 'Disabled'
return 'unknown' | [
"def",
"_refine_mode",
"(",
"mode",
")",
":",
"mode",
"=",
"six",
".",
"text_type",
"(",
"mode",
")",
".",
"lower",
"(",
")",
"if",
"any",
"(",
"[",
"mode",
".",
"startswith",
"(",
"'e'",
")",
",",
"mode",
"==",
"'1'",
",",
"mode",
"==",
"'on'",
... | Return a mode value that is predictable | [
"Return",
"a",
"mode",
"value",
"that",
"is",
"predictable"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/selinux.py#L41-L56 | train |
saltstack/salt | salt/states/selinux.py | mode | def mode(name):
'''
Verifies the mode SELinux is running in, can be set to enforcing,
permissive, or disabled
.. note::
A change to or from disabled mode requires a system reboot. You will
need to perform this yourself.
name
The mode to run SELinux in, permissive, enforcing, or disabled.
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
tmode = _refine_mode(name)
if tmode == 'unknown':
ret['comment'] = '{0} is not an accepted mode'.format(name)
return ret
# Either the current mode in memory or a non-matching config value
# will trigger setenforce
mode = __salt__['selinux.getenforce']()
config = __salt__['selinux.getconfig']()
# Just making sure the oldmode reflects the thing that didn't match tmode
if mode == tmode and mode != config and tmode != config:
mode = config
if mode == tmode:
ret['result'] = True
ret['comment'] = 'SELinux is already in {0} mode'.format(tmode)
return ret
# The mode needs to change...
if __opts__['test']:
ret['comment'] = 'SELinux mode is set to be changed to {0}'.format(
tmode)
ret['result'] = None
ret['changes'] = {'old': mode,
'new': tmode}
return ret
oldmode, mode = mode, __salt__['selinux.setenforce'](tmode)
if mode == tmode or (tmode == 'Disabled' and __salt__['selinux.getconfig']() == tmode):
ret['result'] = True
ret['comment'] = 'SELinux has been set to {0} mode'.format(tmode)
ret['changes'] = {'old': oldmode,
'new': mode}
return ret
ret['comment'] = 'Failed to set SELinux to {0} mode'.format(tmode)
return ret | python | def mode(name):
'''
Verifies the mode SELinux is running in, can be set to enforcing,
permissive, or disabled
.. note::
A change to or from disabled mode requires a system reboot. You will
need to perform this yourself.
name
The mode to run SELinux in, permissive, enforcing, or disabled.
'''
ret = {'name': name,
'result': False,
'comment': '',
'changes': {}}
tmode = _refine_mode(name)
if tmode == 'unknown':
ret['comment'] = '{0} is not an accepted mode'.format(name)
return ret
# Either the current mode in memory or a non-matching config value
# will trigger setenforce
mode = __salt__['selinux.getenforce']()
config = __salt__['selinux.getconfig']()
# Just making sure the oldmode reflects the thing that didn't match tmode
if mode == tmode and mode != config and tmode != config:
mode = config
if mode == tmode:
ret['result'] = True
ret['comment'] = 'SELinux is already in {0} mode'.format(tmode)
return ret
# The mode needs to change...
if __opts__['test']:
ret['comment'] = 'SELinux mode is set to be changed to {0}'.format(
tmode)
ret['result'] = None
ret['changes'] = {'old': mode,
'new': tmode}
return ret
oldmode, mode = mode, __salt__['selinux.setenforce'](tmode)
if mode == tmode or (tmode == 'Disabled' and __salt__['selinux.getconfig']() == tmode):
ret['result'] = True
ret['comment'] = 'SELinux has been set to {0} mode'.format(tmode)
ret['changes'] = {'old': oldmode,
'new': mode}
return ret
ret['comment'] = 'Failed to set SELinux to {0} mode'.format(tmode)
return ret | [
"def",
"mode",
"(",
"name",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"False",
",",
"'comment'",
":",
"''",
",",
"'changes'",
":",
"{",
"}",
"}",
"tmode",
"=",
"_refine_mode",
"(",
"name",
")",
"if",
"tmode",
"==",
"... | Verifies the mode SELinux is running in, can be set to enforcing,
permissive, or disabled
.. note::
A change to or from disabled mode requires a system reboot. You will
need to perform this yourself.
name
The mode to run SELinux in, permissive, enforcing, or disabled. | [
"Verifies",
"the",
"mode",
"SELinux",
"is",
"running",
"in",
"can",
"be",
"set",
"to",
"enforcing",
"permissive",
"or",
"disabled"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/selinux.py#L84-L133 | train |
saltstack/salt | salt/states/selinux.py | boolean | def boolean(name, value, persist=False):
'''
Set up an SELinux boolean
name
The name of the boolean to set
value
The value to set on the boolean
persist
Defaults to False, set persist to true to make the boolean apply on a
reboot
'''
ret = {'name': name,
'result': True,
'comment': '',
'changes': {}}
bools = __salt__['selinux.list_sebool']()
if name not in bools:
ret['comment'] = 'Boolean {0} is not available'.format(name)
ret['result'] = False
return ret
rvalue = _refine_value(value)
if rvalue is None:
ret['comment'] = '{0} is not a valid value for the ' \
'boolean'.format(value)
ret['result'] = False
return ret
state = bools[name]['State'] == rvalue
default = bools[name]['Default'] == rvalue
if persist:
if state and default:
ret['comment'] = 'Boolean is in the correct state'
return ret
else:
if state:
ret['comment'] = 'Boolean is in the correct state'
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Boolean {0} is set to be changed to {1}'.format(
name, rvalue)
return ret
ret['result'] = __salt__['selinux.setsebool'](name, rvalue, persist)
if ret['result']:
ret['comment'] = 'Boolean {0} has been set to {1}'.format(name, rvalue)
ret['changes'].update({'State': {'old': bools[name]['State'],
'new': rvalue}})
if persist and not default:
ret['changes'].update({'Default': {'old': bools[name]['Default'],
'new': rvalue}})
return ret
ret['comment'] = 'Failed to set the boolean {0} to {1}'.format(name, rvalue)
return ret | python | def boolean(name, value, persist=False):
'''
Set up an SELinux boolean
name
The name of the boolean to set
value
The value to set on the boolean
persist
Defaults to False, set persist to true to make the boolean apply on a
reboot
'''
ret = {'name': name,
'result': True,
'comment': '',
'changes': {}}
bools = __salt__['selinux.list_sebool']()
if name not in bools:
ret['comment'] = 'Boolean {0} is not available'.format(name)
ret['result'] = False
return ret
rvalue = _refine_value(value)
if rvalue is None:
ret['comment'] = '{0} is not a valid value for the ' \
'boolean'.format(value)
ret['result'] = False
return ret
state = bools[name]['State'] == rvalue
default = bools[name]['Default'] == rvalue
if persist:
if state and default:
ret['comment'] = 'Boolean is in the correct state'
return ret
else:
if state:
ret['comment'] = 'Boolean is in the correct state'
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Boolean {0} is set to be changed to {1}'.format(
name, rvalue)
return ret
ret['result'] = __salt__['selinux.setsebool'](name, rvalue, persist)
if ret['result']:
ret['comment'] = 'Boolean {0} has been set to {1}'.format(name, rvalue)
ret['changes'].update({'State': {'old': bools[name]['State'],
'new': rvalue}})
if persist and not default:
ret['changes'].update({'Default': {'old': bools[name]['Default'],
'new': rvalue}})
return ret
ret['comment'] = 'Failed to set the boolean {0} to {1}'.format(name, rvalue)
return ret | [
"def",
"boolean",
"(",
"name",
",",
"value",
",",
"persist",
"=",
"False",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",
"''",
",",
"'changes'",
":",
"{",
"}",
"}",
"bools",
"=",
"__salt__",
... | Set up an SELinux boolean
name
The name of the boolean to set
value
The value to set on the boolean
persist
Defaults to False, set persist to true to make the boolean apply on a
reboot | [
"Set",
"up",
"an",
"SELinux",
"boolean"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/selinux.py#L136-L191 | train |
saltstack/salt | salt/states/selinux.py | module | def module(name, module_state='Enabled', version='any', **opts):
'''
Enable/Disable and optionally force a specific version for an SELinux module
name
The name of the module to control
module_state
Should the module be enabled or disabled?
version
Defaults to no preference, set to a specified value if required.
Currently can only alert if the version is incorrect.
install
Setting to True installs module
source
Points to module source file, used only when install is True
remove
Setting to True removes module
.. versionadded:: 2016.3.0
'''
ret = {'name': name,
'result': True,
'comment': '',
'changes': {}}
if opts.get('install', False) and opts.get('remove', False):
ret['result'] = False
ret['comment'] = 'Cannot install and remove at the same time'
return ret
if opts.get('install', False):
module_path = opts.get('source', name)
ret = module_install(module_path)
if not ret['result']:
return ret
elif opts.get('remove', False):
return module_remove(name)
modules = __salt__['selinux.list_semod']()
if name not in modules:
ret['comment'] = 'Module {0} is not available'.format(name)
ret['result'] = False
return ret
rmodule_state = _refine_module_state(module_state)
if rmodule_state == 'unknown':
ret['comment'] = '{0} is not a valid state for the ' \
'{1} module.'.format(module_state, module)
ret['result'] = False
return ret
if version != 'any':
installed_version = modules[name]['Version']
if not installed_version == version:
ret['comment'] = 'Module version is {0} and does not match ' \
'the desired version of {1} or you are ' \
'using semodule >= 2.4'.format(installed_version, version)
ret['result'] = False
return ret
current_module_state = _refine_module_state(modules[name]['Enabled'])
if rmodule_state == current_module_state:
ret['comment'] = 'Module {0} is in the desired state'.format(name)
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Module {0} is set to be toggled to {1}'.format(
name, module_state)
return ret
if __salt__['selinux.setsemod'](name, rmodule_state):
ret['comment'] = 'Module {0} has been set to {1}'.format(name, module_state)
return ret
ret['result'] = False
ret['comment'] = 'Failed to set the Module {0} to {1}'.format(name, module_state)
return ret | python | def module(name, module_state='Enabled', version='any', **opts):
'''
Enable/Disable and optionally force a specific version for an SELinux module
name
The name of the module to control
module_state
Should the module be enabled or disabled?
version
Defaults to no preference, set to a specified value if required.
Currently can only alert if the version is incorrect.
install
Setting to True installs module
source
Points to module source file, used only when install is True
remove
Setting to True removes module
.. versionadded:: 2016.3.0
'''
ret = {'name': name,
'result': True,
'comment': '',
'changes': {}}
if opts.get('install', False) and opts.get('remove', False):
ret['result'] = False
ret['comment'] = 'Cannot install and remove at the same time'
return ret
if opts.get('install', False):
module_path = opts.get('source', name)
ret = module_install(module_path)
if not ret['result']:
return ret
elif opts.get('remove', False):
return module_remove(name)
modules = __salt__['selinux.list_semod']()
if name not in modules:
ret['comment'] = 'Module {0} is not available'.format(name)
ret['result'] = False
return ret
rmodule_state = _refine_module_state(module_state)
if rmodule_state == 'unknown':
ret['comment'] = '{0} is not a valid state for the ' \
'{1} module.'.format(module_state, module)
ret['result'] = False
return ret
if version != 'any':
installed_version = modules[name]['Version']
if not installed_version == version:
ret['comment'] = 'Module version is {0} and does not match ' \
'the desired version of {1} or you are ' \
'using semodule >= 2.4'.format(installed_version, version)
ret['result'] = False
return ret
current_module_state = _refine_module_state(modules[name]['Enabled'])
if rmodule_state == current_module_state:
ret['comment'] = 'Module {0} is in the desired state'.format(name)
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Module {0} is set to be toggled to {1}'.format(
name, module_state)
return ret
if __salt__['selinux.setsemod'](name, rmodule_state):
ret['comment'] = 'Module {0} has been set to {1}'.format(name, module_state)
return ret
ret['result'] = False
ret['comment'] = 'Failed to set the Module {0} to {1}'.format(name, module_state)
return ret | [
"def",
"module",
"(",
"name",
",",
"module_state",
"=",
"'Enabled'",
",",
"version",
"=",
"'any'",
",",
"*",
"*",
"opts",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",
"''",
",",
"'changes'",
... | Enable/Disable and optionally force a specific version for an SELinux module
name
The name of the module to control
module_state
Should the module be enabled or disabled?
version
Defaults to no preference, set to a specified value if required.
Currently can only alert if the version is incorrect.
install
Setting to True installs module
source
Points to module source file, used only when install is True
remove
Setting to True removes module
.. versionadded:: 2016.3.0 | [
"Enable",
"/",
"Disable",
"and",
"optionally",
"force",
"a",
"specific",
"version",
"for",
"an",
"SELinux",
"module"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/selinux.py#L194-L268 | train |
saltstack/salt | salt/states/selinux.py | module_install | def module_install(name):
'''
Installs custom SELinux module from given file
name
Path to file with module to install
.. versionadded:: 2016.11.6
'''
ret = {'name': name,
'result': True,
'comment': '',
'changes': {}}
if __salt__['selinux.install_semod'](name):
ret['comment'] = 'Module {0} has been installed'.format(name)
return ret
ret['result'] = False
ret['comment'] = 'Failed to install module {0}'.format(name)
return ret | python | def module_install(name):
'''
Installs custom SELinux module from given file
name
Path to file with module to install
.. versionadded:: 2016.11.6
'''
ret = {'name': name,
'result': True,
'comment': '',
'changes': {}}
if __salt__['selinux.install_semod'](name):
ret['comment'] = 'Module {0} has been installed'.format(name)
return ret
ret['result'] = False
ret['comment'] = 'Failed to install module {0}'.format(name)
return ret | [
"def",
"module_install",
"(",
"name",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",
"''",
",",
"'changes'",
":",
"{",
"}",
"}",
"if",
"__salt__",
"[",
"'selinux.install_semod'",
"]",
"(",
"name",... | Installs custom SELinux module from given file
name
Path to file with module to install
.. versionadded:: 2016.11.6 | [
"Installs",
"custom",
"SELinux",
"module",
"from",
"given",
"file"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/selinux.py#L271-L289 | train |
saltstack/salt | salt/states/selinux.py | module_remove | def module_remove(name):
'''
Removes SELinux module
name
The name of the module to remove
.. versionadded:: 2016.11.6
'''
ret = {'name': name,
'result': True,
'comment': '',
'changes': {}}
modules = __salt__['selinux.list_semod']()
if name not in modules:
ret['comment'] = 'Module {0} is not available'.format(name)
ret['result'] = False
return ret
if __salt__['selinux.remove_semod'](name):
ret['comment'] = 'Module {0} has been removed'.format(name)
return ret
ret['result'] = False
ret['comment'] = 'Failed to remove module {0}'.format(name)
return ret | python | def module_remove(name):
'''
Removes SELinux module
name
The name of the module to remove
.. versionadded:: 2016.11.6
'''
ret = {'name': name,
'result': True,
'comment': '',
'changes': {}}
modules = __salt__['selinux.list_semod']()
if name not in modules:
ret['comment'] = 'Module {0} is not available'.format(name)
ret['result'] = False
return ret
if __salt__['selinux.remove_semod'](name):
ret['comment'] = 'Module {0} has been removed'.format(name)
return ret
ret['result'] = False
ret['comment'] = 'Failed to remove module {0}'.format(name)
return ret | [
"def",
"module_remove",
"(",
"name",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",
"''",
",",
"'changes'",
":",
"{",
"}",
"}",
"modules",
"=",
"__salt__",
"[",
"'selinux.list_semod'",
"]",
"(",
... | Removes SELinux module
name
The name of the module to remove
.. versionadded:: 2016.11.6 | [
"Removes",
"SELinux",
"module"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/selinux.py#L292-L315 | train |
saltstack/salt | salt/states/selinux.py | fcontext_policy_present | def fcontext_policy_present(name, sel_type, filetype='a', sel_user=None, sel_level=None):
'''
.. versionadded:: 2017.7.0
Makes sure a SELinux policy for a given filespec (name), filetype
and SELinux context type is present.
name
filespec of the file or directory. Regex syntax is allowed.
sel_type
SELinux context type. There are many.
filetype
The SELinux filetype specification. Use one of [a, f, d, c, b,
s, l, p]. See also `man semanage-fcontext`. Defaults to 'a'
(all files).
sel_user
The SELinux user.
sel_level
The SELinux MLS range.
'''
ret = {'name': name, 'result': False, 'changes': {}, 'comment': ''}
new_state = {}
old_state = {}
filetype_str = __salt__['selinux.filetype_id_to_string'](filetype)
current_state = __salt__['selinux.fcontext_get_policy'](
name=name,
filetype=filetype,
sel_type=sel_type,
sel_user=sel_user,
sel_level=sel_level)
if not current_state:
new_state = {name: {'filetype': filetype_str, 'sel_type': sel_type}}
if __opts__['test']:
ret.update({'result': None})
else:
add_ret = __salt__['selinux.fcontext_add_policy'](
name=name,
filetype=filetype,
sel_type=sel_type,
sel_user=sel_user,
sel_level=sel_level)
if add_ret['retcode'] != 0:
ret.update({'comment': 'Error adding new rule: {0}'.format(add_ret)})
else:
ret.update({'result': True})
else:
if current_state['sel_type'] != sel_type:
old_state.update({name: {'sel_type': current_state['sel_type']}})
new_state.update({name: {'sel_type': sel_type}})
else:
ret.update({'result': True,
'comment': 'SELinux policy for "{0}" already present '.format(name) +
'with specified filetype "{0}" and sel_type "{1}".'.format(
filetype_str,
sel_type)})
return ret
# Removal of current rule is not neccesary, since adding a new rule for the same
# filespec and the same filetype automatically overwrites
if __opts__['test']:
ret.update({'result': None})
else:
change_ret = __salt__['selinux.fcontext_add_policy'](
name=name,
filetype=filetype,
sel_type=sel_type,
sel_user=sel_user,
sel_level=sel_level)
if change_ret['retcode'] != 0:
ret.update({'comment': 'Error adding new rule: {0}'.format(change_ret)})
else:
ret.update({'result': True})
if ret['result'] and (new_state or old_state):
ret['changes'].update({'old': old_state, 'new': new_state})
return ret | python | def fcontext_policy_present(name, sel_type, filetype='a', sel_user=None, sel_level=None):
'''
.. versionadded:: 2017.7.0
Makes sure a SELinux policy for a given filespec (name), filetype
and SELinux context type is present.
name
filespec of the file or directory. Regex syntax is allowed.
sel_type
SELinux context type. There are many.
filetype
The SELinux filetype specification. Use one of [a, f, d, c, b,
s, l, p]. See also `man semanage-fcontext`. Defaults to 'a'
(all files).
sel_user
The SELinux user.
sel_level
The SELinux MLS range.
'''
ret = {'name': name, 'result': False, 'changes': {}, 'comment': ''}
new_state = {}
old_state = {}
filetype_str = __salt__['selinux.filetype_id_to_string'](filetype)
current_state = __salt__['selinux.fcontext_get_policy'](
name=name,
filetype=filetype,
sel_type=sel_type,
sel_user=sel_user,
sel_level=sel_level)
if not current_state:
new_state = {name: {'filetype': filetype_str, 'sel_type': sel_type}}
if __opts__['test']:
ret.update({'result': None})
else:
add_ret = __salt__['selinux.fcontext_add_policy'](
name=name,
filetype=filetype,
sel_type=sel_type,
sel_user=sel_user,
sel_level=sel_level)
if add_ret['retcode'] != 0:
ret.update({'comment': 'Error adding new rule: {0}'.format(add_ret)})
else:
ret.update({'result': True})
else:
if current_state['sel_type'] != sel_type:
old_state.update({name: {'sel_type': current_state['sel_type']}})
new_state.update({name: {'sel_type': sel_type}})
else:
ret.update({'result': True,
'comment': 'SELinux policy for "{0}" already present '.format(name) +
'with specified filetype "{0}" and sel_type "{1}".'.format(
filetype_str,
sel_type)})
return ret
# Removal of current rule is not neccesary, since adding a new rule for the same
# filespec and the same filetype automatically overwrites
if __opts__['test']:
ret.update({'result': None})
else:
change_ret = __salt__['selinux.fcontext_add_policy'](
name=name,
filetype=filetype,
sel_type=sel_type,
sel_user=sel_user,
sel_level=sel_level)
if change_ret['retcode'] != 0:
ret.update({'comment': 'Error adding new rule: {0}'.format(change_ret)})
else:
ret.update({'result': True})
if ret['result'] and (new_state or old_state):
ret['changes'].update({'old': old_state, 'new': new_state})
return ret | [
"def",
"fcontext_policy_present",
"(",
"name",
",",
"sel_type",
",",
"filetype",
"=",
"'a'",
",",
"sel_user",
"=",
"None",
",",
"sel_level",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"False",
",",
"'changes'",
... | .. versionadded:: 2017.7.0
Makes sure a SELinux policy for a given filespec (name), filetype
and SELinux context type is present.
name
filespec of the file or directory. Regex syntax is allowed.
sel_type
SELinux context type. There are many.
filetype
The SELinux filetype specification. Use one of [a, f, d, c, b,
s, l, p]. See also `man semanage-fcontext`. Defaults to 'a'
(all files).
sel_user
The SELinux user.
sel_level
The SELinux MLS range. | [
"..",
"versionadded",
"::",
"2017",
".",
"7",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/selinux.py#L318-L396 | train |
saltstack/salt | salt/states/selinux.py | fcontext_policy_absent | def fcontext_policy_absent(name, filetype='a', sel_type=None, sel_user=None, sel_level=None):
'''
.. versionadded:: 2017.7.0
Makes sure an SELinux file context policy for a given filespec
(name), filetype and SELinux context type is absent.
name
filespec of the file or directory. Regex syntax is allowed.
filetype
The SELinux filetype specification. Use one of [a, f, d, c, b,
s, l, p]. See also `man semanage-fcontext`. Defaults to 'a'
(all files).
sel_type
The SELinux context type. There are many.
sel_user
The SELinux user.
sel_level
The SELinux MLS range.
'''
ret = {'name': name, 'result': False, 'changes': {}, 'comment': ''}
new_state = {}
old_state = {}
current_state = __salt__['selinux.fcontext_get_policy'](
name=name,
filetype=filetype,
sel_type=sel_type,
sel_user=sel_user,
sel_level=sel_level)
if not current_state:
ret.update({'result': True,
'comment': 'SELinux policy for "{0}" already absent '.format(name) +
'with specified filetype "{0}" and sel_type "{1}".'.format(
filetype,
sel_type)})
return ret
else:
old_state.update({name: current_state})
ret['changes'].update({'old': old_state, 'new': new_state})
if __opts__['test']:
ret.update({'result': None})
else:
remove_ret = __salt__['selinux.fcontext_delete_policy'](
name=name,
filetype=filetype,
sel_type=sel_type or current_state['sel_type'],
sel_user=sel_user,
sel_level=sel_level)
if remove_ret['retcode'] != 0:
ret.update({'comment': 'Error removing policy: {0}'.format(remove_ret)})
else:
ret.update({'result': True})
return ret | python | def fcontext_policy_absent(name, filetype='a', sel_type=None, sel_user=None, sel_level=None):
'''
.. versionadded:: 2017.7.0
Makes sure an SELinux file context policy for a given filespec
(name), filetype and SELinux context type is absent.
name
filespec of the file or directory. Regex syntax is allowed.
filetype
The SELinux filetype specification. Use one of [a, f, d, c, b,
s, l, p]. See also `man semanage-fcontext`. Defaults to 'a'
(all files).
sel_type
The SELinux context type. There are many.
sel_user
The SELinux user.
sel_level
The SELinux MLS range.
'''
ret = {'name': name, 'result': False, 'changes': {}, 'comment': ''}
new_state = {}
old_state = {}
current_state = __salt__['selinux.fcontext_get_policy'](
name=name,
filetype=filetype,
sel_type=sel_type,
sel_user=sel_user,
sel_level=sel_level)
if not current_state:
ret.update({'result': True,
'comment': 'SELinux policy for "{0}" already absent '.format(name) +
'with specified filetype "{0}" and sel_type "{1}".'.format(
filetype,
sel_type)})
return ret
else:
old_state.update({name: current_state})
ret['changes'].update({'old': old_state, 'new': new_state})
if __opts__['test']:
ret.update({'result': None})
else:
remove_ret = __salt__['selinux.fcontext_delete_policy'](
name=name,
filetype=filetype,
sel_type=sel_type or current_state['sel_type'],
sel_user=sel_user,
sel_level=sel_level)
if remove_ret['retcode'] != 0:
ret.update({'comment': 'Error removing policy: {0}'.format(remove_ret)})
else:
ret.update({'result': True})
return ret | [
"def",
"fcontext_policy_absent",
"(",
"name",
",",
"filetype",
"=",
"'a'",
",",
"sel_type",
"=",
"None",
",",
"sel_user",
"=",
"None",
",",
"sel_level",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"False",
",",
... | .. versionadded:: 2017.7.0
Makes sure an SELinux file context policy for a given filespec
(name), filetype and SELinux context type is absent.
name
filespec of the file or directory. Regex syntax is allowed.
filetype
The SELinux filetype specification. Use one of [a, f, d, c, b,
s, l, p]. See also `man semanage-fcontext`. Defaults to 'a'
(all files).
sel_type
The SELinux context type. There are many.
sel_user
The SELinux user.
sel_level
The SELinux MLS range. | [
"..",
"versionadded",
"::",
"2017",
".",
"7",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/selinux.py#L399-L455 | train |
saltstack/salt | salt/states/selinux.py | fcontext_policy_applied | def fcontext_policy_applied(name, recursive=False):
'''
.. versionadded:: 2017.7.0
Checks and makes sure the SELinux policies for a given filespec are
applied.
'''
ret = {'name': name, 'result': False, 'changes': {}, 'comment': ''}
changes_text = __salt__['selinux.fcontext_policy_is_applied'](name, recursive)
if changes_text == '':
ret.update({'result': True,
'comment': 'SElinux policies are already applied for filespec "{0}"'.format(name)})
return ret
if __opts__['test']:
ret.update({'result': None})
else:
apply_ret = __salt__['selinux.fcontext_apply_policy'](name, recursive)
if apply_ret['retcode'] != 0:
ret.update({'comment': apply_ret})
else:
ret.update({'result': True})
ret.update({'changes': apply_ret.get('changes')})
return ret | python | def fcontext_policy_applied(name, recursive=False):
'''
.. versionadded:: 2017.7.0
Checks and makes sure the SELinux policies for a given filespec are
applied.
'''
ret = {'name': name, 'result': False, 'changes': {}, 'comment': ''}
changes_text = __salt__['selinux.fcontext_policy_is_applied'](name, recursive)
if changes_text == '':
ret.update({'result': True,
'comment': 'SElinux policies are already applied for filespec "{0}"'.format(name)})
return ret
if __opts__['test']:
ret.update({'result': None})
else:
apply_ret = __salt__['selinux.fcontext_apply_policy'](name, recursive)
if apply_ret['retcode'] != 0:
ret.update({'comment': apply_ret})
else:
ret.update({'result': True})
ret.update({'changes': apply_ret.get('changes')})
return ret | [
"def",
"fcontext_policy_applied",
"(",
"name",
",",
"recursive",
"=",
"False",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"False",
",",
"'changes'",
":",
"{",
"}",
",",
"'comment'",
":",
"''",
"}",
"changes_text",
"=",
"__s... | .. versionadded:: 2017.7.0
Checks and makes sure the SELinux policies for a given filespec are
applied. | [
"..",
"versionadded",
"::",
"2017",
".",
"7",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/selinux.py#L458-L481 | train |
saltstack/salt | salt/states/selinux.py | port_policy_present | def port_policy_present(name, sel_type, protocol=None, port=None, sel_range=None):
'''
.. versionadded:: 2019.2.0
Makes sure an SELinux port policy for a given port, protocol and SELinux context type is present.
name
The protocol and port spec. Can be formatted as ``(tcp|udp)/(port|port-range)``.
sel_type
The SELinux Type.
protocol
The protocol for the port, ``tcp`` or ``udp``. Required if name is not formatted.
port
The port or port range. Required if name is not formatted.
sel_range
The SELinux MLS/MCS Security Range.
'''
ret = {'name': name, 'result': False, 'changes': {}, 'comment': ''}
old_state = __salt__['selinux.port_get_policy'](
name=name,
sel_type=sel_type,
protocol=protocol,
port=port, )
if old_state:
ret.update({'result': True,
'comment': 'SELinux policy for "{0}" already present '.format(name) +
'with specified sel_type "{0}", protocol "{1}" and port "{2}".'.format(
sel_type, protocol, port)})
return ret
if __opts__['test']:
ret.update({'result': None})
else:
add_ret = __salt__['selinux.port_add_policy'](
name=name,
sel_type=sel_type,
protocol=protocol,
port=port,
sel_range=sel_range, )
if add_ret['retcode'] != 0:
ret.update({'comment': 'Error adding new policy: {0}'.format(add_ret)})
else:
ret.update({'result': True})
new_state = __salt__['selinux.port_get_policy'](
name=name,
sel_type=sel_type,
protocol=protocol,
port=port, )
ret['changes'].update({'old': old_state, 'new': new_state})
return ret | python | def port_policy_present(name, sel_type, protocol=None, port=None, sel_range=None):
'''
.. versionadded:: 2019.2.0
Makes sure an SELinux port policy for a given port, protocol and SELinux context type is present.
name
The protocol and port spec. Can be formatted as ``(tcp|udp)/(port|port-range)``.
sel_type
The SELinux Type.
protocol
The protocol for the port, ``tcp`` or ``udp``. Required if name is not formatted.
port
The port or port range. Required if name is not formatted.
sel_range
The SELinux MLS/MCS Security Range.
'''
ret = {'name': name, 'result': False, 'changes': {}, 'comment': ''}
old_state = __salt__['selinux.port_get_policy'](
name=name,
sel_type=sel_type,
protocol=protocol,
port=port, )
if old_state:
ret.update({'result': True,
'comment': 'SELinux policy for "{0}" already present '.format(name) +
'with specified sel_type "{0}", protocol "{1}" and port "{2}".'.format(
sel_type, protocol, port)})
return ret
if __opts__['test']:
ret.update({'result': None})
else:
add_ret = __salt__['selinux.port_add_policy'](
name=name,
sel_type=sel_type,
protocol=protocol,
port=port,
sel_range=sel_range, )
if add_ret['retcode'] != 0:
ret.update({'comment': 'Error adding new policy: {0}'.format(add_ret)})
else:
ret.update({'result': True})
new_state = __salt__['selinux.port_get_policy'](
name=name,
sel_type=sel_type,
protocol=protocol,
port=port, )
ret['changes'].update({'old': old_state, 'new': new_state})
return ret | [
"def",
"port_policy_present",
"(",
"name",
",",
"sel_type",
",",
"protocol",
"=",
"None",
",",
"port",
"=",
"None",
",",
"sel_range",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"False",
",",
"'changes'",
":",
... | .. versionadded:: 2019.2.0
Makes sure an SELinux port policy for a given port, protocol and SELinux context type is present.
name
The protocol and port spec. Can be formatted as ``(tcp|udp)/(port|port-range)``.
sel_type
The SELinux Type.
protocol
The protocol for the port, ``tcp`` or ``udp``. Required if name is not formatted.
port
The port or port range. Required if name is not formatted.
sel_range
The SELinux MLS/MCS Security Range. | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/selinux.py#L484-L536 | train |
saltstack/salt | salt/states/selinux.py | port_policy_absent | def port_policy_absent(name, sel_type=None, protocol=None, port=None):
'''
.. versionadded:: 2019.2.0
Makes sure an SELinux port policy for a given port, protocol and SELinux context type is absent.
name
The protocol and port spec. Can be formatted as ``(tcp|udp)/(port|port-range)``.
sel_type
The SELinux Type. Optional; can be used in determining if policy is present,
ignored by ``semanage port --delete``.
protocol
The protocol for the port, ``tcp`` or ``udp``. Required if name is not formatted.
port
The port or port range. Required if name is not formatted.
'''
ret = {'name': name, 'result': False, 'changes': {}, 'comment': ''}
old_state = __salt__['selinux.port_get_policy'](
name=name,
sel_type=sel_type,
protocol=protocol,
port=port, )
if not old_state:
ret.update({'result': True,
'comment': 'SELinux policy for "{0}" already absent '.format(name) +
'with specified sel_type "{0}", protocol "{1}" and port "{2}".'.format(
sel_type, protocol, port)})
return ret
if __opts__['test']:
ret.update({'result': None})
else:
delete_ret = __salt__['selinux.port_delete_policy'](
name=name,
protocol=protocol,
port=port, )
if delete_ret['retcode'] != 0:
ret.update({'comment': 'Error deleting policy: {0}'.format(delete_ret)})
else:
ret.update({'result': True})
new_state = __salt__['selinux.port_get_policy'](
name=name,
sel_type=sel_type,
protocol=protocol,
port=port, )
ret['changes'].update({'old': old_state, 'new': new_state})
return ret | python | def port_policy_absent(name, sel_type=None, protocol=None, port=None):
'''
.. versionadded:: 2019.2.0
Makes sure an SELinux port policy for a given port, protocol and SELinux context type is absent.
name
The protocol and port spec. Can be formatted as ``(tcp|udp)/(port|port-range)``.
sel_type
The SELinux Type. Optional; can be used in determining if policy is present,
ignored by ``semanage port --delete``.
protocol
The protocol for the port, ``tcp`` or ``udp``. Required if name is not formatted.
port
The port or port range. Required if name is not formatted.
'''
ret = {'name': name, 'result': False, 'changes': {}, 'comment': ''}
old_state = __salt__['selinux.port_get_policy'](
name=name,
sel_type=sel_type,
protocol=protocol,
port=port, )
if not old_state:
ret.update({'result': True,
'comment': 'SELinux policy for "{0}" already absent '.format(name) +
'with specified sel_type "{0}", protocol "{1}" and port "{2}".'.format(
sel_type, protocol, port)})
return ret
if __opts__['test']:
ret.update({'result': None})
else:
delete_ret = __salt__['selinux.port_delete_policy'](
name=name,
protocol=protocol,
port=port, )
if delete_ret['retcode'] != 0:
ret.update({'comment': 'Error deleting policy: {0}'.format(delete_ret)})
else:
ret.update({'result': True})
new_state = __salt__['selinux.port_get_policy'](
name=name,
sel_type=sel_type,
protocol=protocol,
port=port, )
ret['changes'].update({'old': old_state, 'new': new_state})
return ret | [
"def",
"port_policy_absent",
"(",
"name",
",",
"sel_type",
"=",
"None",
",",
"protocol",
"=",
"None",
",",
"port",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"False",
",",
"'changes'",
":",
"{",
"}",
",",
"... | .. versionadded:: 2019.2.0
Makes sure an SELinux port policy for a given port, protocol and SELinux context type is absent.
name
The protocol and port spec. Can be formatted as ``(tcp|udp)/(port|port-range)``.
sel_type
The SELinux Type. Optional; can be used in determining if policy is present,
ignored by ``semanage port --delete``.
protocol
The protocol for the port, ``tcp`` or ``udp``. Required if name is not formatted.
port
The port or port range. Required if name is not formatted. | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/selinux.py#L539-L587 | train |
saltstack/salt | salt/states/openstack_config.py | present | def present(name, filename, section, value, parameter=None):
'''
Ensure a value is set in an OpenStack configuration file.
filename
The full path to the configuration file
section
The section in which the parameter will be set
parameter (optional)
The parameter to change. If the parameter is not supplied, the name will be used as the parameter.
value
The value to set
'''
if parameter is None:
parameter = name
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
try:
old_value = __salt__['openstack_config.get'](filename=filename,
section=section,
parameter=parameter)
if old_value == value:
ret['result'] = True
ret['comment'] = 'The value is already set to the correct value'
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Value \'{0}\' is set to be changed to \'{1}\'.'.format(
old_value,
value
)
return ret
except CommandExecutionError as err:
if not six.text_type(err).lower().startswith('parameter not found:'):
raise
__salt__['openstack_config.set'](filename=filename,
section=section,
parameter=parameter,
value=value)
ret['changes'] = {'Value': 'Updated'}
ret['result'] = True
ret['comment'] = 'The value has been updated'
return ret | python | def present(name, filename, section, value, parameter=None):
'''
Ensure a value is set in an OpenStack configuration file.
filename
The full path to the configuration file
section
The section in which the parameter will be set
parameter (optional)
The parameter to change. If the parameter is not supplied, the name will be used as the parameter.
value
The value to set
'''
if parameter is None:
parameter = name
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
try:
old_value = __salt__['openstack_config.get'](filename=filename,
section=section,
parameter=parameter)
if old_value == value:
ret['result'] = True
ret['comment'] = 'The value is already set to the correct value'
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Value \'{0}\' is set to be changed to \'{1}\'.'.format(
old_value,
value
)
return ret
except CommandExecutionError as err:
if not six.text_type(err).lower().startswith('parameter not found:'):
raise
__salt__['openstack_config.set'](filename=filename,
section=section,
parameter=parameter,
value=value)
ret['changes'] = {'Value': 'Updated'}
ret['result'] = True
ret['comment'] = 'The value has been updated'
return ret | [
"def",
"present",
"(",
"name",
",",
"filename",
",",
"section",
",",
"value",
",",
"parameter",
"=",
"None",
")",
":",
"if",
"parameter",
"is",
"None",
":",
"parameter",
"=",
"name",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",... | Ensure a value is set in an OpenStack configuration file.
filename
The full path to the configuration file
section
The section in which the parameter will be set
parameter (optional)
The parameter to change. If the parameter is not supplied, the name will be used as the parameter.
value
The value to set | [
"Ensure",
"a",
"value",
"is",
"set",
"in",
"an",
"OpenStack",
"configuration",
"file",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/openstack_config.py#L33-L90 | train |
saltstack/salt | salt/states/azurearm_compute.py | availability_set_present | def availability_set_present(name, resource_group, tags=None, platform_update_domain_count=None,
platform_fault_domain_count=None, virtual_machines=None, sku=None, connection_auth=None,
**kwargs):
'''
.. versionadded:: 2019.2.0
Ensure an availability set exists.
:param name:
Name of the availability set.
:param resource_group:
The resource group assigned to the availability set.
:param tags:
A dictionary of strings can be passed as tag metadata to the availability set object.
:param platform_update_domain_count:
An optional parameter which indicates groups of virtual machines and underlying physical hardware that can be
rebooted at the same time.
:param platform_fault_domain_count:
An optional parameter which defines the group of virtual machines that share a common power source and network
switch.
:param virtual_machines:
A list of names of existing virtual machines to be included in the availability set.
:param sku:
The availability set SKU, which specifies whether the availability set is managed or not. Possible values are
'Aligned' or 'Classic'. An 'Aligned' availability set is managed, 'Classic' is not.
:param connection_auth:
A dict with subscription and authentication parameters to be used in connecting to the
Azure Resource Manager API.
Example usage:
.. code-block:: yaml
Ensure availability set exists:
azurearm_compute.availability_set_present:
- name: aset1
- resource_group: group1
- platform_update_domain_count: 5
- platform_fault_domain_count: 3
- sku: aligned
- tags:
contact_name: Elmer Fudd Gantry
- connection_auth: {{ profile }}
- require:
- azurearm_resource: Ensure resource group exists
'''
ret = {
'name': name,
'result': False,
'comment': '',
'changes': {}
}
if not isinstance(connection_auth, dict):
ret['comment'] = 'Connection information must be specified via connection_auth dictionary!'
return ret
if sku:
sku = {'name': sku.capitalize()}
aset = __salt__['azurearm_compute.availability_set_get'](
name,
resource_group,
azurearm_log_level='info',
**connection_auth
)
if 'error' not in aset:
tag_changes = __utils__['dictdiffer.deep_diff'](aset.get('tags', {}), tags or {})
if tag_changes:
ret['changes']['tags'] = tag_changes
if platform_update_domain_count and (int(platform_update_domain_count) != aset.get('platform_update_domain_count')):
ret['changes']['platform_update_domain_count'] = {
'old': aset.get('platform_update_domain_count'),
'new': platform_update_domain_count
}
if platform_fault_domain_count and (int(platform_fault_domain_count) != aset.get('platform_fault_domain_count')):
ret['changes']['platform_fault_domain_count'] = {
'old': aset.get('platform_fault_domain_count'),
'new': platform_fault_domain_count
}
if sku and (sku['name'] != aset.get('sku', {}).get('name')):
ret['changes']['sku'] = {
'old': aset.get('sku'),
'new': sku
}
if virtual_machines:
if not isinstance(virtual_machines, list):
ret['comment'] = 'Virtual machines must be supplied as a list!'
return ret
aset_vms = aset.get('virtual_machines', [])
remote_vms = sorted([vm['id'].split('/')[-1].lower() for vm in aset_vms if 'id' in aset_vms])
local_vms = sorted([vm.lower() for vm in virtual_machines or []])
if local_vms != remote_vms:
ret['changes']['virtual_machines'] = {
'old': aset_vms,
'new': virtual_machines
}
if not ret['changes']:
ret['result'] = True
ret['comment'] = 'Availability set {0} is already present.'.format(name)
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Availability set {0} would be updated.'.format(name)
return ret
else:
ret['changes'] = {
'old': {},
'new': {
'name': name,
'virtual_machines': virtual_machines,
'platform_update_domain_count': platform_update_domain_count,
'platform_fault_domain_count': platform_fault_domain_count,
'sku': sku,
'tags': tags
}
}
if __opts__['test']:
ret['comment'] = 'Availability set {0} would be created.'.format(name)
ret['result'] = None
return ret
aset_kwargs = kwargs.copy()
aset_kwargs.update(connection_auth)
aset = __salt__['azurearm_compute.availability_set_create_or_update'](
name=name,
resource_group=resource_group,
virtual_machines=virtual_machines,
platform_update_domain_count=platform_update_domain_count,
platform_fault_domain_count=platform_fault_domain_count,
sku=sku,
tags=tags,
**aset_kwargs
)
if 'error' not in aset:
ret['result'] = True
ret['comment'] = 'Availability set {0} has been created.'.format(name)
return ret
ret['comment'] = 'Failed to create availability set {0}! ({1})'.format(name, aset.get('error'))
return ret | python | def availability_set_present(name, resource_group, tags=None, platform_update_domain_count=None,
platform_fault_domain_count=None, virtual_machines=None, sku=None, connection_auth=None,
**kwargs):
'''
.. versionadded:: 2019.2.0
Ensure an availability set exists.
:param name:
Name of the availability set.
:param resource_group:
The resource group assigned to the availability set.
:param tags:
A dictionary of strings can be passed as tag metadata to the availability set object.
:param platform_update_domain_count:
An optional parameter which indicates groups of virtual machines and underlying physical hardware that can be
rebooted at the same time.
:param platform_fault_domain_count:
An optional parameter which defines the group of virtual machines that share a common power source and network
switch.
:param virtual_machines:
A list of names of existing virtual machines to be included in the availability set.
:param sku:
The availability set SKU, which specifies whether the availability set is managed or not. Possible values are
'Aligned' or 'Classic'. An 'Aligned' availability set is managed, 'Classic' is not.
:param connection_auth:
A dict with subscription and authentication parameters to be used in connecting to the
Azure Resource Manager API.
Example usage:
.. code-block:: yaml
Ensure availability set exists:
azurearm_compute.availability_set_present:
- name: aset1
- resource_group: group1
- platform_update_domain_count: 5
- platform_fault_domain_count: 3
- sku: aligned
- tags:
contact_name: Elmer Fudd Gantry
- connection_auth: {{ profile }}
- require:
- azurearm_resource: Ensure resource group exists
'''
ret = {
'name': name,
'result': False,
'comment': '',
'changes': {}
}
if not isinstance(connection_auth, dict):
ret['comment'] = 'Connection information must be specified via connection_auth dictionary!'
return ret
if sku:
sku = {'name': sku.capitalize()}
aset = __salt__['azurearm_compute.availability_set_get'](
name,
resource_group,
azurearm_log_level='info',
**connection_auth
)
if 'error' not in aset:
tag_changes = __utils__['dictdiffer.deep_diff'](aset.get('tags', {}), tags or {})
if tag_changes:
ret['changes']['tags'] = tag_changes
if platform_update_domain_count and (int(platform_update_domain_count) != aset.get('platform_update_domain_count')):
ret['changes']['platform_update_domain_count'] = {
'old': aset.get('platform_update_domain_count'),
'new': platform_update_domain_count
}
if platform_fault_domain_count and (int(platform_fault_domain_count) != aset.get('platform_fault_domain_count')):
ret['changes']['platform_fault_domain_count'] = {
'old': aset.get('platform_fault_domain_count'),
'new': platform_fault_domain_count
}
if sku and (sku['name'] != aset.get('sku', {}).get('name')):
ret['changes']['sku'] = {
'old': aset.get('sku'),
'new': sku
}
if virtual_machines:
if not isinstance(virtual_machines, list):
ret['comment'] = 'Virtual machines must be supplied as a list!'
return ret
aset_vms = aset.get('virtual_machines', [])
remote_vms = sorted([vm['id'].split('/')[-1].lower() for vm in aset_vms if 'id' in aset_vms])
local_vms = sorted([vm.lower() for vm in virtual_machines or []])
if local_vms != remote_vms:
ret['changes']['virtual_machines'] = {
'old': aset_vms,
'new': virtual_machines
}
if not ret['changes']:
ret['result'] = True
ret['comment'] = 'Availability set {0} is already present.'.format(name)
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Availability set {0} would be updated.'.format(name)
return ret
else:
ret['changes'] = {
'old': {},
'new': {
'name': name,
'virtual_machines': virtual_machines,
'platform_update_domain_count': platform_update_domain_count,
'platform_fault_domain_count': platform_fault_domain_count,
'sku': sku,
'tags': tags
}
}
if __opts__['test']:
ret['comment'] = 'Availability set {0} would be created.'.format(name)
ret['result'] = None
return ret
aset_kwargs = kwargs.copy()
aset_kwargs.update(connection_auth)
aset = __salt__['azurearm_compute.availability_set_create_or_update'](
name=name,
resource_group=resource_group,
virtual_machines=virtual_machines,
platform_update_domain_count=platform_update_domain_count,
platform_fault_domain_count=platform_fault_domain_count,
sku=sku,
tags=tags,
**aset_kwargs
)
if 'error' not in aset:
ret['result'] = True
ret['comment'] = 'Availability set {0} has been created.'.format(name)
return ret
ret['comment'] = 'Failed to create availability set {0}! ({1})'.format(name, aset.get('error'))
return ret | [
"def",
"availability_set_present",
"(",
"name",
",",
"resource_group",
",",
"tags",
"=",
"None",
",",
"platform_update_domain_count",
"=",
"None",
",",
"platform_fault_domain_count",
"=",
"None",
",",
"virtual_machines",
"=",
"None",
",",
"sku",
"=",
"None",
",",
... | .. versionadded:: 2019.2.0
Ensure an availability set exists.
:param name:
Name of the availability set.
:param resource_group:
The resource group assigned to the availability set.
:param tags:
A dictionary of strings can be passed as tag metadata to the availability set object.
:param platform_update_domain_count:
An optional parameter which indicates groups of virtual machines and underlying physical hardware that can be
rebooted at the same time.
:param platform_fault_domain_count:
An optional parameter which defines the group of virtual machines that share a common power source and network
switch.
:param virtual_machines:
A list of names of existing virtual machines to be included in the availability set.
:param sku:
The availability set SKU, which specifies whether the availability set is managed or not. Possible values are
'Aligned' or 'Classic'. An 'Aligned' availability set is managed, 'Classic' is not.
:param connection_auth:
A dict with subscription and authentication parameters to be used in connecting to the
Azure Resource Manager API.
Example usage:
.. code-block:: yaml
Ensure availability set exists:
azurearm_compute.availability_set_present:
- name: aset1
- resource_group: group1
- platform_update_domain_count: 5
- platform_fault_domain_count: 3
- sku: aligned
- tags:
contact_name: Elmer Fudd Gantry
- connection_auth: {{ profile }}
- require:
- azurearm_resource: Ensure resource group exists | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/azurearm_compute.py#L104-L263 | train |
saltstack/salt | salt/states/azurearm_compute.py | availability_set_absent | def availability_set_absent(name, resource_group, connection_auth=None):
'''
.. versionadded:: 2019.2.0
Ensure an availability set does not exist in a resource group.
:param name:
Name of the availability set.
:param resource_group:
Name of the resource group containing the availability set.
:param connection_auth:
A dict with subscription and authentication parameters to be used in connecting to the
Azure Resource Manager API.
'''
ret = {
'name': name,
'result': False,
'comment': '',
'changes': {}
}
if not isinstance(connection_auth, dict):
ret['comment'] = 'Connection information must be specified via connection_auth dictionary!'
return ret
aset = __salt__['azurearm_compute.availability_set_get'](
name,
resource_group,
azurearm_log_level='info',
**connection_auth
)
if 'error' in aset:
ret['result'] = True
ret['comment'] = 'Availability set {0} was not found.'.format(name)
return ret
elif __opts__['test']:
ret['comment'] = 'Availability set {0} would be deleted.'.format(name)
ret['result'] = None
ret['changes'] = {
'old': aset,
'new': {},
}
return ret
deleted = __salt__['azurearm_compute.availability_set_delete'](name, resource_group, **connection_auth)
if deleted:
ret['result'] = True
ret['comment'] = 'Availability set {0} has been deleted.'.format(name)
ret['changes'] = {
'old': aset,
'new': {}
}
return ret
ret['comment'] = 'Failed to delete availability set {0}!'.format(name)
return ret | python | def availability_set_absent(name, resource_group, connection_auth=None):
'''
.. versionadded:: 2019.2.0
Ensure an availability set does not exist in a resource group.
:param name:
Name of the availability set.
:param resource_group:
Name of the resource group containing the availability set.
:param connection_auth:
A dict with subscription and authentication parameters to be used in connecting to the
Azure Resource Manager API.
'''
ret = {
'name': name,
'result': False,
'comment': '',
'changes': {}
}
if not isinstance(connection_auth, dict):
ret['comment'] = 'Connection information must be specified via connection_auth dictionary!'
return ret
aset = __salt__['azurearm_compute.availability_set_get'](
name,
resource_group,
azurearm_log_level='info',
**connection_auth
)
if 'error' in aset:
ret['result'] = True
ret['comment'] = 'Availability set {0} was not found.'.format(name)
return ret
elif __opts__['test']:
ret['comment'] = 'Availability set {0} would be deleted.'.format(name)
ret['result'] = None
ret['changes'] = {
'old': aset,
'new': {},
}
return ret
deleted = __salt__['azurearm_compute.availability_set_delete'](name, resource_group, **connection_auth)
if deleted:
ret['result'] = True
ret['comment'] = 'Availability set {0} has been deleted.'.format(name)
ret['changes'] = {
'old': aset,
'new': {}
}
return ret
ret['comment'] = 'Failed to delete availability set {0}!'.format(name)
return ret | [
"def",
"availability_set_absent",
"(",
"name",
",",
"resource_group",
",",
"connection_auth",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"False",
",",
"'comment'",
":",
"''",
",",
"'changes'",
":",
"{",
"}",
"}",... | .. versionadded:: 2019.2.0
Ensure an availability set does not exist in a resource group.
:param name:
Name of the availability set.
:param resource_group:
Name of the resource group containing the availability set.
:param connection_auth:
A dict with subscription and authentication parameters to be used in connecting to the
Azure Resource Manager API. | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/azurearm_compute.py#L266-L326 | train |
saltstack/salt | salt/grains/fibre_channel.py | _linux_wwns | def _linux_wwns():
'''
Return Fibre Channel port WWNs from a Linux host.
'''
ret = []
for fc_file in glob.glob('/sys/class/fc_host/*/port_name'):
with salt.utils.files.fopen(fc_file, 'r') as _wwn:
content = _wwn.read()
for line in content.splitlines():
ret.append(line.rstrip()[2:])
return ret | python | def _linux_wwns():
'''
Return Fibre Channel port WWNs from a Linux host.
'''
ret = []
for fc_file in glob.glob('/sys/class/fc_host/*/port_name'):
with salt.utils.files.fopen(fc_file, 'r') as _wwn:
content = _wwn.read()
for line in content.splitlines():
ret.append(line.rstrip()[2:])
return ret | [
"def",
"_linux_wwns",
"(",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"fc_file",
"in",
"glob",
".",
"glob",
"(",
"'/sys/class/fc_host/*/port_name'",
")",
":",
"with",
"salt",
".",
"utils",
".",
"files",
".",
"fopen",
"(",
"fc_file",
",",
"'r'",
")",
"as",
... | Return Fibre Channel port WWNs from a Linux host. | [
"Return",
"Fibre",
"Channel",
"port",
"WWNs",
"from",
"a",
"Linux",
"host",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/grains/fibre_channel.py#L38-L48 | train |
saltstack/salt | salt/grains/fibre_channel.py | _windows_wwns | def _windows_wwns():
'''
Return Fibre Channel port WWNs from a Windows host.
'''
ps_cmd = r'Get-WmiObject -ErrorAction Stop ' \
r'-class MSFC_FibrePortHBAAttributes ' \
r'-namespace "root\WMI" | ' \
r'Select -Expandproperty Attributes | ' \
r'%{($_.PortWWN | % {"{0:x2}" -f $_}) -join ""}'
ret = []
cmd_ret = salt.modules.cmdmod.powershell(ps_cmd)
for line in cmd_ret:
ret.append(line.rstrip())
return ret | python | def _windows_wwns():
'''
Return Fibre Channel port WWNs from a Windows host.
'''
ps_cmd = r'Get-WmiObject -ErrorAction Stop ' \
r'-class MSFC_FibrePortHBAAttributes ' \
r'-namespace "root\WMI" | ' \
r'Select -Expandproperty Attributes | ' \
r'%{($_.PortWWN | % {"{0:x2}" -f $_}) -join ""}'
ret = []
cmd_ret = salt.modules.cmdmod.powershell(ps_cmd)
for line in cmd_ret:
ret.append(line.rstrip())
return ret | [
"def",
"_windows_wwns",
"(",
")",
":",
"ps_cmd",
"=",
"r'Get-WmiObject -ErrorAction Stop '",
"r'-class MSFC_FibrePortHBAAttributes '",
"r'-namespace \"root\\WMI\" | '",
"r'Select -Expandproperty Attributes | '",
"r'%{($_.PortWWN | % {\"{0:x2}\" -f $_}) -join \"\"}'",
"ret",
"=",
"[",
"... | Return Fibre Channel port WWNs from a Windows host. | [
"Return",
"Fibre",
"Channel",
"port",
"WWNs",
"from",
"a",
"Windows",
"host",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/grains/fibre_channel.py#L51-L64 | train |
saltstack/salt | salt/grains/fibre_channel.py | fibre_channel_wwns | def fibre_channel_wwns():
'''
Return list of fiber channel HBA WWNs
'''
grains = {'fc_wwn': False}
if salt.utils.platform.is_linux():
grains['fc_wwn'] = _linux_wwns()
elif salt.utils.platform.is_windows():
grains['fc_wwn'] = _windows_wwns()
return grains | python | def fibre_channel_wwns():
'''
Return list of fiber channel HBA WWNs
'''
grains = {'fc_wwn': False}
if salt.utils.platform.is_linux():
grains['fc_wwn'] = _linux_wwns()
elif salt.utils.platform.is_windows():
grains['fc_wwn'] = _windows_wwns()
return grains | [
"def",
"fibre_channel_wwns",
"(",
")",
":",
"grains",
"=",
"{",
"'fc_wwn'",
":",
"False",
"}",
"if",
"salt",
".",
"utils",
".",
"platform",
".",
"is_linux",
"(",
")",
":",
"grains",
"[",
"'fc_wwn'",
"]",
"=",
"_linux_wwns",
"(",
")",
"elif",
"salt",
... | Return list of fiber channel HBA WWNs | [
"Return",
"list",
"of",
"fiber",
"channel",
"HBA",
"WWNs"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/grains/fibre_channel.py#L67-L76 | train |
saltstack/salt | salt/utils/vsan.py | vsan_supported | def vsan_supported(service_instance):
'''
Returns whether vsan is supported on the vCenter:
api version needs to be 6 or higher
service_instance
Service instance to the host or vCenter
'''
try:
api_version = service_instance.content.about.apiVersion
except vim.fault.NoPermission as exc:
log.exception(exc)
raise VMwareApiError('Not enough permissions. Required privilege: '
'{0}'.format(exc.privilegeId))
except vim.fault.VimFault as exc:
log.exception(exc)
raise VMwareApiError(exc.msg)
except vmodl.RuntimeFault as exc:
log.exception(exc)
raise VMwareRuntimeError(exc.msg)
if int(api_version.split('.')[0]) < 6:
return False
return True | python | def vsan_supported(service_instance):
'''
Returns whether vsan is supported on the vCenter:
api version needs to be 6 or higher
service_instance
Service instance to the host or vCenter
'''
try:
api_version = service_instance.content.about.apiVersion
except vim.fault.NoPermission as exc:
log.exception(exc)
raise VMwareApiError('Not enough permissions. Required privilege: '
'{0}'.format(exc.privilegeId))
except vim.fault.VimFault as exc:
log.exception(exc)
raise VMwareApiError(exc.msg)
except vmodl.RuntimeFault as exc:
log.exception(exc)
raise VMwareRuntimeError(exc.msg)
if int(api_version.split('.')[0]) < 6:
return False
return True | [
"def",
"vsan_supported",
"(",
"service_instance",
")",
":",
"try",
":",
"api_version",
"=",
"service_instance",
".",
"content",
".",
"about",
".",
"apiVersion",
"except",
"vim",
".",
"fault",
".",
"NoPermission",
"as",
"exc",
":",
"log",
".",
"exception",
"(... | Returns whether vsan is supported on the vCenter:
api version needs to be 6 or higher
service_instance
Service instance to the host or vCenter | [
"Returns",
"whether",
"vsan",
"is",
"supported",
"on",
"the",
"vCenter",
":",
"api",
"version",
"needs",
"to",
"be",
"6",
"or",
"higher"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/vsan.py#L85-L107 | train |
saltstack/salt | salt/utils/vsan.py | get_vsan_cluster_config_system | def get_vsan_cluster_config_system(service_instance):
'''
Returns a vim.cluster.VsanVcClusterConfigSystem object
service_instance
Service instance to the host or vCenter
'''
#TODO Replace when better connection mechanism is available
#For python 2.7.9 and later, the defaul SSL conext has more strict
#connection handshaking rule. We may need turn of the hostname checking
#and client side cert verification
context = None
if sys.version_info[:3] > (2, 7, 8):
context = ssl.create_default_context()
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE
stub = service_instance._stub
vc_mos = vsanapiutils.GetVsanVcMos(stub, context=context)
return vc_mos['vsan-cluster-config-system'] | python | def get_vsan_cluster_config_system(service_instance):
'''
Returns a vim.cluster.VsanVcClusterConfigSystem object
service_instance
Service instance to the host or vCenter
'''
#TODO Replace when better connection mechanism is available
#For python 2.7.9 and later, the defaul SSL conext has more strict
#connection handshaking rule. We may need turn of the hostname checking
#and client side cert verification
context = None
if sys.version_info[:3] > (2, 7, 8):
context = ssl.create_default_context()
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE
stub = service_instance._stub
vc_mos = vsanapiutils.GetVsanVcMos(stub, context=context)
return vc_mos['vsan-cluster-config-system'] | [
"def",
"get_vsan_cluster_config_system",
"(",
"service_instance",
")",
":",
"#TODO Replace when better connection mechanism is available",
"#For python 2.7.9 and later, the defaul SSL conext has more strict",
"#connection handshaking rule. We may need turn of the hostname checking",
"#and client s... | Returns a vim.cluster.VsanVcClusterConfigSystem object
service_instance
Service instance to the host or vCenter | [
"Returns",
"a",
"vim",
".",
"cluster",
".",
"VsanVcClusterConfigSystem",
"object"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/vsan.py#L110-L131 | train |
saltstack/salt | salt/utils/vsan.py | get_host_vsan_system | def get_host_vsan_system(service_instance, host_ref, hostname=None):
'''
Returns a host's vsan system
service_instance
Service instance to the host or vCenter
host_ref
Refernce to ESXi host
hostname
Name of ESXi host. Default value is None.
'''
if not hostname:
hostname = salt.utils.vmware.get_managed_object_name(host_ref)
traversal_spec = vmodl.query.PropertyCollector.TraversalSpec(
path='configManager.vsanSystem',
type=vim.HostSystem,
skip=False)
objs = salt.utils.vmware.get_mors_with_properties(
service_instance, vim.HostVsanSystem, property_list=['config.enabled'],
container_ref=host_ref, traversal_spec=traversal_spec)
if not objs:
raise VMwareObjectRetrievalError('Host\'s \'{0}\' VSAN system was '
'not retrieved'.format(hostname))
log.trace('[%s] Retrieved VSAN system', hostname)
return objs[0]['object'] | python | def get_host_vsan_system(service_instance, host_ref, hostname=None):
'''
Returns a host's vsan system
service_instance
Service instance to the host or vCenter
host_ref
Refernce to ESXi host
hostname
Name of ESXi host. Default value is None.
'''
if not hostname:
hostname = salt.utils.vmware.get_managed_object_name(host_ref)
traversal_spec = vmodl.query.PropertyCollector.TraversalSpec(
path='configManager.vsanSystem',
type=vim.HostSystem,
skip=False)
objs = salt.utils.vmware.get_mors_with_properties(
service_instance, vim.HostVsanSystem, property_list=['config.enabled'],
container_ref=host_ref, traversal_spec=traversal_spec)
if not objs:
raise VMwareObjectRetrievalError('Host\'s \'{0}\' VSAN system was '
'not retrieved'.format(hostname))
log.trace('[%s] Retrieved VSAN system', hostname)
return objs[0]['object'] | [
"def",
"get_host_vsan_system",
"(",
"service_instance",
",",
"host_ref",
",",
"hostname",
"=",
"None",
")",
":",
"if",
"not",
"hostname",
":",
"hostname",
"=",
"salt",
".",
"utils",
".",
"vmware",
".",
"get_managed_object_name",
"(",
"host_ref",
")",
"traversa... | Returns a host's vsan system
service_instance
Service instance to the host or vCenter
host_ref
Refernce to ESXi host
hostname
Name of ESXi host. Default value is None. | [
"Returns",
"a",
"host",
"s",
"vsan",
"system"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/vsan.py#L158-L184 | train |
saltstack/salt | salt/utils/vsan.py | create_diskgroup | def create_diskgroup(service_instance, vsan_disk_mgmt_system,
host_ref, cache_disk, capacity_disks):
'''
Creates a disk group
service_instance
Service instance to the host or vCenter
vsan_disk_mgmt_system
vim.VimClusterVsanVcDiskManagemenetSystem representing the vSan disk
management system retrieved from the vsan endpoint.
host_ref
vim.HostSystem object representing the target host the disk group will
be created on
cache_disk
The vim.HostScsidisk to be used as a cache disk. It must be an ssd disk.
capacity_disks
List of vim.HostScsiDisk objects representing of disks to be used as
capacity disks. Can be either ssd or non-ssd. There must be a minimum
of 1 capacity disk in the list.
'''
hostname = salt.utils.vmware.get_managed_object_name(host_ref)
cache_disk_id = cache_disk.canonicalName
log.debug(
'Creating a new disk group with cache disk \'%s\' on host \'%s\'',
cache_disk_id, hostname
)
log.trace('capacity_disk_ids = %s', [c.canonicalName for c in capacity_disks])
spec = vim.VimVsanHostDiskMappingCreationSpec()
spec.cacheDisks = [cache_disk]
spec.capacityDisks = capacity_disks
# All capacity disks must be either ssd or non-ssd (mixed disks are not
# supported)
spec.creationType = 'allFlash' if getattr(capacity_disks[0], 'ssd') \
else 'hybrid'
spec.host = host_ref
try:
task = vsan_disk_mgmt_system.InitializeDiskMappings(spec)
except vim.fault.NoPermission as exc:
log.exception(exc)
raise VMwareApiError('Not enough permissions. Required privilege: '
'{0}'.format(exc.privilegeId))
except vim.fault.VimFault as exc:
log.exception(exc)
raise VMwareApiError(exc.msg)
except vmodl.fault.MethodNotFound as exc:
log.exception(exc)
raise VMwareRuntimeError('Method \'{0}\' not found'.format(exc.method))
except vmodl.RuntimeFault as exc:
log.exception(exc)
raise VMwareRuntimeError(exc.msg)
_wait_for_tasks([task], service_instance)
return True | python | def create_diskgroup(service_instance, vsan_disk_mgmt_system,
host_ref, cache_disk, capacity_disks):
'''
Creates a disk group
service_instance
Service instance to the host or vCenter
vsan_disk_mgmt_system
vim.VimClusterVsanVcDiskManagemenetSystem representing the vSan disk
management system retrieved from the vsan endpoint.
host_ref
vim.HostSystem object representing the target host the disk group will
be created on
cache_disk
The vim.HostScsidisk to be used as a cache disk. It must be an ssd disk.
capacity_disks
List of vim.HostScsiDisk objects representing of disks to be used as
capacity disks. Can be either ssd or non-ssd. There must be a minimum
of 1 capacity disk in the list.
'''
hostname = salt.utils.vmware.get_managed_object_name(host_ref)
cache_disk_id = cache_disk.canonicalName
log.debug(
'Creating a new disk group with cache disk \'%s\' on host \'%s\'',
cache_disk_id, hostname
)
log.trace('capacity_disk_ids = %s', [c.canonicalName for c in capacity_disks])
spec = vim.VimVsanHostDiskMappingCreationSpec()
spec.cacheDisks = [cache_disk]
spec.capacityDisks = capacity_disks
# All capacity disks must be either ssd or non-ssd (mixed disks are not
# supported)
spec.creationType = 'allFlash' if getattr(capacity_disks[0], 'ssd') \
else 'hybrid'
spec.host = host_ref
try:
task = vsan_disk_mgmt_system.InitializeDiskMappings(spec)
except vim.fault.NoPermission as exc:
log.exception(exc)
raise VMwareApiError('Not enough permissions. Required privilege: '
'{0}'.format(exc.privilegeId))
except vim.fault.VimFault as exc:
log.exception(exc)
raise VMwareApiError(exc.msg)
except vmodl.fault.MethodNotFound as exc:
log.exception(exc)
raise VMwareRuntimeError('Method \'{0}\' not found'.format(exc.method))
except vmodl.RuntimeFault as exc:
log.exception(exc)
raise VMwareRuntimeError(exc.msg)
_wait_for_tasks([task], service_instance)
return True | [
"def",
"create_diskgroup",
"(",
"service_instance",
",",
"vsan_disk_mgmt_system",
",",
"host_ref",
",",
"cache_disk",
",",
"capacity_disks",
")",
":",
"hostname",
"=",
"salt",
".",
"utils",
".",
"vmware",
".",
"get_managed_object_name",
"(",
"host_ref",
")",
"cach... | Creates a disk group
service_instance
Service instance to the host or vCenter
vsan_disk_mgmt_system
vim.VimClusterVsanVcDiskManagemenetSystem representing the vSan disk
management system retrieved from the vsan endpoint.
host_ref
vim.HostSystem object representing the target host the disk group will
be created on
cache_disk
The vim.HostScsidisk to be used as a cache disk. It must be an ssd disk.
capacity_disks
List of vim.HostScsiDisk objects representing of disks to be used as
capacity disks. Can be either ssd or non-ssd. There must be a minimum
of 1 capacity disk in the list. | [
"Creates",
"a",
"disk",
"group"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/vsan.py#L187-L242 | train |
saltstack/salt | salt/utils/vsan.py | remove_capacity_from_diskgroup | def remove_capacity_from_diskgroup(service_instance, host_ref, diskgroup,
capacity_disks, data_evacuation=True,
hostname=None,
host_vsan_system=None):
'''
Removes capacity disk(s) from a disk group.
service_instance
Service instance to the host or vCenter
host_vsan_system
ESXi host's VSAN system
host_ref
Reference to the ESXi host
diskgroup
The vsan.HostDiskMapping object representing the host's diskgroup from
where the capacity needs to be removed
capacity_disks
List of vim.HostScsiDisk objects representing the capacity disks to be
removed. Can be either ssd or non-ssd. There must be a minimum
of 1 capacity disk in the list.
data_evacuation
Specifies whether to gracefully evacuate the data on the capacity disks
before removing them from the disk group. Default value is True.
hostname
Name of ESXi host. Default value is None.
host_vsan_system
ESXi host's VSAN system. Default value is None.
'''
if not hostname:
hostname = salt.utils.vmware.get_managed_object_name(host_ref)
cache_disk = diskgroup.ssd
cache_disk_id = cache_disk.canonicalName
log.debug(
'Removing capacity from disk group with cache disk \'%s\' on host \'%s\'',
cache_disk_id, hostname
)
log.trace('capacity_disk_ids = %s',
[c.canonicalName for c in capacity_disks])
if not host_vsan_system:
host_vsan_system = get_host_vsan_system(service_instance,
host_ref, hostname)
# Set to evacuate all data before removing the disks
maint_spec = vim.HostMaintenanceSpec()
maint_spec.vsanMode = vim.VsanHostDecommissionMode()
if data_evacuation:
maint_spec.vsanMode.objectAction = \
vim.VsanHostDecommissionModeObjectAction.evacuateAllData
else:
maint_spec.vsanMode.objectAction = \
vim.VsanHostDecommissionModeObjectAction.noAction
try:
task = host_vsan_system.RemoveDisk_Task(disk=capacity_disks,
maintenanceSpec=maint_spec)
except vim.fault.NoPermission as exc:
log.exception(exc)
raise VMwareApiError('Not enough permissions. Required privilege: '
'{0}'.format(exc.privilegeId))
except vim.fault.VimFault as exc:
log.exception(exc)
raise VMwareApiError(exc.msg)
except vmodl.RuntimeFault as exc:
log.exception(exc)
raise VMwareRuntimeError(exc.msg)
salt.utils.vmware.wait_for_task(task, hostname, 'remove_capacity')
return True | python | def remove_capacity_from_diskgroup(service_instance, host_ref, diskgroup,
capacity_disks, data_evacuation=True,
hostname=None,
host_vsan_system=None):
'''
Removes capacity disk(s) from a disk group.
service_instance
Service instance to the host or vCenter
host_vsan_system
ESXi host's VSAN system
host_ref
Reference to the ESXi host
diskgroup
The vsan.HostDiskMapping object representing the host's diskgroup from
where the capacity needs to be removed
capacity_disks
List of vim.HostScsiDisk objects representing the capacity disks to be
removed. Can be either ssd or non-ssd. There must be a minimum
of 1 capacity disk in the list.
data_evacuation
Specifies whether to gracefully evacuate the data on the capacity disks
before removing them from the disk group. Default value is True.
hostname
Name of ESXi host. Default value is None.
host_vsan_system
ESXi host's VSAN system. Default value is None.
'''
if not hostname:
hostname = salt.utils.vmware.get_managed_object_name(host_ref)
cache_disk = diskgroup.ssd
cache_disk_id = cache_disk.canonicalName
log.debug(
'Removing capacity from disk group with cache disk \'%s\' on host \'%s\'',
cache_disk_id, hostname
)
log.trace('capacity_disk_ids = %s',
[c.canonicalName for c in capacity_disks])
if not host_vsan_system:
host_vsan_system = get_host_vsan_system(service_instance,
host_ref, hostname)
# Set to evacuate all data before removing the disks
maint_spec = vim.HostMaintenanceSpec()
maint_spec.vsanMode = vim.VsanHostDecommissionMode()
if data_evacuation:
maint_spec.vsanMode.objectAction = \
vim.VsanHostDecommissionModeObjectAction.evacuateAllData
else:
maint_spec.vsanMode.objectAction = \
vim.VsanHostDecommissionModeObjectAction.noAction
try:
task = host_vsan_system.RemoveDisk_Task(disk=capacity_disks,
maintenanceSpec=maint_spec)
except vim.fault.NoPermission as exc:
log.exception(exc)
raise VMwareApiError('Not enough permissions. Required privilege: '
'{0}'.format(exc.privilegeId))
except vim.fault.VimFault as exc:
log.exception(exc)
raise VMwareApiError(exc.msg)
except vmodl.RuntimeFault as exc:
log.exception(exc)
raise VMwareRuntimeError(exc.msg)
salt.utils.vmware.wait_for_task(task, hostname, 'remove_capacity')
return True | [
"def",
"remove_capacity_from_diskgroup",
"(",
"service_instance",
",",
"host_ref",
",",
"diskgroup",
",",
"capacity_disks",
",",
"data_evacuation",
"=",
"True",
",",
"hostname",
"=",
"None",
",",
"host_vsan_system",
"=",
"None",
")",
":",
"if",
"not",
"hostname",
... | Removes capacity disk(s) from a disk group.
service_instance
Service instance to the host or vCenter
host_vsan_system
ESXi host's VSAN system
host_ref
Reference to the ESXi host
diskgroup
The vsan.HostDiskMapping object representing the host's diskgroup from
where the capacity needs to be removed
capacity_disks
List of vim.HostScsiDisk objects representing the capacity disks to be
removed. Can be either ssd or non-ssd. There must be a minimum
of 1 capacity disk in the list.
data_evacuation
Specifies whether to gracefully evacuate the data on the capacity disks
before removing them from the disk group. Default value is True.
hostname
Name of ESXi host. Default value is None.
host_vsan_system
ESXi host's VSAN system. Default value is None. | [
"Removes",
"capacity",
"disk",
"(",
"s",
")",
"from",
"a",
"disk",
"group",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/vsan.py#L308-L379 | train |
saltstack/salt | salt/utils/vsan.py | remove_diskgroup | def remove_diskgroup(service_instance, host_ref, diskgroup, hostname=None,
host_vsan_system=None, erase_disk_partitions=False,
data_accessibility=True):
'''
Removes a disk group.
service_instance
Service instance to the host or vCenter
host_ref
Reference to the ESXi host
diskgroup
The vsan.HostDiskMapping object representing the host's diskgroup from
where the capacity needs to be removed
hostname
Name of ESXi host. Default value is None.
host_vsan_system
ESXi host's VSAN system. Default value is None.
data_accessibility
Specifies whether to ensure data accessibility. Default value is True.
'''
if not hostname:
hostname = salt.utils.vmware.get_managed_object_name(host_ref)
cache_disk_id = diskgroup.ssd.canonicalName
log.debug('Removing disk group with cache disk \'%s\' on '
'host \'%s\'', cache_disk_id, hostname)
if not host_vsan_system:
host_vsan_system = get_host_vsan_system(
service_instance, host_ref, hostname)
# Set to evacuate all data before removing the disks
maint_spec = vim.HostMaintenanceSpec()
maint_spec.vsanMode = vim.VsanHostDecommissionMode()
object_action = vim.VsanHostDecommissionModeObjectAction
if data_accessibility:
maint_spec.vsanMode.objectAction = \
object_action.ensureObjectAccessibility
else:
maint_spec.vsanMode.objectAction = object_action.noAction
try:
task = host_vsan_system.RemoveDiskMapping_Task(
mapping=[diskgroup], maintenanceSpec=maint_spec)
except vim.fault.NoPermission as exc:
log.exception(exc)
raise VMwareApiError('Not enough permissions. Required privilege: '
'{0}'.format(exc.privilegeId))
except vim.fault.VimFault as exc:
log.exception(exc)
raise VMwareApiError(exc.msg)
except vmodl.RuntimeFault as exc:
log.exception(exc)
raise VMwareRuntimeError(exc.msg)
salt.utils.vmware.wait_for_task(task, hostname, 'remove_diskgroup')
log.debug('Removed disk group with cache disk \'%s\' on host \'%s\'',
cache_disk_id, hostname)
return True | python | def remove_diskgroup(service_instance, host_ref, diskgroup, hostname=None,
host_vsan_system=None, erase_disk_partitions=False,
data_accessibility=True):
'''
Removes a disk group.
service_instance
Service instance to the host or vCenter
host_ref
Reference to the ESXi host
diskgroup
The vsan.HostDiskMapping object representing the host's diskgroup from
where the capacity needs to be removed
hostname
Name of ESXi host. Default value is None.
host_vsan_system
ESXi host's VSAN system. Default value is None.
data_accessibility
Specifies whether to ensure data accessibility. Default value is True.
'''
if not hostname:
hostname = salt.utils.vmware.get_managed_object_name(host_ref)
cache_disk_id = diskgroup.ssd.canonicalName
log.debug('Removing disk group with cache disk \'%s\' on '
'host \'%s\'', cache_disk_id, hostname)
if not host_vsan_system:
host_vsan_system = get_host_vsan_system(
service_instance, host_ref, hostname)
# Set to evacuate all data before removing the disks
maint_spec = vim.HostMaintenanceSpec()
maint_spec.vsanMode = vim.VsanHostDecommissionMode()
object_action = vim.VsanHostDecommissionModeObjectAction
if data_accessibility:
maint_spec.vsanMode.objectAction = \
object_action.ensureObjectAccessibility
else:
maint_spec.vsanMode.objectAction = object_action.noAction
try:
task = host_vsan_system.RemoveDiskMapping_Task(
mapping=[diskgroup], maintenanceSpec=maint_spec)
except vim.fault.NoPermission as exc:
log.exception(exc)
raise VMwareApiError('Not enough permissions. Required privilege: '
'{0}'.format(exc.privilegeId))
except vim.fault.VimFault as exc:
log.exception(exc)
raise VMwareApiError(exc.msg)
except vmodl.RuntimeFault as exc:
log.exception(exc)
raise VMwareRuntimeError(exc.msg)
salt.utils.vmware.wait_for_task(task, hostname, 'remove_diskgroup')
log.debug('Removed disk group with cache disk \'%s\' on host \'%s\'',
cache_disk_id, hostname)
return True | [
"def",
"remove_diskgroup",
"(",
"service_instance",
",",
"host_ref",
",",
"diskgroup",
",",
"hostname",
"=",
"None",
",",
"host_vsan_system",
"=",
"None",
",",
"erase_disk_partitions",
"=",
"False",
",",
"data_accessibility",
"=",
"True",
")",
":",
"if",
"not",
... | Removes a disk group.
service_instance
Service instance to the host or vCenter
host_ref
Reference to the ESXi host
diskgroup
The vsan.HostDiskMapping object representing the host's diskgroup from
where the capacity needs to be removed
hostname
Name of ESXi host. Default value is None.
host_vsan_system
ESXi host's VSAN system. Default value is None.
data_accessibility
Specifies whether to ensure data accessibility. Default value is True. | [
"Removes",
"a",
"disk",
"group",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/vsan.py#L382-L440 | train |
saltstack/salt | salt/utils/vsan.py | get_cluster_vsan_info | def get_cluster_vsan_info(cluster_ref):
'''
Returns the extended cluster vsan configuration object
(vim.VsanConfigInfoEx).
cluster_ref
Reference to the cluster
'''
cluster_name = salt.utils.vmware.get_managed_object_name(cluster_ref)
log.trace('Retrieving cluster vsan info of cluster \'%s\'', cluster_name)
si = salt.utils.vmware.get_service_instance_from_managed_object(
cluster_ref)
vsan_cl_conf_sys = get_vsan_cluster_config_system(si)
try:
return vsan_cl_conf_sys.VsanClusterGetConfig(cluster_ref)
except vim.fault.NoPermission as exc:
log.exception(exc)
raise VMwareApiError('Not enough permissions. Required privilege: '
'{0}'.format(exc.privilegeId))
except vim.fault.VimFault as exc:
log.exception(exc)
raise VMwareApiError(exc.msg)
except vmodl.RuntimeFault as exc:
log.exception(exc)
raise VMwareRuntimeError(exc.msg) | python | def get_cluster_vsan_info(cluster_ref):
'''
Returns the extended cluster vsan configuration object
(vim.VsanConfigInfoEx).
cluster_ref
Reference to the cluster
'''
cluster_name = salt.utils.vmware.get_managed_object_name(cluster_ref)
log.trace('Retrieving cluster vsan info of cluster \'%s\'', cluster_name)
si = salt.utils.vmware.get_service_instance_from_managed_object(
cluster_ref)
vsan_cl_conf_sys = get_vsan_cluster_config_system(si)
try:
return vsan_cl_conf_sys.VsanClusterGetConfig(cluster_ref)
except vim.fault.NoPermission as exc:
log.exception(exc)
raise VMwareApiError('Not enough permissions. Required privilege: '
'{0}'.format(exc.privilegeId))
except vim.fault.VimFault as exc:
log.exception(exc)
raise VMwareApiError(exc.msg)
except vmodl.RuntimeFault as exc:
log.exception(exc)
raise VMwareRuntimeError(exc.msg) | [
"def",
"get_cluster_vsan_info",
"(",
"cluster_ref",
")",
":",
"cluster_name",
"=",
"salt",
".",
"utils",
".",
"vmware",
".",
"get_managed_object_name",
"(",
"cluster_ref",
")",
"log",
".",
"trace",
"(",
"'Retrieving cluster vsan info of cluster \\'%s\\''",
",",
"clust... | Returns the extended cluster vsan configuration object
(vim.VsanConfigInfoEx).
cluster_ref
Reference to the cluster | [
"Returns",
"the",
"extended",
"cluster",
"vsan",
"configuration",
"object",
"(",
"vim",
".",
"VsanConfigInfoEx",
")",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/vsan.py#L443-L468 | train |
saltstack/salt | salt/utils/vsan.py | reconfigure_cluster_vsan | def reconfigure_cluster_vsan(cluster_ref, cluster_vsan_spec):
'''
Reconfigures the VSAN system of a cluster.
cluster_ref
Reference to the cluster
cluster_vsan_spec
Cluster VSAN reconfigure spec (vim.vsan.ReconfigSpec).
'''
cluster_name = salt.utils.vmware.get_managed_object_name(cluster_ref)
log.trace('Reconfiguring vsan on cluster \'%s\': %s',
cluster_name, cluster_vsan_spec)
si = salt.utils.vmware.get_service_instance_from_managed_object(
cluster_ref)
vsan_cl_conf_sys = salt.utils.vsan.get_vsan_cluster_config_system(si)
try:
task = vsan_cl_conf_sys.VsanClusterReconfig(cluster_ref,
cluster_vsan_spec)
except vim.fault.NoPermission as exc:
log.exception(exc)
raise VMwareApiError('Not enough permissions. Required privilege: '
'{0}'.format(exc.privilegeId))
except vim.fault.VimFault as exc:
log.exception(exc)
raise VMwareApiError(exc.msg)
except vmodl.RuntimeFault as exc:
log.exception(exc)
raise VMwareRuntimeError(exc.msg)
_wait_for_tasks([task], si) | python | def reconfigure_cluster_vsan(cluster_ref, cluster_vsan_spec):
'''
Reconfigures the VSAN system of a cluster.
cluster_ref
Reference to the cluster
cluster_vsan_spec
Cluster VSAN reconfigure spec (vim.vsan.ReconfigSpec).
'''
cluster_name = salt.utils.vmware.get_managed_object_name(cluster_ref)
log.trace('Reconfiguring vsan on cluster \'%s\': %s',
cluster_name, cluster_vsan_spec)
si = salt.utils.vmware.get_service_instance_from_managed_object(
cluster_ref)
vsan_cl_conf_sys = salt.utils.vsan.get_vsan_cluster_config_system(si)
try:
task = vsan_cl_conf_sys.VsanClusterReconfig(cluster_ref,
cluster_vsan_spec)
except vim.fault.NoPermission as exc:
log.exception(exc)
raise VMwareApiError('Not enough permissions. Required privilege: '
'{0}'.format(exc.privilegeId))
except vim.fault.VimFault as exc:
log.exception(exc)
raise VMwareApiError(exc.msg)
except vmodl.RuntimeFault as exc:
log.exception(exc)
raise VMwareRuntimeError(exc.msg)
_wait_for_tasks([task], si) | [
"def",
"reconfigure_cluster_vsan",
"(",
"cluster_ref",
",",
"cluster_vsan_spec",
")",
":",
"cluster_name",
"=",
"salt",
".",
"utils",
".",
"vmware",
".",
"get_managed_object_name",
"(",
"cluster_ref",
")",
"log",
".",
"trace",
"(",
"'Reconfiguring vsan on cluster \\'%... | Reconfigures the VSAN system of a cluster.
cluster_ref
Reference to the cluster
cluster_vsan_spec
Cluster VSAN reconfigure spec (vim.vsan.ReconfigSpec). | [
"Reconfigures",
"the",
"VSAN",
"system",
"of",
"a",
"cluster",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/vsan.py#L471-L500 | train |
saltstack/salt | salt/utils/vsan.py | _wait_for_tasks | def _wait_for_tasks(tasks, service_instance):
'''
Wait for tasks created via the VSAN API
'''
log.trace('Waiting for vsan tasks: {0}',
', '.join([six.text_type(t) for t in tasks]))
try:
vsanapiutils.WaitForTasks(tasks, service_instance)
except vim.fault.NoPermission as exc:
log.exception(exc)
raise VMwareApiError('Not enough permissions. Required privilege: '
'{0}'.format(exc.privilegeId))
except vim.fault.VimFault as exc:
log.exception(exc)
raise VMwareApiError(exc.msg)
except vmodl.RuntimeFault as exc:
log.exception(exc)
raise VMwareRuntimeError(exc.msg)
log.trace('Tasks %s finished successfully',
', '.join([six.text_type(t) for t in tasks])) | python | def _wait_for_tasks(tasks, service_instance):
'''
Wait for tasks created via the VSAN API
'''
log.trace('Waiting for vsan tasks: {0}',
', '.join([six.text_type(t) for t in tasks]))
try:
vsanapiutils.WaitForTasks(tasks, service_instance)
except vim.fault.NoPermission as exc:
log.exception(exc)
raise VMwareApiError('Not enough permissions. Required privilege: '
'{0}'.format(exc.privilegeId))
except vim.fault.VimFault as exc:
log.exception(exc)
raise VMwareApiError(exc.msg)
except vmodl.RuntimeFault as exc:
log.exception(exc)
raise VMwareRuntimeError(exc.msg)
log.trace('Tasks %s finished successfully',
', '.join([six.text_type(t) for t in tasks])) | [
"def",
"_wait_for_tasks",
"(",
"tasks",
",",
"service_instance",
")",
":",
"log",
".",
"trace",
"(",
"'Waiting for vsan tasks: {0}'",
",",
"', '",
".",
"join",
"(",
"[",
"six",
".",
"text_type",
"(",
"t",
")",
"for",
"t",
"in",
"tasks",
"]",
")",
")",
... | Wait for tasks created via the VSAN API | [
"Wait",
"for",
"tasks",
"created",
"via",
"the",
"VSAN",
"API"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/vsan.py#L503-L522 | train |
saltstack/salt | salt/utils/crypt.py | decrypt | def decrypt(data,
rend,
translate_newlines=False,
renderers=None,
opts=None,
valid_rend=None):
'''
.. versionadded:: 2017.7.0
Decrypt a data structure using the specified renderer. Written originally
as a common codebase to handle decryption of encrypted elements within
Pillar data, but should be flexible enough for other uses as well.
Returns the decrypted result, but any decryption renderer should be
recursively decrypting mutable types in-place, so any data structure passed
should be automagically decrypted using this function. Immutable types
obviously won't, so it's a good idea to check if ``data`` is hashable in
the calling function, and replace the original value with the decrypted
result if that is not the case. For an example of this, see
salt.pillar.Pillar.decrypt_pillar().
data
The data to be decrypted. This can be a string of ciphertext or a data
structure. If it is a data structure, the items in the data structure
will be recursively decrypted.
rend
The renderer used to decrypt
translate_newlines : False
If True, then the renderer will convert a literal backslash followed by
an 'n' into a newline before performing the decryption.
renderers
Optionally pass a loader instance containing loaded renderer functions.
If not passed, then the ``opts`` will be required and will be used to
invoke the loader to get the available renderers. Where possible,
renderers should be passed to avoid the overhead of loading them here.
opts
The master/minion configuration opts. Used only if renderers are not
passed.
valid_rend
A list containing valid renderers, used to restrict the renderers which
this function will be allowed to use. If not passed, no restriction
will be made.
'''
try:
if valid_rend and rend not in valid_rend:
raise SaltInvocationError(
'\'{0}\' is not a valid decryption renderer. Valid choices '
'are: {1}'.format(rend, ', '.join(valid_rend))
)
except TypeError as exc:
# SaltInvocationError inherits TypeError, so check for it first and
# raise if needed.
if isinstance(exc, SaltInvocationError):
raise
# 'valid' argument is not iterable
log.error('Non-iterable value %s passed for valid_rend', valid_rend)
if renderers is None:
if opts is None:
raise TypeError('opts are required')
renderers = salt.loader.render(opts, {})
rend_func = renderers.get(rend)
if rend_func is None:
raise SaltInvocationError(
'Decryption renderer \'{0}\' is not available'.format(rend)
)
return rend_func(data, translate_newlines=translate_newlines) | python | def decrypt(data,
rend,
translate_newlines=False,
renderers=None,
opts=None,
valid_rend=None):
'''
.. versionadded:: 2017.7.0
Decrypt a data structure using the specified renderer. Written originally
as a common codebase to handle decryption of encrypted elements within
Pillar data, but should be flexible enough for other uses as well.
Returns the decrypted result, but any decryption renderer should be
recursively decrypting mutable types in-place, so any data structure passed
should be automagically decrypted using this function. Immutable types
obviously won't, so it's a good idea to check if ``data`` is hashable in
the calling function, and replace the original value with the decrypted
result if that is not the case. For an example of this, see
salt.pillar.Pillar.decrypt_pillar().
data
The data to be decrypted. This can be a string of ciphertext or a data
structure. If it is a data structure, the items in the data structure
will be recursively decrypted.
rend
The renderer used to decrypt
translate_newlines : False
If True, then the renderer will convert a literal backslash followed by
an 'n' into a newline before performing the decryption.
renderers
Optionally pass a loader instance containing loaded renderer functions.
If not passed, then the ``opts`` will be required and will be used to
invoke the loader to get the available renderers. Where possible,
renderers should be passed to avoid the overhead of loading them here.
opts
The master/minion configuration opts. Used only if renderers are not
passed.
valid_rend
A list containing valid renderers, used to restrict the renderers which
this function will be allowed to use. If not passed, no restriction
will be made.
'''
try:
if valid_rend and rend not in valid_rend:
raise SaltInvocationError(
'\'{0}\' is not a valid decryption renderer. Valid choices '
'are: {1}'.format(rend, ', '.join(valid_rend))
)
except TypeError as exc:
# SaltInvocationError inherits TypeError, so check for it first and
# raise if needed.
if isinstance(exc, SaltInvocationError):
raise
# 'valid' argument is not iterable
log.error('Non-iterable value %s passed for valid_rend', valid_rend)
if renderers is None:
if opts is None:
raise TypeError('opts are required')
renderers = salt.loader.render(opts, {})
rend_func = renderers.get(rend)
if rend_func is None:
raise SaltInvocationError(
'Decryption renderer \'{0}\' is not available'.format(rend)
)
return rend_func(data, translate_newlines=translate_newlines) | [
"def",
"decrypt",
"(",
"data",
",",
"rend",
",",
"translate_newlines",
"=",
"False",
",",
"renderers",
"=",
"None",
",",
"opts",
"=",
"None",
",",
"valid_rend",
"=",
"None",
")",
":",
"try",
":",
"if",
"valid_rend",
"and",
"rend",
"not",
"in",
"valid_r... | .. versionadded:: 2017.7.0
Decrypt a data structure using the specified renderer. Written originally
as a common codebase to handle decryption of encrypted elements within
Pillar data, but should be flexible enough for other uses as well.
Returns the decrypted result, but any decryption renderer should be
recursively decrypting mutable types in-place, so any data structure passed
should be automagically decrypted using this function. Immutable types
obviously won't, so it's a good idea to check if ``data`` is hashable in
the calling function, and replace the original value with the decrypted
result if that is not the case. For an example of this, see
salt.pillar.Pillar.decrypt_pillar().
data
The data to be decrypted. This can be a string of ciphertext or a data
structure. If it is a data structure, the items in the data structure
will be recursively decrypted.
rend
The renderer used to decrypt
translate_newlines : False
If True, then the renderer will convert a literal backslash followed by
an 'n' into a newline before performing the decryption.
renderers
Optionally pass a loader instance containing loaded renderer functions.
If not passed, then the ``opts`` will be required and will be used to
invoke the loader to get the available renderers. Where possible,
renderers should be passed to avoid the overhead of loading them here.
opts
The master/minion configuration opts. Used only if renderers are not
passed.
valid_rend
A list containing valid renderers, used to restrict the renderers which
this function will be allowed to use. If not passed, no restriction
will be made. | [
"..",
"versionadded",
"::",
"2017",
".",
"7",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/crypt.py#L27-L100 | train |
saltstack/salt | salt/utils/crypt.py | pem_finger | def pem_finger(path=None, key=None, sum_type='sha256'):
'''
Pass in either a raw pem string, or the path on disk to the location of a
pem file, and the type of cryptographic hash to use. The default is SHA256.
The fingerprint of the pem will be returned.
If neither a key nor a path are passed in, a blank string will be returned.
'''
if not key:
if not os.path.isfile(path):
return ''
with salt.utils.files.fopen(path, 'rb') as fp_:
key = b''.join([x for x in fp_.readlines() if x.strip()][1:-1])
pre = getattr(hashlib, sum_type)(key).hexdigest()
finger = ''
for ind, _ in enumerate(pre):
if ind % 2:
# Is odd
finger += '{0}:'.format(pre[ind])
else:
finger += pre[ind]
return finger.rstrip(':') | python | def pem_finger(path=None, key=None, sum_type='sha256'):
'''
Pass in either a raw pem string, or the path on disk to the location of a
pem file, and the type of cryptographic hash to use. The default is SHA256.
The fingerprint of the pem will be returned.
If neither a key nor a path are passed in, a blank string will be returned.
'''
if not key:
if not os.path.isfile(path):
return ''
with salt.utils.files.fopen(path, 'rb') as fp_:
key = b''.join([x for x in fp_.readlines() if x.strip()][1:-1])
pre = getattr(hashlib, sum_type)(key).hexdigest()
finger = ''
for ind, _ in enumerate(pre):
if ind % 2:
# Is odd
finger += '{0}:'.format(pre[ind])
else:
finger += pre[ind]
return finger.rstrip(':') | [
"def",
"pem_finger",
"(",
"path",
"=",
"None",
",",
"key",
"=",
"None",
",",
"sum_type",
"=",
"'sha256'",
")",
":",
"if",
"not",
"key",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
")",
":",
"return",
"''",
"with",
"salt",
"."... | Pass in either a raw pem string, or the path on disk to the location of a
pem file, and the type of cryptographic hash to use. The default is SHA256.
The fingerprint of the pem will be returned.
If neither a key nor a path are passed in, a blank string will be returned. | [
"Pass",
"in",
"either",
"a",
"raw",
"pem",
"string",
"or",
"the",
"path",
"on",
"disk",
"to",
"the",
"location",
"of",
"a",
"pem",
"file",
"and",
"the",
"type",
"of",
"cryptographic",
"hash",
"to",
"use",
".",
"The",
"default",
"is",
"SHA256",
".",
"... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/crypt.py#L117-L140 | train |
saltstack/salt | salt/utils/schema.py | SchemaItem._get_argname_value | def _get_argname_value(self, argname):
'''
Return the argname value looking up on all possible attributes
'''
# Let's see if there's a private function to get the value
argvalue = getattr(self, '__get_{0}__'.format(argname), None)
if argvalue is not None and callable(argvalue):
argvalue = argvalue()
if argvalue is None:
# Let's see if the value is defined as a public class variable
argvalue = getattr(self, argname, None)
if argvalue is None:
# Let's see if it's defined as a private class variable
argvalue = getattr(self, '__{0}__'.format(argname), None)
if argvalue is None:
# Let's look for it in the extra dictionary
argvalue = self.extra.get(argname, None)
return argvalue | python | def _get_argname_value(self, argname):
'''
Return the argname value looking up on all possible attributes
'''
# Let's see if there's a private function to get the value
argvalue = getattr(self, '__get_{0}__'.format(argname), None)
if argvalue is not None and callable(argvalue):
argvalue = argvalue()
if argvalue is None:
# Let's see if the value is defined as a public class variable
argvalue = getattr(self, argname, None)
if argvalue is None:
# Let's see if it's defined as a private class variable
argvalue = getattr(self, '__{0}__'.format(argname), None)
if argvalue is None:
# Let's look for it in the extra dictionary
argvalue = self.extra.get(argname, None)
return argvalue | [
"def",
"_get_argname_value",
"(",
"self",
",",
"argname",
")",
":",
"# Let's see if there's a private function to get the value",
"argvalue",
"=",
"getattr",
"(",
"self",
",",
"'__get_{0}__'",
".",
"format",
"(",
"argname",
")",
",",
"None",
")",
"if",
"argvalue",
... | Return the argname value looking up on all possible attributes | [
"Return",
"the",
"argname",
"value",
"looking",
"up",
"on",
"all",
"possible",
"attributes"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/schema.py#L731-L748 | train |
saltstack/salt | salt/utils/schema.py | BaseSchemaItem.serialize | def serialize(self):
'''
Return a serializable form of the config instance
'''
serialized = {'type': self.__type__}
for argname in self._attributes:
if argname == 'required':
# This is handled elsewhere
continue
argvalue = self._get_argname_value(argname)
if argvalue is not None:
if argvalue is Null:
argvalue = None
# None values are not meant to be included in the
# serialization, since this is not None...
if self.__serialize_attr_aliases__ and argname in self.__serialize_attr_aliases__:
argname = self.__serialize_attr_aliases__[argname]
serialized[argname] = argvalue
return serialized | python | def serialize(self):
'''
Return a serializable form of the config instance
'''
serialized = {'type': self.__type__}
for argname in self._attributes:
if argname == 'required':
# This is handled elsewhere
continue
argvalue = self._get_argname_value(argname)
if argvalue is not None:
if argvalue is Null:
argvalue = None
# None values are not meant to be included in the
# serialization, since this is not None...
if self.__serialize_attr_aliases__ and argname in self.__serialize_attr_aliases__:
argname = self.__serialize_attr_aliases__[argname]
serialized[argname] = argvalue
return serialized | [
"def",
"serialize",
"(",
"self",
")",
":",
"serialized",
"=",
"{",
"'type'",
":",
"self",
".",
"__type__",
"}",
"for",
"argname",
"in",
"self",
".",
"_attributes",
":",
"if",
"argname",
"==",
"'required'",
":",
"# This is handled elsewhere",
"continue",
"arg... | Return a serializable form of the config instance | [
"Return",
"a",
"serializable",
"form",
"of",
"the",
"config",
"instance"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/schema.py#L827-L845 | train |
saltstack/salt | salt/utils/schema.py | ComplexSchemaItem._add_missing_schema_attributes | def _add_missing_schema_attributes(self):
'''
Adds any missed schema attributes to the _attributes list
The attributes can be class attributes and they won't be
included in the _attributes list automatically
'''
for attr in [attr for attr in dir(self) if not attr.startswith('__')]:
attr_val = getattr(self, attr)
if isinstance(getattr(self, attr), SchemaItem) and \
attr not in self._attributes:
self._attributes.append(attr) | python | def _add_missing_schema_attributes(self):
'''
Adds any missed schema attributes to the _attributes list
The attributes can be class attributes and they won't be
included in the _attributes list automatically
'''
for attr in [attr for attr in dir(self) if not attr.startswith('__')]:
attr_val = getattr(self, attr)
if isinstance(getattr(self, attr), SchemaItem) and \
attr not in self._attributes:
self._attributes.append(attr) | [
"def",
"_add_missing_schema_attributes",
"(",
"self",
")",
":",
"for",
"attr",
"in",
"[",
"attr",
"for",
"attr",
"in",
"dir",
"(",
"self",
")",
"if",
"not",
"attr",
".",
"startswith",
"(",
"'__'",
")",
"]",
":",
"attr_val",
"=",
"getattr",
"(",
"self",... | Adds any missed schema attributes to the _attributes list
The attributes can be class attributes and they won't be
included in the _attributes list automatically | [
"Adds",
"any",
"missed",
"schema",
"attributes",
"to",
"the",
"_attributes",
"list"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/schema.py#L1481-L1493 | train |
saltstack/salt | salt/utils/schema.py | ComplexSchemaItem.get_definition | def get_definition(self):
'''Returns the definition of the complex item'''
serialized = super(ComplexSchemaItem, self).serialize()
# Adjust entries in the serialization
del serialized['definition_name']
serialized['title'] = self.definition_name
properties = {}
required_attr_names = []
for attr_name in self._attributes:
attr = getattr(self, attr_name)
if attr and isinstance(attr, BaseSchemaItem):
# Remove the attribute entry added by the base serialization
del serialized[attr_name]
properties[attr_name] = attr.serialize()
properties[attr_name]['type'] = attr.__type__
if attr.required:
required_attr_names.append(attr_name)
if serialized.get('properties') is None:
serialized['properties'] = {}
serialized['properties'].update(properties)
# Assign the required array
if required_attr_names:
serialized['required'] = required_attr_names
return serialized | python | def get_definition(self):
'''Returns the definition of the complex item'''
serialized = super(ComplexSchemaItem, self).serialize()
# Adjust entries in the serialization
del serialized['definition_name']
serialized['title'] = self.definition_name
properties = {}
required_attr_names = []
for attr_name in self._attributes:
attr = getattr(self, attr_name)
if attr and isinstance(attr, BaseSchemaItem):
# Remove the attribute entry added by the base serialization
del serialized[attr_name]
properties[attr_name] = attr.serialize()
properties[attr_name]['type'] = attr.__type__
if attr.required:
required_attr_names.append(attr_name)
if serialized.get('properties') is None:
serialized['properties'] = {}
serialized['properties'].update(properties)
# Assign the required array
if required_attr_names:
serialized['required'] = required_attr_names
return serialized | [
"def",
"get_definition",
"(",
"self",
")",
":",
"serialized",
"=",
"super",
"(",
"ComplexSchemaItem",
",",
"self",
")",
".",
"serialize",
"(",
")",
"# Adjust entries in the serialization",
"del",
"serialized",
"[",
"'definition_name'",
"]",
"serialized",
"[",
"'ti... | Returns the definition of the complex item | [
"Returns",
"the",
"definition",
"of",
"the",
"complex",
"item"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/schema.py#L1506-L1533 | train |
saltstack/salt | salt/utils/schema.py | ComplexSchemaItem.get_complex_attrs | def get_complex_attrs(self):
'''Returns a dictionary of the complex attributes'''
return [getattr(self, attr_name) for attr_name in self._attributes if
isinstance(getattr(self, attr_name), ComplexSchemaItem)] | python | def get_complex_attrs(self):
'''Returns a dictionary of the complex attributes'''
return [getattr(self, attr_name) for attr_name in self._attributes if
isinstance(getattr(self, attr_name), ComplexSchemaItem)] | [
"def",
"get_complex_attrs",
"(",
"self",
")",
":",
"return",
"[",
"getattr",
"(",
"self",
",",
"attr_name",
")",
"for",
"attr_name",
"in",
"self",
".",
"_attributes",
"if",
"isinstance",
"(",
"getattr",
"(",
"self",
",",
"attr_name",
")",
",",
"ComplexSche... | Returns a dictionary of the complex attributes | [
"Returns",
"a",
"dictionary",
"of",
"the",
"complex",
"attributes"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/schema.py#L1535-L1538 | train |
saltstack/salt | salt/modules/boto_rds.py | exists | def exists(name, tags=None, region=None, key=None, keyid=None, profile=None):
'''
Check to see if an RDS exists.
CLI example::
salt myminion boto_rds.exists myrds region=us-east-1
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
rds = conn.describe_db_instances(DBInstanceIdentifier=name)
return {'exists': bool(rds)}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)} | python | def exists(name, tags=None, region=None, key=None, keyid=None, profile=None):
'''
Check to see if an RDS exists.
CLI example::
salt myminion boto_rds.exists myrds region=us-east-1
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
rds = conn.describe_db_instances(DBInstanceIdentifier=name)
return {'exists': bool(rds)}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)} | [
"def",
"exists",
"(",
"name",
",",
"tags",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
"="... | Check to see if an RDS exists.
CLI example::
salt myminion boto_rds.exists myrds region=us-east-1 | [
"Check",
"to",
"see",
"if",
"an",
"RDS",
"exists",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_rds.py#L141-L155 | train |
saltstack/salt | salt/modules/boto_rds.py | option_group_exists | def option_group_exists(name, tags=None, region=None, key=None, keyid=None,
profile=None):
'''
Check to see if an RDS option group exists.
CLI example::
salt myminion boto_rds.option_group_exists myoptiongr region=us-east-1
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
rds = conn.describe_option_groups(OptionGroupName=name)
return {'exists': bool(rds)}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)} | python | def option_group_exists(name, tags=None, region=None, key=None, keyid=None,
profile=None):
'''
Check to see if an RDS option group exists.
CLI example::
salt myminion boto_rds.option_group_exists myoptiongr region=us-east-1
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
rds = conn.describe_option_groups(OptionGroupName=name)
return {'exists': bool(rds)}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)} | [
"def",
"option_group_exists",
"(",
"name",
",",
"tags",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
... | Check to see if an RDS option group exists.
CLI example::
salt myminion boto_rds.option_group_exists myoptiongr region=us-east-1 | [
"Check",
"to",
"see",
"if",
"an",
"RDS",
"option",
"group",
"exists",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_rds.py#L158-L173 | train |
saltstack/salt | salt/modules/boto_rds.py | parameter_group_exists | def parameter_group_exists(name, tags=None, region=None, key=None, keyid=None,
profile=None):
'''
Check to see if an RDS parameter group exists.
CLI example::
salt myminion boto_rds.parameter_group_exists myparametergroup \
region=us-east-1
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
rds = conn.describe_db_parameter_groups(DBParameterGroupName=name)
return {'exists': bool(rds), 'error': None}
except ClientError as e:
resp = {}
if e.response['Error']['Code'] == 'DBParameterGroupNotFound':
resp['exists'] = False
resp['error'] = __utils__['boto3.get_error'](e)
return resp | python | def parameter_group_exists(name, tags=None, region=None, key=None, keyid=None,
profile=None):
'''
Check to see if an RDS parameter group exists.
CLI example::
salt myminion boto_rds.parameter_group_exists myparametergroup \
region=us-east-1
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
rds = conn.describe_db_parameter_groups(DBParameterGroupName=name)
return {'exists': bool(rds), 'error': None}
except ClientError as e:
resp = {}
if e.response['Error']['Code'] == 'DBParameterGroupNotFound':
resp['exists'] = False
resp['error'] = __utils__['boto3.get_error'](e)
return resp | [
"def",
"parameter_group_exists",
"(",
"name",
",",
"tags",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
","... | Check to see if an RDS parameter group exists.
CLI example::
salt myminion boto_rds.parameter_group_exists myparametergroup \
region=us-east-1 | [
"Check",
"to",
"see",
"if",
"an",
"RDS",
"parameter",
"group",
"exists",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_rds.py#L176-L196 | train |
saltstack/salt | salt/modules/boto_rds.py | subnet_group_exists | def subnet_group_exists(name, tags=None, region=None, key=None, keyid=None,
profile=None):
'''
Check to see if an RDS subnet group exists.
CLI example::
salt myminion boto_rds.subnet_group_exists my-param-group \
region=us-east-1
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if not conn:
return {'exists': bool(conn)}
rds = conn.describe_db_subnet_groups(DBSubnetGroupName=name)
return {'exists': bool(rds)}
except ClientError as e:
if "DBSubnetGroupNotFoundFault" in e.message:
return {'exists': False}
else:
return {'error': __utils__['boto3.get_error'](e)} | python | def subnet_group_exists(name, tags=None, region=None, key=None, keyid=None,
profile=None):
'''
Check to see if an RDS subnet group exists.
CLI example::
salt myminion boto_rds.subnet_group_exists my-param-group \
region=us-east-1
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if not conn:
return {'exists': bool(conn)}
rds = conn.describe_db_subnet_groups(DBSubnetGroupName=name)
return {'exists': bool(rds)}
except ClientError as e:
if "DBSubnetGroupNotFoundFault" in e.message:
return {'exists': False}
else:
return {'error': __utils__['boto3.get_error'](e)} | [
"def",
"subnet_group_exists",
"(",
"name",
",",
"tags",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"try",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"r... | Check to see if an RDS subnet group exists.
CLI example::
salt myminion boto_rds.subnet_group_exists my-param-group \
region=us-east-1 | [
"Check",
"to",
"see",
"if",
"an",
"RDS",
"subnet",
"group",
"exists",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_rds.py#L199-L220 | train |
saltstack/salt | salt/modules/boto_rds.py | create | def create(name, allocated_storage, db_instance_class, engine,
master_username, master_user_password, db_name=None,
db_security_groups=None, vpc_security_group_ids=None,
vpc_security_groups=None, availability_zone=None,
db_subnet_group_name=None, preferred_maintenance_window=None,
db_parameter_group_name=None, backup_retention_period=None,
preferred_backup_window=None, port=None, multi_az=None,
engine_version=None, auto_minor_version_upgrade=None,
license_model=None, iops=None, option_group_name=None,
character_set_name=None, publicly_accessible=None, wait_status=None,
tags=None, db_cluster_identifier=None, storage_type=None,
tde_credential_arn=None, tde_credential_password=None,
storage_encrypted=None, kms_key_id=None, domain=None,
copy_tags_to_snapshot=None, monitoring_interval=None,
monitoring_role_arn=None, domain_iam_role_name=None, region=None,
promotion_tier=None, key=None, keyid=None, profile=None):
'''
Create an RDS Instance
CLI example to create an RDS Instance::
salt myminion boto_rds.create myrds 10 db.t2.micro MySQL sqlusr sqlpassw
'''
if not allocated_storage:
raise SaltInvocationError('allocated_storage is required')
if not db_instance_class:
raise SaltInvocationError('db_instance_class is required')
if not engine:
raise SaltInvocationError('engine is required')
if not master_username:
raise SaltInvocationError('master_username is required')
if not master_user_password:
raise SaltInvocationError('master_user_password is required')
if availability_zone and multi_az:
raise SaltInvocationError('availability_zone and multi_az are mutually'
' exclusive arguments.')
if wait_status:
wait_stati = ['available', 'modifying', 'backing-up']
if wait_status not in wait_stati:
raise SaltInvocationError(
'wait_status can be one of: {0}'.format(wait_stati))
if vpc_security_groups:
v_tmp = __salt__['boto_secgroup.convert_to_group_ids'](
groups=vpc_security_groups, region=region, key=key, keyid=keyid,
profile=profile)
vpc_security_group_ids = (vpc_security_group_ids + v_tmp
if vpc_security_group_ids else v_tmp)
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if not conn:
return {'results': bool(conn)}
kwargs = {}
boto_params = set(boto3_param_map.keys())
keys = set(locals().keys())
tags = _tag_doc(tags)
for param_key in keys.intersection(boto_params):
val = locals()[param_key]
if val is not None:
mapped = boto3_param_map[param_key]
kwargs[mapped[0]] = mapped[1](val)
# Validation doesn't want parameters that are None
# https://github.com/boto/boto3/issues/400
kwargs = dict((k, v) for k, v in six.iteritems(kwargs) if v is not None)
rds = conn.create_db_instance(**kwargs)
if not rds:
return {'created': False}
if not wait_status:
return {'created': True, 'message':
'RDS instance {0} created.'.format(name)}
while True:
jmespath = 'DBInstances[*].DBInstanceStatus'
status = describe_db_instances(name=name, jmespath=jmespath,
region=region, key=key, keyid=keyid,
profile=profile)
if status:
stat = status[0]
else:
# Whoops, something is horribly wrong...
return {'created': False,
'error': "RDS instance {0} should have been created but"
" now I can't find it.".format(name)}
if stat == wait_status:
return {'created': True,
'message': 'RDS instance {0} created (current status '
'{1})'.format(name, stat)}
time.sleep(10)
log.info('Instance status after 10 seconds is: %s', stat)
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)} | python | def create(name, allocated_storage, db_instance_class, engine,
master_username, master_user_password, db_name=None,
db_security_groups=None, vpc_security_group_ids=None,
vpc_security_groups=None, availability_zone=None,
db_subnet_group_name=None, preferred_maintenance_window=None,
db_parameter_group_name=None, backup_retention_period=None,
preferred_backup_window=None, port=None, multi_az=None,
engine_version=None, auto_minor_version_upgrade=None,
license_model=None, iops=None, option_group_name=None,
character_set_name=None, publicly_accessible=None, wait_status=None,
tags=None, db_cluster_identifier=None, storage_type=None,
tde_credential_arn=None, tde_credential_password=None,
storage_encrypted=None, kms_key_id=None, domain=None,
copy_tags_to_snapshot=None, monitoring_interval=None,
monitoring_role_arn=None, domain_iam_role_name=None, region=None,
promotion_tier=None, key=None, keyid=None, profile=None):
'''
Create an RDS Instance
CLI example to create an RDS Instance::
salt myminion boto_rds.create myrds 10 db.t2.micro MySQL sqlusr sqlpassw
'''
if not allocated_storage:
raise SaltInvocationError('allocated_storage is required')
if not db_instance_class:
raise SaltInvocationError('db_instance_class is required')
if not engine:
raise SaltInvocationError('engine is required')
if not master_username:
raise SaltInvocationError('master_username is required')
if not master_user_password:
raise SaltInvocationError('master_user_password is required')
if availability_zone and multi_az:
raise SaltInvocationError('availability_zone and multi_az are mutually'
' exclusive arguments.')
if wait_status:
wait_stati = ['available', 'modifying', 'backing-up']
if wait_status not in wait_stati:
raise SaltInvocationError(
'wait_status can be one of: {0}'.format(wait_stati))
if vpc_security_groups:
v_tmp = __salt__['boto_secgroup.convert_to_group_ids'](
groups=vpc_security_groups, region=region, key=key, keyid=keyid,
profile=profile)
vpc_security_group_ids = (vpc_security_group_ids + v_tmp
if vpc_security_group_ids else v_tmp)
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if not conn:
return {'results': bool(conn)}
kwargs = {}
boto_params = set(boto3_param_map.keys())
keys = set(locals().keys())
tags = _tag_doc(tags)
for param_key in keys.intersection(boto_params):
val = locals()[param_key]
if val is not None:
mapped = boto3_param_map[param_key]
kwargs[mapped[0]] = mapped[1](val)
# Validation doesn't want parameters that are None
# https://github.com/boto/boto3/issues/400
kwargs = dict((k, v) for k, v in six.iteritems(kwargs) if v is not None)
rds = conn.create_db_instance(**kwargs)
if not rds:
return {'created': False}
if not wait_status:
return {'created': True, 'message':
'RDS instance {0} created.'.format(name)}
while True:
jmespath = 'DBInstances[*].DBInstanceStatus'
status = describe_db_instances(name=name, jmespath=jmespath,
region=region, key=key, keyid=keyid,
profile=profile)
if status:
stat = status[0]
else:
# Whoops, something is horribly wrong...
return {'created': False,
'error': "RDS instance {0} should have been created but"
" now I can't find it.".format(name)}
if stat == wait_status:
return {'created': True,
'message': 'RDS instance {0} created (current status '
'{1})'.format(name, stat)}
time.sleep(10)
log.info('Instance status after 10 seconds is: %s', stat)
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)} | [
"def",
"create",
"(",
"name",
",",
"allocated_storage",
",",
"db_instance_class",
",",
"engine",
",",
"master_username",
",",
"master_user_password",
",",
"db_name",
"=",
"None",
",",
"db_security_groups",
"=",
"None",
",",
"vpc_security_group_ids",
"=",
"None",
"... | Create an RDS Instance
CLI example to create an RDS Instance::
salt myminion boto_rds.create myrds 10 db.t2.micro MySQL sqlusr sqlpassw | [
"Create",
"an",
"RDS",
"Instance"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_rds.py#L223-L319 | train |
saltstack/salt | salt/modules/boto_rds.py | create_read_replica | def create_read_replica(name, source_name, db_instance_class=None,
availability_zone=None, port=None,
auto_minor_version_upgrade=None, iops=None,
option_group_name=None, publicly_accessible=None,
tags=None, db_subnet_group_name=None,
storage_type=None, copy_tags_to_snapshot=None,
monitoring_interval=None, monitoring_role_arn=None,
region=None, key=None, keyid=None, profile=None):
'''
Create an RDS read replica
CLI example to create an RDS read replica::
salt myminion boto_rds.create_read_replica replicaname source_name
'''
if not backup_retention_period:
raise SaltInvocationError('backup_retention_period is required')
res = __salt__['boto_rds.exists'](source_name, tags, region, key, keyid, profile)
if not res.get('exists'):
return {'exists': bool(res), 'message':
'RDS instance source {0} does not exists.'.format(source_name)}
res = __salt__['boto_rds.exists'](name, tags, region, key, keyid, profile)
if res.get('exists'):
return {'exists': bool(res), 'message':
'RDS replica instance {0} already exists.'.format(name)}
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
kwargs = {}
for key in ('OptionGroupName', 'MonitoringRoleArn'):
if locals()[key] is not None:
kwargs[key] = str(locals()[key]) # future lint: disable=blacklisted-function
for key in ('MonitoringInterval', 'Iops', 'Port'):
if locals()[key] is not None:
kwargs[key] = int(locals()[key])
for key in ('CopyTagsToSnapshot', 'AutoMinorVersionUpgrade'):
if locals()[key] is not None:
kwargs[key] = bool(locals()[key])
taglist = _tag_doc(tags)
rds_replica = conn.create_db_instance_read_replica(DBInstanceIdentifier=name,
SourceDBInstanceIdentifier=source_name,
DBInstanceClass=db_instance_class,
AvailabilityZone=availability_zone,
PubliclyAccessible=publicly_accessible,
Tags=taglist, DBSubnetGroupName=db_subnet_group_name,
StorageType=storage_type,
**kwargs)
return {'exists': bool(rds_replica)}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)} | python | def create_read_replica(name, source_name, db_instance_class=None,
availability_zone=None, port=None,
auto_minor_version_upgrade=None, iops=None,
option_group_name=None, publicly_accessible=None,
tags=None, db_subnet_group_name=None,
storage_type=None, copy_tags_to_snapshot=None,
monitoring_interval=None, monitoring_role_arn=None,
region=None, key=None, keyid=None, profile=None):
'''
Create an RDS read replica
CLI example to create an RDS read replica::
salt myminion boto_rds.create_read_replica replicaname source_name
'''
if not backup_retention_period:
raise SaltInvocationError('backup_retention_period is required')
res = __salt__['boto_rds.exists'](source_name, tags, region, key, keyid, profile)
if not res.get('exists'):
return {'exists': bool(res), 'message':
'RDS instance source {0} does not exists.'.format(source_name)}
res = __salt__['boto_rds.exists'](name, tags, region, key, keyid, profile)
if res.get('exists'):
return {'exists': bool(res), 'message':
'RDS replica instance {0} already exists.'.format(name)}
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
kwargs = {}
for key in ('OptionGroupName', 'MonitoringRoleArn'):
if locals()[key] is not None:
kwargs[key] = str(locals()[key]) # future lint: disable=blacklisted-function
for key in ('MonitoringInterval', 'Iops', 'Port'):
if locals()[key] is not None:
kwargs[key] = int(locals()[key])
for key in ('CopyTagsToSnapshot', 'AutoMinorVersionUpgrade'):
if locals()[key] is not None:
kwargs[key] = bool(locals()[key])
taglist = _tag_doc(tags)
rds_replica = conn.create_db_instance_read_replica(DBInstanceIdentifier=name,
SourceDBInstanceIdentifier=source_name,
DBInstanceClass=db_instance_class,
AvailabilityZone=availability_zone,
PubliclyAccessible=publicly_accessible,
Tags=taglist, DBSubnetGroupName=db_subnet_group_name,
StorageType=storage_type,
**kwargs)
return {'exists': bool(rds_replica)}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)} | [
"def",
"create_read_replica",
"(",
"name",
",",
"source_name",
",",
"db_instance_class",
"=",
"None",
",",
"availability_zone",
"=",
"None",
",",
"port",
"=",
"None",
",",
"auto_minor_version_upgrade",
"=",
"None",
",",
"iops",
"=",
"None",
",",
"option_group_na... | Create an RDS read replica
CLI example to create an RDS read replica::
salt myminion boto_rds.create_read_replica replicaname source_name | [
"Create",
"an",
"RDS",
"read",
"replica"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_rds.py#L322-L377 | train |
saltstack/salt | salt/modules/boto_rds.py | create_option_group | def create_option_group(name, engine_name, major_engine_version,
option_group_description, tags=None, region=None,
key=None, keyid=None, profile=None):
'''
Create an RDS option group
CLI example to create an RDS option group::
salt myminion boto_rds.create_option_group my-opt-group mysql 5.6 \
"group description"
'''
res = __salt__['boto_rds.option_group_exists'](name, tags, region, key, keyid,
profile)
if res.get('exists'):
return {'exists': bool(res)}
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if not conn:
return {'results': bool(conn)}
taglist = _tag_doc(tags)
rds = conn.create_option_group(OptionGroupName=name,
EngineName=engine_name,
MajorEngineVersion=major_engine_version,
OptionGroupDescription=option_group_description,
Tags=taglist)
return {'exists': bool(rds)}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)} | python | def create_option_group(name, engine_name, major_engine_version,
option_group_description, tags=None, region=None,
key=None, keyid=None, profile=None):
'''
Create an RDS option group
CLI example to create an RDS option group::
salt myminion boto_rds.create_option_group my-opt-group mysql 5.6 \
"group description"
'''
res = __salt__['boto_rds.option_group_exists'](name, tags, region, key, keyid,
profile)
if res.get('exists'):
return {'exists': bool(res)}
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if not conn:
return {'results': bool(conn)}
taglist = _tag_doc(tags)
rds = conn.create_option_group(OptionGroupName=name,
EngineName=engine_name,
MajorEngineVersion=major_engine_version,
OptionGroupDescription=option_group_description,
Tags=taglist)
return {'exists': bool(rds)}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)} | [
"def",
"create_option_group",
"(",
"name",
",",
"engine_name",
",",
"major_engine_version",
",",
"option_group_description",
",",
"tags",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None"... | Create an RDS option group
CLI example to create an RDS option group::
salt myminion boto_rds.create_option_group my-opt-group mysql 5.6 \
"group description" | [
"Create",
"an",
"RDS",
"option",
"group"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_rds.py#L380-L410 | train |
saltstack/salt | salt/modules/boto_rds.py | create_parameter_group | def create_parameter_group(name, db_parameter_group_family, description,
tags=None, region=None, key=None, keyid=None,
profile=None):
'''
Create an RDS parameter group
CLI example to create an RDS parameter group::
salt myminion boto_rds.create_parameter_group my-param-group mysql5.6 \
"group description"
'''
res = __salt__['boto_rds.parameter_group_exists'](name, tags, region, key,
keyid, profile)
if res.get('exists'):
return {'exists': bool(res)}
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if not conn:
return {'results': bool(conn)}
taglist = _tag_doc(tags)
rds = conn.create_db_parameter_group(DBParameterGroupName=name,
DBParameterGroupFamily=db_parameter_group_family,
Description=description,
Tags=taglist)
if not rds:
return {'created': False, 'message':
'Failed to create RDS parameter group {0}'.format(name)}
return {'exists': bool(rds), 'message':
'Created RDS parameter group {0}'.format(name)}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)} | python | def create_parameter_group(name, db_parameter_group_family, description,
tags=None, region=None, key=None, keyid=None,
profile=None):
'''
Create an RDS parameter group
CLI example to create an RDS parameter group::
salt myminion boto_rds.create_parameter_group my-param-group mysql5.6 \
"group description"
'''
res = __salt__['boto_rds.parameter_group_exists'](name, tags, region, key,
keyid, profile)
if res.get('exists'):
return {'exists': bool(res)}
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if not conn:
return {'results': bool(conn)}
taglist = _tag_doc(tags)
rds = conn.create_db_parameter_group(DBParameterGroupName=name,
DBParameterGroupFamily=db_parameter_group_family,
Description=description,
Tags=taglist)
if not rds:
return {'created': False, 'message':
'Failed to create RDS parameter group {0}'.format(name)}
return {'exists': bool(rds), 'message':
'Created RDS parameter group {0}'.format(name)}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)} | [
"def",
"create_parameter_group",
"(",
"name",
",",
"db_parameter_group_family",
",",
"description",
",",
"tags",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"res",
"=... | Create an RDS parameter group
CLI example to create an RDS parameter group::
salt myminion boto_rds.create_parameter_group my-param-group mysql5.6 \
"group description" | [
"Create",
"an",
"RDS",
"parameter",
"group"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_rds.py#L413-L446 | train |
saltstack/salt | salt/modules/boto_rds.py | create_subnet_group | def create_subnet_group(name, description, subnet_ids, tags=None,
region=None, key=None, keyid=None, profile=None):
'''
Create an RDS subnet group
CLI example to create an RDS subnet group::
salt myminion boto_rds.create_subnet_group my-subnet-group \
"group description" '[subnet-12345678, subnet-87654321]' \
region=us-east-1
'''
res = __salt__['boto_rds.subnet_group_exists'](name, tags, region, key,
keyid, profile)
if res.get('exists'):
return {'exists': bool(res)}
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if not conn:
return {'results': bool(conn)}
taglist = _tag_doc(tags)
rds = conn.create_db_subnet_group(DBSubnetGroupName=name,
DBSubnetGroupDescription=description,
SubnetIds=subnet_ids, Tags=taglist)
return {'created': bool(rds)}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)} | python | def create_subnet_group(name, description, subnet_ids, tags=None,
region=None, key=None, keyid=None, profile=None):
'''
Create an RDS subnet group
CLI example to create an RDS subnet group::
salt myminion boto_rds.create_subnet_group my-subnet-group \
"group description" '[subnet-12345678, subnet-87654321]' \
region=us-east-1
'''
res = __salt__['boto_rds.subnet_group_exists'](name, tags, region, key,
keyid, profile)
if res.get('exists'):
return {'exists': bool(res)}
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if not conn:
return {'results': bool(conn)}
taglist = _tag_doc(tags)
rds = conn.create_db_subnet_group(DBSubnetGroupName=name,
DBSubnetGroupDescription=description,
SubnetIds=subnet_ids, Tags=taglist)
return {'created': bool(rds)}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)} | [
"def",
"create_subnet_group",
"(",
"name",
",",
"description",
",",
"subnet_ids",
",",
"tags",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"res",
"=",
"__salt__",
... | Create an RDS subnet group
CLI example to create an RDS subnet group::
salt myminion boto_rds.create_subnet_group my-subnet-group \
"group description" '[subnet-12345678, subnet-87654321]' \
region=us-east-1 | [
"Create",
"an",
"RDS",
"subnet",
"group"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_rds.py#L449-L477 | train |
saltstack/salt | salt/modules/boto_rds.py | update_parameter_group | def update_parameter_group(name, parameters, apply_method="pending-reboot",
tags=None, region=None, key=None, keyid=None,
profile=None):
'''
Update an RDS parameter group.
CLI example::
salt myminion boto_rds.update_parameter_group my-param-group \
parameters='{"back_log":1, "binlog_cache_size":4096}' \
region=us-east-1
'''
res = __salt__['boto_rds.parameter_group_exists'](name, tags, region, key,
keyid, profile)
if not res.get('exists'):
return {'exists': bool(res), 'message':
'RDS parameter group {0} does not exist.'.format(name)}
param_list = []
for key, value in six.iteritems(parameters):
item = odict.OrderedDict()
item.update({'ParameterName': key})
item.update({'ApplyMethod': apply_method})
if type(value) is bool:
item.update({'ParameterValue': 'on' if value else 'off'})
else:
item.update({'ParameterValue': str(value)}) # future lint: disable=blacklisted-function
param_list.append(item)
if not param_list:
return {'results': False}
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if not conn:
return {'results': bool(conn)}
res = conn.modify_db_parameter_group(DBParameterGroupName=name,
Parameters=param_list)
return {'results': bool(res)}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)} | python | def update_parameter_group(name, parameters, apply_method="pending-reboot",
tags=None, region=None, key=None, keyid=None,
profile=None):
'''
Update an RDS parameter group.
CLI example::
salt myminion boto_rds.update_parameter_group my-param-group \
parameters='{"back_log":1, "binlog_cache_size":4096}' \
region=us-east-1
'''
res = __salt__['boto_rds.parameter_group_exists'](name, tags, region, key,
keyid, profile)
if not res.get('exists'):
return {'exists': bool(res), 'message':
'RDS parameter group {0} does not exist.'.format(name)}
param_list = []
for key, value in six.iteritems(parameters):
item = odict.OrderedDict()
item.update({'ParameterName': key})
item.update({'ApplyMethod': apply_method})
if type(value) is bool:
item.update({'ParameterValue': 'on' if value else 'off'})
else:
item.update({'ParameterValue': str(value)}) # future lint: disable=blacklisted-function
param_list.append(item)
if not param_list:
return {'results': False}
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if not conn:
return {'results': bool(conn)}
res = conn.modify_db_parameter_group(DBParameterGroupName=name,
Parameters=param_list)
return {'results': bool(res)}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)} | [
"def",
"update_parameter_group",
"(",
"name",
",",
"parameters",
",",
"apply_method",
"=",
"\"pending-reboot\"",
",",
"tags",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
"... | Update an RDS parameter group.
CLI example::
salt myminion boto_rds.update_parameter_group my-param-group \
parameters='{"back_log":1, "binlog_cache_size":4096}' \
region=us-east-1 | [
"Update",
"an",
"RDS",
"parameter",
"group",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_rds.py#L480-L522 | train |
saltstack/salt | salt/modules/boto_rds.py | describe | def describe(name, tags=None, region=None, key=None, keyid=None,
profile=None):
'''
Return RDS instance details.
CLI example::
salt myminion boto_rds.describe myrds
'''
res = __salt__['boto_rds.exists'](name, tags, region, key, keyid,
profile)
if not res.get('exists'):
return {'exists': bool(res), 'message':
'RDS instance {0} does not exist.'.format(name)}
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if not conn:
return {'results': bool(conn)}
rds = conn.describe_db_instances(DBInstanceIdentifier=name)
rds = [
i for i in rds.get('DBInstances', [])
if i.get('DBInstanceIdentifier') == name
].pop(0)
if rds:
keys = ('DBInstanceIdentifier', 'DBInstanceClass', 'Engine',
'DBInstanceStatus', 'DBName', 'AllocatedStorage',
'PreferredBackupWindow', 'BackupRetentionPeriod',
'AvailabilityZone', 'PreferredMaintenanceWindow',
'LatestRestorableTime', 'EngineVersion',
'AutoMinorVersionUpgrade', 'LicenseModel',
'Iops', 'CharacterSetName', 'PubliclyAccessible',
'StorageType', 'TdeCredentialArn', 'DBInstancePort',
'DBClusterIdentifier', 'StorageEncrypted', 'KmsKeyId',
'DbiResourceId', 'CACertificateIdentifier',
'CopyTagsToSnapshot', 'MonitoringInterval',
'MonitoringRoleArn', 'PromotionTier',
'DomainMemberships')
return {'rds': dict([(k, rds.get(k)) for k in keys])}
else:
return {'rds': None}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
except IndexError:
return {'rds': None} | python | def describe(name, tags=None, region=None, key=None, keyid=None,
profile=None):
'''
Return RDS instance details.
CLI example::
salt myminion boto_rds.describe myrds
'''
res = __salt__['boto_rds.exists'](name, tags, region, key, keyid,
profile)
if not res.get('exists'):
return {'exists': bool(res), 'message':
'RDS instance {0} does not exist.'.format(name)}
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if not conn:
return {'results': bool(conn)}
rds = conn.describe_db_instances(DBInstanceIdentifier=name)
rds = [
i for i in rds.get('DBInstances', [])
if i.get('DBInstanceIdentifier') == name
].pop(0)
if rds:
keys = ('DBInstanceIdentifier', 'DBInstanceClass', 'Engine',
'DBInstanceStatus', 'DBName', 'AllocatedStorage',
'PreferredBackupWindow', 'BackupRetentionPeriod',
'AvailabilityZone', 'PreferredMaintenanceWindow',
'LatestRestorableTime', 'EngineVersion',
'AutoMinorVersionUpgrade', 'LicenseModel',
'Iops', 'CharacterSetName', 'PubliclyAccessible',
'StorageType', 'TdeCredentialArn', 'DBInstancePort',
'DBClusterIdentifier', 'StorageEncrypted', 'KmsKeyId',
'DbiResourceId', 'CACertificateIdentifier',
'CopyTagsToSnapshot', 'MonitoringInterval',
'MonitoringRoleArn', 'PromotionTier',
'DomainMemberships')
return {'rds': dict([(k, rds.get(k)) for k in keys])}
else:
return {'rds': None}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
except IndexError:
return {'rds': None} | [
"def",
"describe",
"(",
"name",
",",
"tags",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"res",
"=",
"__salt__",
"[",
"'boto_rds.exists'",
"]",
"(",
"name",
","... | Return RDS instance details.
CLI example::
salt myminion boto_rds.describe myrds | [
"Return",
"RDS",
"instance",
"details",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_rds.py#L525-L572 | train |
saltstack/salt | salt/modules/boto_rds.py | describe_db_instances | def describe_db_instances(name=None, filters=None, jmespath='DBInstances',
region=None, key=None, keyid=None, profile=None):
'''
Return a detailed listing of some, or all, DB Instances visible in the
current scope. Arbitrary subelements or subsections of the returned dataset
can be selected by passing in a valid JMSEPath filter as well.
CLI example::
salt myminion boto_rds.describe_db_instances jmespath='DBInstances[*].DBInstanceIdentifier'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
pag = conn.get_paginator('describe_db_instances')
args = {}
args.update({'DBInstanceIdentifier': name}) if name else None
args.update({'Filters': filters}) if filters else None
pit = pag.paginate(**args)
pit = pit.search(jmespath) if jmespath else pit
try:
return [p for p in pit]
except ClientError as e:
code = getattr(e, 'response', {}).get('Error', {}).get('Code')
if code != 'DBInstanceNotFound':
log.error(__utils__['boto3.get_error'](e))
return [] | python | def describe_db_instances(name=None, filters=None, jmespath='DBInstances',
region=None, key=None, keyid=None, profile=None):
'''
Return a detailed listing of some, or all, DB Instances visible in the
current scope. Arbitrary subelements or subsections of the returned dataset
can be selected by passing in a valid JMSEPath filter as well.
CLI example::
salt myminion boto_rds.describe_db_instances jmespath='DBInstances[*].DBInstanceIdentifier'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
pag = conn.get_paginator('describe_db_instances')
args = {}
args.update({'DBInstanceIdentifier': name}) if name else None
args.update({'Filters': filters}) if filters else None
pit = pag.paginate(**args)
pit = pit.search(jmespath) if jmespath else pit
try:
return [p for p in pit]
except ClientError as e:
code = getattr(e, 'response', {}).get('Error', {}).get('Code')
if code != 'DBInstanceNotFound':
log.error(__utils__['boto3.get_error'](e))
return [] | [
"def",
"describe_db_instances",
"(",
"name",
"=",
"None",
",",
"filters",
"=",
"None",
",",
"jmespath",
"=",
"'DBInstances'",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"conn",... | Return a detailed listing of some, or all, DB Instances visible in the
current scope. Arbitrary subelements or subsections of the returned dataset
can be selected by passing in a valid JMSEPath filter as well.
CLI example::
salt myminion boto_rds.describe_db_instances jmespath='DBInstances[*].DBInstanceIdentifier' | [
"Return",
"a",
"detailed",
"listing",
"of",
"some",
"or",
"all",
"DB",
"Instances",
"visible",
"in",
"the",
"current",
"scope",
".",
"Arbitrary",
"subelements",
"or",
"subsections",
"of",
"the",
"returned",
"dataset",
"can",
"be",
"selected",
"by",
"passing",
... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_rds.py#L575-L600 | train |
saltstack/salt | salt/modules/boto_rds.py | describe_db_subnet_groups | def describe_db_subnet_groups(name=None, filters=None, jmespath='DBSubnetGroups',
region=None, key=None, keyid=None, profile=None):
'''
Return a detailed listing of some, or all, DB Subnet Groups visible in the
current scope. Arbitrary subelements or subsections of the returned dataset
can be selected by passing in a valid JMSEPath filter as well.
CLI example::
salt myminion boto_rds.describe_db_subnet_groups
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
pag = conn.get_paginator('describe_db_subnet_groups')
args = {}
args.update({'DBSubnetGroupName': name}) if name else None
args.update({'Filters': filters}) if filters else None
pit = pag.paginate(**args)
pit = pit.search(jmespath) if jmespath else pit
return [p for p in pit] | python | def describe_db_subnet_groups(name=None, filters=None, jmespath='DBSubnetGroups',
region=None, key=None, keyid=None, profile=None):
'''
Return a detailed listing of some, or all, DB Subnet Groups visible in the
current scope. Arbitrary subelements or subsections of the returned dataset
can be selected by passing in a valid JMSEPath filter as well.
CLI example::
salt myminion boto_rds.describe_db_subnet_groups
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
pag = conn.get_paginator('describe_db_subnet_groups')
args = {}
args.update({'DBSubnetGroupName': name}) if name else None
args.update({'Filters': filters}) if filters else None
pit = pag.paginate(**args)
pit = pit.search(jmespath) if jmespath else pit
return [p for p in pit] | [
"def",
"describe_db_subnet_groups",
"(",
"name",
"=",
"None",
",",
"filters",
"=",
"None",
",",
"jmespath",
"=",
"'DBSubnetGroups'",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
... | Return a detailed listing of some, or all, DB Subnet Groups visible in the
current scope. Arbitrary subelements or subsections of the returned dataset
can be selected by passing in a valid JMSEPath filter as well.
CLI example::
salt myminion boto_rds.describe_db_subnet_groups | [
"Return",
"a",
"detailed",
"listing",
"of",
"some",
"or",
"all",
"DB",
"Subnet",
"Groups",
"visible",
"in",
"the",
"current",
"scope",
".",
"Arbitrary",
"subelements",
"or",
"subsections",
"of",
"the",
"returned",
"dataset",
"can",
"be",
"selected",
"by",
"p... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_rds.py#L603-L622 | train |
saltstack/salt | salt/modules/boto_rds.py | get_endpoint | def get_endpoint(name, tags=None, region=None, key=None, keyid=None,
profile=None):
'''
Return the endpoint of an RDS instance.
CLI example::
salt myminion boto_rds.get_endpoint myrds
'''
endpoint = False
res = __salt__['boto_rds.exists'](name, tags, region, key, keyid,
profile)
if res.get('exists'):
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if conn:
rds = conn.describe_db_instances(DBInstanceIdentifier=name)
if rds and 'Endpoint' in rds['DBInstances'][0]:
endpoint = rds['DBInstances'][0]['Endpoint']['Address']
return endpoint
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
return endpoint | python | def get_endpoint(name, tags=None, region=None, key=None, keyid=None,
profile=None):
'''
Return the endpoint of an RDS instance.
CLI example::
salt myminion boto_rds.get_endpoint myrds
'''
endpoint = False
res = __salt__['boto_rds.exists'](name, tags, region, key, keyid,
profile)
if res.get('exists'):
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if conn:
rds = conn.describe_db_instances(DBInstanceIdentifier=name)
if rds and 'Endpoint' in rds['DBInstances'][0]:
endpoint = rds['DBInstances'][0]['Endpoint']['Address']
return endpoint
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
return endpoint | [
"def",
"get_endpoint",
"(",
"name",
",",
"tags",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"endpoint",
"=",
"False",
"res",
"=",
"__salt__",
"[",
"'boto_rds.exi... | Return the endpoint of an RDS instance.
CLI example::
salt myminion boto_rds.get_endpoint myrds | [
"Return",
"the",
"endpoint",
"of",
"an",
"RDS",
"instance",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_rds.py#L625-L651 | train |
saltstack/salt | salt/modules/boto_rds.py | delete | def delete(name, skip_final_snapshot=None, final_db_snapshot_identifier=None,
region=None, key=None, keyid=None, profile=None, tags=None,
wait_for_deletion=True, timeout=180):
'''
Delete an RDS instance.
CLI example::
salt myminion boto_rds.delete myrds skip_final_snapshot=True \
region=us-east-1
'''
if timeout == 180 and not skip_final_snapshot:
timeout = 420
if not skip_final_snapshot and not final_db_snapshot_identifier:
raise SaltInvocationError('At least one of the following must'
' be specified: skip_final_snapshot'
' final_db_snapshot_identifier')
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if not conn:
return {'deleted': bool(conn)}
kwargs = {}
if locals()['skip_final_snapshot'] is not None:
kwargs['SkipFinalSnapshot'] = bool(locals()['skip_final_snapshot'])
if locals()['final_db_snapshot_identifier'] is not None:
kwargs['FinalDBSnapshotIdentifier'] = str(locals()['final_db_snapshot_identifier']) # future lint: disable=blacklisted-function
res = conn.delete_db_instance(DBInstanceIdentifier=name, **kwargs)
if not wait_for_deletion:
return {'deleted': bool(res), 'message':
'Deleted RDS instance {0}.'.format(name)}
start_time = time.time()
while True:
res = __salt__['boto_rds.exists'](name=name, tags=tags, region=region,
key=key, keyid=keyid,
profile=profile)
if not res.get('exists'):
return {'deleted': bool(res), 'message':
'Deleted RDS instance {0} completely.'.format(name)}
if time.time() - start_time > timeout:
raise SaltInvocationError('RDS instance {0} has not been '
'deleted completely after {1} '
'seconds'.format(name, timeout))
log.info('Waiting up to %s seconds for RDS instance %s to be '
'deleted.', timeout, name)
time.sleep(10)
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)} | python | def delete(name, skip_final_snapshot=None, final_db_snapshot_identifier=None,
region=None, key=None, keyid=None, profile=None, tags=None,
wait_for_deletion=True, timeout=180):
'''
Delete an RDS instance.
CLI example::
salt myminion boto_rds.delete myrds skip_final_snapshot=True \
region=us-east-1
'''
if timeout == 180 and not skip_final_snapshot:
timeout = 420
if not skip_final_snapshot and not final_db_snapshot_identifier:
raise SaltInvocationError('At least one of the following must'
' be specified: skip_final_snapshot'
' final_db_snapshot_identifier')
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if not conn:
return {'deleted': bool(conn)}
kwargs = {}
if locals()['skip_final_snapshot'] is not None:
kwargs['SkipFinalSnapshot'] = bool(locals()['skip_final_snapshot'])
if locals()['final_db_snapshot_identifier'] is not None:
kwargs['FinalDBSnapshotIdentifier'] = str(locals()['final_db_snapshot_identifier']) # future lint: disable=blacklisted-function
res = conn.delete_db_instance(DBInstanceIdentifier=name, **kwargs)
if not wait_for_deletion:
return {'deleted': bool(res), 'message':
'Deleted RDS instance {0}.'.format(name)}
start_time = time.time()
while True:
res = __salt__['boto_rds.exists'](name=name, tags=tags, region=region,
key=key, keyid=keyid,
profile=profile)
if not res.get('exists'):
return {'deleted': bool(res), 'message':
'Deleted RDS instance {0} completely.'.format(name)}
if time.time() - start_time > timeout:
raise SaltInvocationError('RDS instance {0} has not been '
'deleted completely after {1} '
'seconds'.format(name, timeout))
log.info('Waiting up to %s seconds for RDS instance %s to be '
'deleted.', timeout, name)
time.sleep(10)
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)} | [
"def",
"delete",
"(",
"name",
",",
"skip_final_snapshot",
"=",
"None",
",",
"final_db_snapshot_identifier",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
",",
"tags",
"=",
"None"... | Delete an RDS instance.
CLI example::
salt myminion boto_rds.delete myrds skip_final_snapshot=True \
region=us-east-1 | [
"Delete",
"an",
"RDS",
"instance",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_rds.py#L654-L708 | train |
saltstack/salt | salt/modules/boto_rds.py | delete_option_group | def delete_option_group(name, region=None, key=None, keyid=None, profile=None):
'''
Delete an RDS option group.
CLI example::
salt myminion boto_rds.delete_option_group my-opt-group \
region=us-east-1
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if not conn:
return {'deleted': bool(conn)}
res = conn.delete_option_group(OptionGroupName=name)
if not res:
return {'deleted': bool(res), 'message':
'Failed to delete RDS option group {0}.'.format(name)}
return {'deleted': bool(res), 'message':
'Deleted RDS option group {0}.'.format(name)}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)} | python | def delete_option_group(name, region=None, key=None, keyid=None, profile=None):
'''
Delete an RDS option group.
CLI example::
salt myminion boto_rds.delete_option_group my-opt-group \
region=us-east-1
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if not conn:
return {'deleted': bool(conn)}
res = conn.delete_option_group(OptionGroupName=name)
if not res:
return {'deleted': bool(res), 'message':
'Failed to delete RDS option group {0}.'.format(name)}
return {'deleted': bool(res), 'message':
'Deleted RDS option group {0}.'.format(name)}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)} | [
"def",
"delete_option_group",
"(",
"name",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"try",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
"=",
"... | Delete an RDS option group.
CLI example::
salt myminion boto_rds.delete_option_group my-opt-group \
region=us-east-1 | [
"Delete",
"an",
"RDS",
"option",
"group",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_rds.py#L711-L733 | train |
saltstack/salt | salt/modules/boto_rds.py | delete_parameter_group | def delete_parameter_group(name, region=None, key=None, keyid=None,
profile=None):
'''
Delete an RDS parameter group.
CLI example::
salt myminion boto_rds.delete_parameter_group my-param-group \
region=us-east-1
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if not conn:
return {'results': bool(conn)}
r = conn.delete_db_parameter_group(DBParameterGroupName=name)
return {'deleted': bool(r), 'message':
'Deleted RDS parameter group {0}.'.format(name)}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)} | python | def delete_parameter_group(name, region=None, key=None, keyid=None,
profile=None):
'''
Delete an RDS parameter group.
CLI example::
salt myminion boto_rds.delete_parameter_group my-param-group \
region=us-east-1
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if not conn:
return {'results': bool(conn)}
r = conn.delete_db_parameter_group(DBParameterGroupName=name)
return {'deleted': bool(r), 'message':
'Deleted RDS parameter group {0}.'.format(name)}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)} | [
"def",
"delete_parameter_group",
"(",
"name",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"try",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
"=",
... | Delete an RDS parameter group.
CLI example::
salt myminion boto_rds.delete_parameter_group my-param-group \
region=us-east-1 | [
"Delete",
"an",
"RDS",
"parameter",
"group",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_rds.py#L736-L755 | train |
saltstack/salt | salt/modules/boto_rds.py | delete_subnet_group | def delete_subnet_group(name, region=None, key=None, keyid=None,
profile=None):
'''
Delete an RDS subnet group.
CLI example::
salt myminion boto_rds.delete_subnet_group my-subnet-group \
region=us-east-1
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if not conn:
return {'results': bool(conn)}
r = conn.delete_db_subnet_group(DBSubnetGroupName=name)
return {'deleted': bool(r), 'message':
'Deleted RDS subnet group {0}.'.format(name)}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)} | python | def delete_subnet_group(name, region=None, key=None, keyid=None,
profile=None):
'''
Delete an RDS subnet group.
CLI example::
salt myminion boto_rds.delete_subnet_group my-subnet-group \
region=us-east-1
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if not conn:
return {'results': bool(conn)}
r = conn.delete_db_subnet_group(DBSubnetGroupName=name)
return {'deleted': bool(r), 'message':
'Deleted RDS subnet group {0}.'.format(name)}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)} | [
"def",
"delete_subnet_group",
"(",
"name",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"try",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
"=",
"... | Delete an RDS subnet group.
CLI example::
salt myminion boto_rds.delete_subnet_group my-subnet-group \
region=us-east-1 | [
"Delete",
"an",
"RDS",
"subnet",
"group",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_rds.py#L758-L777 | train |
saltstack/salt | salt/modules/boto_rds.py | describe_parameter_group | def describe_parameter_group(name, Filters=None, MaxRecords=None, Marker=None,
region=None, key=None, keyid=None, profile=None):
'''
Returns a list of `DBParameterGroup` descriptions.
CLI example to description of parameter group::
salt myminion boto_rds.describe_parameter_group parametergroupname\
region=us-east-1
'''
res = __salt__['boto_rds.parameter_group_exists'](name, tags=None,
region=region, key=key,
keyid=keyid,
profile=profile)
if not res.get('exists'):
return {'exists': bool(res)}
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if not conn:
return {'results': bool(conn)}
kwargs = {}
for key in ('Marker', 'Filters'):
if locals()[key] is not None:
kwargs[key] = str(locals()[key]) # future lint: disable=blacklisted-function
if locals()['MaxRecords'] is not None:
kwargs['MaxRecords'] = int(locals()['MaxRecords'])
info = conn.describe_db_parameter_groups(DBParameterGroupName=name,
**kwargs)
if not info:
return {'results': bool(info), 'message':
'Failed to get RDS description for group {0}.'.format(name)}
return {'results': bool(info), 'message':
'Got RDS descrition for group {0}.'.format(name)}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)} | python | def describe_parameter_group(name, Filters=None, MaxRecords=None, Marker=None,
region=None, key=None, keyid=None, profile=None):
'''
Returns a list of `DBParameterGroup` descriptions.
CLI example to description of parameter group::
salt myminion boto_rds.describe_parameter_group parametergroupname\
region=us-east-1
'''
res = __salt__['boto_rds.parameter_group_exists'](name, tags=None,
region=region, key=key,
keyid=keyid,
profile=profile)
if not res.get('exists'):
return {'exists': bool(res)}
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if not conn:
return {'results': bool(conn)}
kwargs = {}
for key in ('Marker', 'Filters'):
if locals()[key] is not None:
kwargs[key] = str(locals()[key]) # future lint: disable=blacklisted-function
if locals()['MaxRecords'] is not None:
kwargs['MaxRecords'] = int(locals()['MaxRecords'])
info = conn.describe_db_parameter_groups(DBParameterGroupName=name,
**kwargs)
if not info:
return {'results': bool(info), 'message':
'Failed to get RDS description for group {0}.'.format(name)}
return {'results': bool(info), 'message':
'Got RDS descrition for group {0}.'.format(name)}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)} | [
"def",
"describe_parameter_group",
"(",
"name",
",",
"Filters",
"=",
"None",
",",
"MaxRecords",
"=",
"None",
",",
"Marker",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
... | Returns a list of `DBParameterGroup` descriptions.
CLI example to description of parameter group::
salt myminion boto_rds.describe_parameter_group parametergroupname\
region=us-east-1 | [
"Returns",
"a",
"list",
"of",
"DBParameterGroup",
"descriptions",
".",
"CLI",
"example",
"to",
"description",
"of",
"parameter",
"group",
"::"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_rds.py#L780-L819 | train |
saltstack/salt | salt/modules/boto_rds.py | describe_parameters | def describe_parameters(name, Source=None, MaxRecords=None, Marker=None,
region=None, key=None, keyid=None, profile=None):
'''
Returns a list of `DBParameterGroup` parameters.
CLI example to description of parameters ::
salt myminion boto_rds.describe_parameters parametergroupname\
region=us-east-1
'''
res = __salt__['boto_rds.parameter_group_exists'](name, tags=None,
region=region, key=key,
keyid=keyid,
profile=profile)
if not res.get('exists'):
return {'result': False,
'message': 'Parameter group {0} does not exist'.format(name)}
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if not conn:
return {'result': False,
'message': 'Could not establish a connection to RDS'}
kwargs = {}
kwargs.update({'DBParameterGroupName': name})
for key in ('Marker', 'Source'):
if locals()[key] is not None:
kwargs[key] = str(locals()[key]) # future lint: disable=blacklisted-function
if locals()['MaxRecords'] is not None:
kwargs['MaxRecords'] = int(locals()['MaxRecords'])
pag = conn.get_paginator('describe_db_parameters')
pit = pag.paginate(**kwargs)
keys = ['ParameterName', 'ParameterValue', 'Description',
'Source', 'ApplyType', 'DataType', 'AllowedValues',
'IsModifieable', 'MinimumEngineVersion', 'ApplyMethod']
parameters = odict.OrderedDict()
ret = {'result': True}
for p in pit:
for result in p['Parameters']:
data = odict.OrderedDict()
for k in keys:
data[k] = result.get(k)
parameters[result.get('ParameterName')] = data
ret['parameters'] = parameters
return ret
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)} | python | def describe_parameters(name, Source=None, MaxRecords=None, Marker=None,
region=None, key=None, keyid=None, profile=None):
'''
Returns a list of `DBParameterGroup` parameters.
CLI example to description of parameters ::
salt myminion boto_rds.describe_parameters parametergroupname\
region=us-east-1
'''
res = __salt__['boto_rds.parameter_group_exists'](name, tags=None,
region=region, key=key,
keyid=keyid,
profile=profile)
if not res.get('exists'):
return {'result': False,
'message': 'Parameter group {0} does not exist'.format(name)}
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if not conn:
return {'result': False,
'message': 'Could not establish a connection to RDS'}
kwargs = {}
kwargs.update({'DBParameterGroupName': name})
for key in ('Marker', 'Source'):
if locals()[key] is not None:
kwargs[key] = str(locals()[key]) # future lint: disable=blacklisted-function
if locals()['MaxRecords'] is not None:
kwargs['MaxRecords'] = int(locals()['MaxRecords'])
pag = conn.get_paginator('describe_db_parameters')
pit = pag.paginate(**kwargs)
keys = ['ParameterName', 'ParameterValue', 'Description',
'Source', 'ApplyType', 'DataType', 'AllowedValues',
'IsModifieable', 'MinimumEngineVersion', 'ApplyMethod']
parameters = odict.OrderedDict()
ret = {'result': True}
for p in pit:
for result in p['Parameters']:
data = odict.OrderedDict()
for k in keys:
data[k] = result.get(k)
parameters[result.get('ParameterName')] = data
ret['parameters'] = parameters
return ret
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)} | [
"def",
"describe_parameters",
"(",
"name",
",",
"Source",
"=",
"None",
",",
"MaxRecords",
"=",
"None",
",",
"Marker",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
... | Returns a list of `DBParameterGroup` parameters.
CLI example to description of parameters ::
salt myminion boto_rds.describe_parameters parametergroupname\
region=us-east-1 | [
"Returns",
"a",
"list",
"of",
"DBParameterGroup",
"parameters",
".",
"CLI",
"example",
"to",
"description",
"of",
"parameters",
"::"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_rds.py#L822-L875 | train |
saltstack/salt | salt/modules/boto_rds.py | modify_db_instance | def modify_db_instance(name,
allocated_storage=None,
allow_major_version_upgrade=None,
apply_immediately=None,
auto_minor_version_upgrade=None,
backup_retention_period=None,
ca_certificate_identifier=None,
character_set_name=None,
copy_tags_to_snapshot=None,
db_cluster_identifier=None,
db_instance_class=None,
db_name=None,
db_parameter_group_name=None,
db_port_number=None,
db_security_groups=None,
db_subnet_group_name=None,
domain=None,
domain_iam_role_name=None,
engine_version=None,
iops=None,
kms_key_id=None,
license_model=None,
master_user_password=None,
monitoring_interval=None,
monitoring_role_arn=None,
multi_az=None,
new_db_instance_identifier=None,
option_group_name=None,
preferred_backup_window=None,
preferred_maintenance_window=None,
promotion_tier=None,
publicly_accessible=None,
storage_encrypted=None,
storage_type=None,
tde_credential_arn=None,
tde_credential_password=None,
vpc_security_group_ids=None,
region=None, key=None, keyid=None, profile=None):
'''
Modify settings for a DB instance.
CLI example to description of parameters ::
salt myminion boto_rds.modify_db_instance db_instance_identifier region=us-east-1
'''
res = __salt__['boto_rds.exists'](name, tags=None, region=region, key=key, keyid=keyid, profile=profile)
if not res.get('exists'):
return {'modified': False, 'message':
'RDS db instance {0} does not exist.'.format(name)}
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if not conn:
return {'modified': False}
kwargs = {}
excluded = set(('name',))
boto_params = set(boto3_param_map.keys())
keys = set(locals().keys())
for key in keys.intersection(boto_params).difference(excluded):
val = locals()[key]
if val is not None:
mapped = boto3_param_map[key]
kwargs[mapped[0]] = mapped[1](val)
info = conn.modify_db_instance(DBInstanceIdentifier=name, **kwargs)
if not info:
return {'modified': bool(info), 'message':
'Failed to modify RDS db instance {0}.'.format(name)}
return {'modified': bool(info), 'message':
'Modified RDS db instance {0}.'.format(name),
'results': dict(info)}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)} | python | def modify_db_instance(name,
allocated_storage=None,
allow_major_version_upgrade=None,
apply_immediately=None,
auto_minor_version_upgrade=None,
backup_retention_period=None,
ca_certificate_identifier=None,
character_set_name=None,
copy_tags_to_snapshot=None,
db_cluster_identifier=None,
db_instance_class=None,
db_name=None,
db_parameter_group_name=None,
db_port_number=None,
db_security_groups=None,
db_subnet_group_name=None,
domain=None,
domain_iam_role_name=None,
engine_version=None,
iops=None,
kms_key_id=None,
license_model=None,
master_user_password=None,
monitoring_interval=None,
monitoring_role_arn=None,
multi_az=None,
new_db_instance_identifier=None,
option_group_name=None,
preferred_backup_window=None,
preferred_maintenance_window=None,
promotion_tier=None,
publicly_accessible=None,
storage_encrypted=None,
storage_type=None,
tde_credential_arn=None,
tde_credential_password=None,
vpc_security_group_ids=None,
region=None, key=None, keyid=None, profile=None):
'''
Modify settings for a DB instance.
CLI example to description of parameters ::
salt myminion boto_rds.modify_db_instance db_instance_identifier region=us-east-1
'''
res = __salt__['boto_rds.exists'](name, tags=None, region=region, key=key, keyid=keyid, profile=profile)
if not res.get('exists'):
return {'modified': False, 'message':
'RDS db instance {0} does not exist.'.format(name)}
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if not conn:
return {'modified': False}
kwargs = {}
excluded = set(('name',))
boto_params = set(boto3_param_map.keys())
keys = set(locals().keys())
for key in keys.intersection(boto_params).difference(excluded):
val = locals()[key]
if val is not None:
mapped = boto3_param_map[key]
kwargs[mapped[0]] = mapped[1](val)
info = conn.modify_db_instance(DBInstanceIdentifier=name, **kwargs)
if not info:
return {'modified': bool(info), 'message':
'Failed to modify RDS db instance {0}.'.format(name)}
return {'modified': bool(info), 'message':
'Modified RDS db instance {0}.'.format(name),
'results': dict(info)}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)} | [
"def",
"modify_db_instance",
"(",
"name",
",",
"allocated_storage",
"=",
"None",
",",
"allow_major_version_upgrade",
"=",
"None",
",",
"apply_immediately",
"=",
"None",
",",
"auto_minor_version_upgrade",
"=",
"None",
",",
"backup_retention_period",
"=",
"None",
",",
... | Modify settings for a DB instance.
CLI example to description of parameters ::
salt myminion boto_rds.modify_db_instance db_instance_identifier region=us-east-1 | [
"Modify",
"settings",
"for",
"a",
"DB",
"instance",
".",
"CLI",
"example",
"to",
"description",
"of",
"parameters",
"::"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_rds.py#L878-L952 | train |
saltstack/salt | salt/beacons/sensehat.py | beacon | def beacon(config):
'''
Monitor the temperature, humidity and pressure using the SenseHat sensors.
You can either specify a threshold for each value and only emit a beacon
if it is exceeded or define a range and emit a beacon when the value is
out of range.
Units:
* humidity: percent
* temperature: degrees Celsius
* temperature_from_pressure: degrees Celsius
* pressure: Millibars
.. code-block:: yaml
beacons:
sensehat:
- sensors:
humidity: 70%
temperature: [20, 40]
temperature_from_pressure: 40
pressure: 1500
'''
ret = []
min_default = {
'humidity': '0',
'pressure': '0',
'temperature': '-273.15'
}
_config = {}
list(map(_config.update, config))
for sensor in _config.get('sensors', {}):
sensor_function = 'sensehat.get_{0}'.format(sensor)
if sensor_function not in __salt__:
log.error('No sensor for meassuring %s. Skipping.', sensor)
continue
sensor_config = _config['sensors'][sensor]
if isinstance(sensor_config, list):
sensor_min = six.text_type(sensor_config[0])
sensor_max = six.text_type(sensor_config[1])
else:
sensor_min = min_default.get(sensor, '0')
sensor_max = six.text_type(sensor_config)
if '%' in sensor_min:
sensor_min = re.sub('%', '', sensor_min)
if '%' in sensor_max:
sensor_max = re.sub('%', '', sensor_max)
sensor_min = float(sensor_min)
sensor_max = float(sensor_max)
current_value = __salt__[sensor_function]()
if not sensor_min <= current_value <= sensor_max:
ret.append({
'tag': 'sensehat/{0}'.format(sensor),
sensor: current_value
})
return ret | python | def beacon(config):
'''
Monitor the temperature, humidity and pressure using the SenseHat sensors.
You can either specify a threshold for each value and only emit a beacon
if it is exceeded or define a range and emit a beacon when the value is
out of range.
Units:
* humidity: percent
* temperature: degrees Celsius
* temperature_from_pressure: degrees Celsius
* pressure: Millibars
.. code-block:: yaml
beacons:
sensehat:
- sensors:
humidity: 70%
temperature: [20, 40]
temperature_from_pressure: 40
pressure: 1500
'''
ret = []
min_default = {
'humidity': '0',
'pressure': '0',
'temperature': '-273.15'
}
_config = {}
list(map(_config.update, config))
for sensor in _config.get('sensors', {}):
sensor_function = 'sensehat.get_{0}'.format(sensor)
if sensor_function not in __salt__:
log.error('No sensor for meassuring %s. Skipping.', sensor)
continue
sensor_config = _config['sensors'][sensor]
if isinstance(sensor_config, list):
sensor_min = six.text_type(sensor_config[0])
sensor_max = six.text_type(sensor_config[1])
else:
sensor_min = min_default.get(sensor, '0')
sensor_max = six.text_type(sensor_config)
if '%' in sensor_min:
sensor_min = re.sub('%', '', sensor_min)
if '%' in sensor_max:
sensor_max = re.sub('%', '', sensor_max)
sensor_min = float(sensor_min)
sensor_max = float(sensor_max)
current_value = __salt__[sensor_function]()
if not sensor_min <= current_value <= sensor_max:
ret.append({
'tag': 'sensehat/{0}'.format(sensor),
sensor: current_value
})
return ret | [
"def",
"beacon",
"(",
"config",
")",
":",
"ret",
"=",
"[",
"]",
"min_default",
"=",
"{",
"'humidity'",
":",
"'0'",
",",
"'pressure'",
":",
"'0'",
",",
"'temperature'",
":",
"'-273.15'",
"}",
"_config",
"=",
"{",
"}",
"list",
"(",
"map",
"(",
"_config... | Monitor the temperature, humidity and pressure using the SenseHat sensors.
You can either specify a threshold for each value and only emit a beacon
if it is exceeded or define a range and emit a beacon when the value is
out of range.
Units:
* humidity: percent
* temperature: degrees Celsius
* temperature_from_pressure: degrees Celsius
* pressure: Millibars
.. code-block:: yaml
beacons:
sensehat:
- sensors:
humidity: 70%
temperature: [20, 40]
temperature_from_pressure: 40
pressure: 1500 | [
"Monitor",
"the",
"temperature",
"humidity",
"and",
"pressure",
"using",
"the",
"SenseHat",
"sensors",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/beacons/sensehat.py#L47-L109 | train |
saltstack/salt | salt/states/nova.py | flavor_present | def flavor_present(name, params=None, **kwargs):
'''
Creates Nova flavor if it does not exist
:param name: Flavor name
:param params: Definition of the Flavor (see Compute API documentation)
.. code-block:: yaml
nova-flavor-present:
nova.flavor_present:
- name: myflavor
- params:
ram: 2
vcpus: 1
disk: 10
is_public: False
'''
dry_run = __opts__['test']
ret = {'name': name, 'result': False, 'comment': '', 'changes': {}}
if params is None:
params = {}
try:
kwargs.update({'filter': {'is_public': None}})
object_list = __salt__['nova.flavor_list'](**kwargs)
object_exists = True if object_list[name]['name'] == name else False
except KeyError:
object_exists = False
if object_exists:
ret['result'] = True
ret['comment'] = 'Flavor "{0}" already exists.'.format(name)
else:
if dry_run:
ret['result'] = None
ret['comment'] = 'Flavor "{0}" would be created.'.format(name)
ret['changes'] = {name: {'old': 'Flavor "{0}" does not exist.'.format(name),
'new': params}}
else:
combined = kwargs.copy()
combined.update(params)
flavor_create = __salt__['nova.flavor_create'](name, **combined)
if flavor_create:
ret['result'] = True
ret['comment'] = 'Flavor "{0}" created.'.format(name)
ret['changes'] = {name: {'old': 'Flavor "{0}" does not exist.'.format(name),
'new': flavor_create}}
return ret | python | def flavor_present(name, params=None, **kwargs):
'''
Creates Nova flavor if it does not exist
:param name: Flavor name
:param params: Definition of the Flavor (see Compute API documentation)
.. code-block:: yaml
nova-flavor-present:
nova.flavor_present:
- name: myflavor
- params:
ram: 2
vcpus: 1
disk: 10
is_public: False
'''
dry_run = __opts__['test']
ret = {'name': name, 'result': False, 'comment': '', 'changes': {}}
if params is None:
params = {}
try:
kwargs.update({'filter': {'is_public': None}})
object_list = __salt__['nova.flavor_list'](**kwargs)
object_exists = True if object_list[name]['name'] == name else False
except KeyError:
object_exists = False
if object_exists:
ret['result'] = True
ret['comment'] = 'Flavor "{0}" already exists.'.format(name)
else:
if dry_run:
ret['result'] = None
ret['comment'] = 'Flavor "{0}" would be created.'.format(name)
ret['changes'] = {name: {'old': 'Flavor "{0}" does not exist.'.format(name),
'new': params}}
else:
combined = kwargs.copy()
combined.update(params)
flavor_create = __salt__['nova.flavor_create'](name, **combined)
if flavor_create:
ret['result'] = True
ret['comment'] = 'Flavor "{0}" created.'.format(name)
ret['changes'] = {name: {'old': 'Flavor "{0}" does not exist.'.format(name),
'new': flavor_create}}
return ret | [
"def",
"flavor_present",
"(",
"name",
",",
"params",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"dry_run",
"=",
"__opts__",
"[",
"'test'",
"]",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"False",
",",
"'comment'",
":",
"''",
... | Creates Nova flavor if it does not exist
:param name: Flavor name
:param params: Definition of the Flavor (see Compute API documentation)
.. code-block:: yaml
nova-flavor-present:
nova.flavor_present:
- name: myflavor
- params:
ram: 2
vcpus: 1
disk: 10
is_public: False | [
"Creates",
"Nova",
"flavor",
"if",
"it",
"does",
"not",
"exist"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/nova.py#L27-L78 | train |
saltstack/salt | salt/states/nova.py | flavor_access_list | def flavor_access_list(name, projects, **kwargs):
'''
Grants access of the flavor to a project. Flavor must be private.
:param name: non-public flavor name
:param projects: list of projects which should have the access to the flavor
.. code-block:: yaml
nova-flavor-share:
nova.flavor_project_access:
- name: myflavor
- project:
- project1
- project2
To remove all project from access list:
.. code-block:: yaml
- project: []
'''
dry_run = __opts__['test']
ret = {'name': name, 'result': False, 'comment': '', 'changes': {}}
kwargs.update({'filter': {'is_public': False}})
try:
flavor_list = __salt__['nova.flavor_list'](**kwargs)
flavor_id = flavor_list[name]['id']
except KeyError:
raise
project_list = __salt__['keystone.project_list'](**kwargs)
access_list = __salt__['nova.flavor_access_list'](flavor_id, **kwargs)
existing_list = [six.text_type(pname) for pname in project_list
if project_list[pname]['id'] in access_list[flavor_id]]
defined_list = [six.text_type(project) for project in projects]
add_list = set(defined_list) - set(existing_list)
remove_list = set(existing_list) - set(defined_list)
if not add_list and not remove_list:
ret['result'] = True
ret['comment'] = 'Flavor "{0}" access list corresponds to defined one.'.format(name)
else:
if dry_run:
ret['result'] = None
ret['comment'] = 'Flavor "{0}" access list would be corrected.'.format(name)
ret['changes'] = {name: {'new': defined_list, 'old': existing_list}}
else:
added = []
removed = []
if add_list:
for project in add_list:
added.append(__salt__['nova.flavor_access_add'](flavor_id, project_list[project]['id'], **kwargs))
if remove_list:
for project in remove_list:
removed.append(__salt__['nova.flavor_access_remove'](flavor_id,
project_list[project]['id'], **kwargs))
if any(add_list) or any(remove_list):
ret['result'] = True
ret['comment'] = 'Flavor "{0}" access list corrected.'.format(name)
ret['changes'] = {name: {'new': defined_list, 'old': existing_list}}
return ret | python | def flavor_access_list(name, projects, **kwargs):
'''
Grants access of the flavor to a project. Flavor must be private.
:param name: non-public flavor name
:param projects: list of projects which should have the access to the flavor
.. code-block:: yaml
nova-flavor-share:
nova.flavor_project_access:
- name: myflavor
- project:
- project1
- project2
To remove all project from access list:
.. code-block:: yaml
- project: []
'''
dry_run = __opts__['test']
ret = {'name': name, 'result': False, 'comment': '', 'changes': {}}
kwargs.update({'filter': {'is_public': False}})
try:
flavor_list = __salt__['nova.flavor_list'](**kwargs)
flavor_id = flavor_list[name]['id']
except KeyError:
raise
project_list = __salt__['keystone.project_list'](**kwargs)
access_list = __salt__['nova.flavor_access_list'](flavor_id, **kwargs)
existing_list = [six.text_type(pname) for pname in project_list
if project_list[pname]['id'] in access_list[flavor_id]]
defined_list = [six.text_type(project) for project in projects]
add_list = set(defined_list) - set(existing_list)
remove_list = set(existing_list) - set(defined_list)
if not add_list and not remove_list:
ret['result'] = True
ret['comment'] = 'Flavor "{0}" access list corresponds to defined one.'.format(name)
else:
if dry_run:
ret['result'] = None
ret['comment'] = 'Flavor "{0}" access list would be corrected.'.format(name)
ret['changes'] = {name: {'new': defined_list, 'old': existing_list}}
else:
added = []
removed = []
if add_list:
for project in add_list:
added.append(__salt__['nova.flavor_access_add'](flavor_id, project_list[project]['id'], **kwargs))
if remove_list:
for project in remove_list:
removed.append(__salt__['nova.flavor_access_remove'](flavor_id,
project_list[project]['id'], **kwargs))
if any(add_list) or any(remove_list):
ret['result'] = True
ret['comment'] = 'Flavor "{0}" access list corrected.'.format(name)
ret['changes'] = {name: {'new': defined_list, 'old': existing_list}}
return ret | [
"def",
"flavor_access_list",
"(",
"name",
",",
"projects",
",",
"*",
"*",
"kwargs",
")",
":",
"dry_run",
"=",
"__opts__",
"[",
"'test'",
"]",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"False",
",",
"'comment'",
":",
"''",
",",
"'c... | Grants access of the flavor to a project. Flavor must be private.
:param name: non-public flavor name
:param projects: list of projects which should have the access to the flavor
.. code-block:: yaml
nova-flavor-share:
nova.flavor_project_access:
- name: myflavor
- project:
- project1
- project2
To remove all project from access list:
.. code-block:: yaml
- project: [] | [
"Grants",
"access",
"of",
"the",
"flavor",
"to",
"a",
"project",
".",
"Flavor",
"must",
"be",
"private",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/nova.py#L81-L141 | train |
saltstack/salt | salt/states/nova.py | flavor_absent | def flavor_absent(name, **kwargs):
'''
Makes flavor to be absent
:param name: flavor name
.. code-block:: yaml
nova-flavor-absent:
nova.flavor_absent:
- name: flavor_name
'''
dry_run = __opts__['test']
ret = {'name': name, 'result': False, 'comment': '', 'changes': {}}
try:
object_list = __salt__['nova.flavor_list'](**kwargs)
object_id = object_list[name]['id']
except KeyError:
object_id = False
if not object_id:
ret['result'] = True
ret['comment'] = 'Flavor "{0}" does not exist.'.format(name)
else:
if dry_run:
ret['result'] = None
ret['comment'] = 'Flavor "{0}", id: {1} would be deleted.'.format(name, object_id)
ret['changes'] = {name: {'old': 'Flavor "{0}", id: {1} exists.'.format(name, object_id),
'new': ret['comment']}}
else:
flavor_delete = __salt__['nova.flavor_delete'](object_id, **kwargs)
if flavor_delete:
ret['result'] = True
ret['comment'] = 'Flavor "{0}", id: {1} deleted.'.format(name, object_id)
ret['changes'] = {name: {'old': 'Flavor "{0}", id: {1} existed.'.format(name, object_id),
'new': ret['comment']}}
return ret | python | def flavor_absent(name, **kwargs):
'''
Makes flavor to be absent
:param name: flavor name
.. code-block:: yaml
nova-flavor-absent:
nova.flavor_absent:
- name: flavor_name
'''
dry_run = __opts__['test']
ret = {'name': name, 'result': False, 'comment': '', 'changes': {}}
try:
object_list = __salt__['nova.flavor_list'](**kwargs)
object_id = object_list[name]['id']
except KeyError:
object_id = False
if not object_id:
ret['result'] = True
ret['comment'] = 'Flavor "{0}" does not exist.'.format(name)
else:
if dry_run:
ret['result'] = None
ret['comment'] = 'Flavor "{0}", id: {1} would be deleted.'.format(name, object_id)
ret['changes'] = {name: {'old': 'Flavor "{0}", id: {1} exists.'.format(name, object_id),
'new': ret['comment']}}
else:
flavor_delete = __salt__['nova.flavor_delete'](object_id, **kwargs)
if flavor_delete:
ret['result'] = True
ret['comment'] = 'Flavor "{0}", id: {1} deleted.'.format(name, object_id)
ret['changes'] = {name: {'old': 'Flavor "{0}", id: {1} existed.'.format(name, object_id),
'new': ret['comment']}}
return ret | [
"def",
"flavor_absent",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"dry_run",
"=",
"__opts__",
"[",
"'test'",
"]",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"False",
",",
"'comment'",
":",
"''",
",",
"'changes'",
":",
"{",
... | Makes flavor to be absent
:param name: flavor name
.. code-block:: yaml
nova-flavor-absent:
nova.flavor_absent:
- name: flavor_name | [
"Makes",
"flavor",
"to",
"be",
"absent"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/nova.py#L144-L183 | train |
saltstack/salt | salt/matchers/nodegroup_match.py | match | def match(tgt, nodegroups=None, opts=None):
'''
This is a compatibility matcher and is NOT called when using
nodegroups for remote execution, but is called when the nodegroups
matcher is used in states
'''
if not opts:
opts = __opts__
if not nodegroups:
log.debug('Nodegroup matcher called with no nodegroups.')
return False
if tgt in nodegroups:
matchers = salt.loader.matchers(opts)
return matchers['compound_match.match'](
salt.utils.minions.nodegroup_comp(tgt, nodegroups)
)
return False | python | def match(tgt, nodegroups=None, opts=None):
'''
This is a compatibility matcher and is NOT called when using
nodegroups for remote execution, but is called when the nodegroups
matcher is used in states
'''
if not opts:
opts = __opts__
if not nodegroups:
log.debug('Nodegroup matcher called with no nodegroups.')
return False
if tgt in nodegroups:
matchers = salt.loader.matchers(opts)
return matchers['compound_match.match'](
salt.utils.minions.nodegroup_comp(tgt, nodegroups)
)
return False | [
"def",
"match",
"(",
"tgt",
",",
"nodegroups",
"=",
"None",
",",
"opts",
"=",
"None",
")",
":",
"if",
"not",
"opts",
":",
"opts",
"=",
"__opts__",
"if",
"not",
"nodegroups",
":",
"log",
".",
"debug",
"(",
"'Nodegroup matcher called with no nodegroups.'",
"... | This is a compatibility matcher and is NOT called when using
nodegroups for remote execution, but is called when the nodegroups
matcher is used in states | [
"This",
"is",
"a",
"compatibility",
"matcher",
"and",
"is",
"NOT",
"called",
"when",
"using",
"nodegroups",
"for",
"remote",
"execution",
"but",
"is",
"called",
"when",
"the",
"nodegroups",
"matcher",
"is",
"used",
"in",
"states"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/matchers/nodegroup_match.py#L14-L30 | train |
saltstack/salt | salt/states/ldap.py | managed | def managed(name, entries, connect_spec=None):
'''Ensure the existence (or not) of LDAP entries and their attributes
Example:
.. code-block:: yaml
ldapi:///:
ldap.managed:
- connect_spec:
bind:
method: sasl
- entries:
# make sure the entry doesn't exist
- cn=foo,ou=users,dc=example,dc=com:
- delete_others: True
# make sure the entry exists with only the specified
# attribute values
- cn=admin,dc=example,dc=com:
- delete_others: True
- replace:
cn:
- admin
description:
- LDAP administrator
objectClass:
- simpleSecurityObject
- organizationalRole
userPassword:
- {{pillar.ldap_admin_password}}
# make sure the entry exists, its olcRootDN attribute
# has only the specified value, the olcRootDN attribute
# doesn't exist, and all other attributes are ignored
- 'olcDatabase={1}hdb,cn=config':
- replace:
olcRootDN:
- cn=admin,dc=example,dc=com
# the admin entry has its own password attribute
olcRootPW: []
# note the use of 'default'. also note how you don't
# have to use list syntax if there is only one attribute
# value
- cn=foo,ou=users,dc=example,dc=com:
- delete_others: True
- default:
userPassword: changeme
shadowLastChange: 0
# keep sshPublicKey if present, but don't create
# the attribute if it is missing
sshPublicKey: []
- replace:
cn: foo
uid: foo
uidNumber: 1000
gidNumber: 1000
gecos: Foo Bar
givenName: Foo
sn: Bar
homeDirectory: /home/foo
loginShell: /bin/bash
objectClass:
- inetOrgPerson
- posixAccount
- top
- ldapPublicKey
- shadowAccount
:param name:
The URL of the LDAP server. This is ignored if
``connect_spec`` is either a connection object or a dict with
a ``'url'`` entry.
:param entries:
A description of the desired state of zero or more LDAP
entries.
``entries`` is an iterable of dicts. Each of these dict's
keys are the distinguished names (DNs) of LDAP entries to
manage. Each of these dicts is processed in order. A later
dict can reference an LDAP entry that was already mentioned in
an earlier dict, which makes it possible for later dicts to
enhance or alter the desired state of an LDAP entry.
The DNs are mapped to a description of the LDAP entry's
desired state. These LDAP entry descriptions are themselves
iterables of dicts. Each dict in the iterable is processed in
order. They contain directives controlling the entry's state.
The key names the directive type and the value is state
information for the directive. The specific structure of the
state information depends on the directive type.
The structure of ``entries`` looks like this::
[{dn1: [{directive1: directive1_state,
directive2: directive2_state},
{directive3: directive3_state}],
dn2: [{directive4: directive4_state,
directive5: directive5_state}]},
{dn3: [{directive6: directive6_state}]}]
These are the directives:
* ``'delete_others'``
Boolean indicating whether to delete attributes not
mentioned in this dict or any of the other directive
dicts for this DN. Defaults to ``False``.
If you don't want to delete an attribute if present, but
you also don't want to add it if it is missing or modify
it if it is present, you can use either the ``'default'``
directive or the ``'add'`` directive with an empty value
list.
* ``'default'``
A dict mapping an attribute name to an iterable of default
values for that attribute. If the attribute already
exists, it is left alone. If not, it is created using the
given list of values.
An empty value list is useful when you don't want to
create an attribute if it is missing but you do want to
preserve it if the ``'delete_others'`` key is ``True``.
* ``'add'``
Attribute values to add to the entry. This is a dict
mapping an attribute name to an iterable of values to add.
An empty value list is useful when you don't want to
create an attribute if it is missing but you do want to
preserve it if the ``'delete_others'`` key is ``True``.
* ``'delete'``
Attribute values to remove from the entry. This is a dict
mapping an attribute name to an iterable of values to
delete from the attribute. If the iterable is empty, all
of the attribute's values are deleted.
* ``'replace'``
Attributes to replace. This is a dict mapping an
attribute name to an iterable of values. Any existing
values for the attribute are deleted, then the given
values are added. The iterable may be empty.
In the above directives, the iterables of attribute values may
instead be ``None``, in which case an empty list is used, or a
scalar such as a string or number, in which case a new list
containing the scalar is used.
Note that if all attribute values are removed from an entry,
the entire entry is deleted.
:param connect_spec:
See the description of the ``connect_spec`` parameter of the
:py:func:`ldap3.connect <salt.modules.ldap3.connect>` function
in the :py:mod:`ldap3 <salt.modules.ldap3>` execution module.
If this is a dict and the ``'url'`` entry is not specified,
the ``'url'`` entry is set to the value of the ``name``
parameter.
:returns:
A dict with the following keys:
* ``'name'``
This is the same object passed to the ``name`` parameter.
* ``'changes'``
This is a dict describing the changes made (or, in test
mode, the changes that would have been attempted). If no
changes were made (or no changes would have been
attempted), then this dict is empty. Only successful
changes are included.
Each key is a DN of an entry that was changed (or would
have been changed). Entries that were not changed (or
would not have been changed) are not included. The value
is a dict with two keys:
* ``'old'``
The state of the entry before modification. If the
entry did not previously exist, this key maps to
``None``. Otherwise, the value is a dict mapping each
of the old entry's attributes to a list of its values
before any modifications were made. Unchanged
attributes are excluded from this dict.
* ``'new'``
The state of the entry after modification. If the
entry was deleted, this key maps to ``None``.
Otherwise, the value is a dict mapping each of the
entry's attributes to a list of its values after the
modifications were made. Unchanged attributes are
excluded from this dict.
Example ``'changes'`` dict where a new entry was created
with a single attribute containing two values::
{'dn1': {'old': None,
'new': {'attr1': ['val1', 'val2']}}}
Example ``'changes'`` dict where a new attribute was added
to an existing entry::
{'dn1': {'old': {},
'new': {'attr2': ['val3']}}}
* ``'result'``
One of the following values:
* ``True`` if no changes were necessary or if all changes
were applied successfully.
* ``False`` if at least one change was unable to be applied.
* ``None`` if changes would be applied but it is in test
mode.
'''
if connect_spec is None:
connect_spec = {}
try:
connect_spec.setdefault('url', name)
except AttributeError:
# already a connection object
pass
connect = __salt__['ldap3.connect']
# hack to get at the ldap3 module to access the ldap3.LDAPError
# exception class. https://github.com/saltstack/salt/issues/27578
ldap3 = inspect.getmodule(connect)
with connect(connect_spec) as l:
old, new = _process_entries(l, entries)
# collect all of the affected entries (only the key is
# important in this dict; would have used an OrderedSet if
# there was one)
dn_set = OrderedDict()
dn_set.update(old)
dn_set.update(new)
# do some cleanup
dn_to_delete = set()
for dn in dn_set:
o = old.get(dn, {})
n = new.get(dn, {})
for x in o, n:
to_delete = set()
for attr, vals in six.iteritems(x):
if not vals:
# clean out empty attribute lists
to_delete.add(attr)
for attr in to_delete:
del x[attr]
if o == n:
# clean out unchanged entries
dn_to_delete.add(dn)
for dn in dn_to_delete:
for x in old, new:
x.pop(dn, None)
del dn_set[dn]
ret = {
'name': name,
'changes': {},
'result': None,
'comment': '',
}
if old == new:
ret['comment'] = 'LDAP entries already set'
ret['result'] = True
return ret
if __opts__['test']:
ret['comment'] = 'Would change LDAP entries'
changed_old = old
changed_new = new
success_dn_set = dn_set
else:
# execute the changes
changed_old = OrderedDict()
changed_new = OrderedDict()
# assume success; these will be changed on error
ret['result'] = True
ret['comment'] = 'Successfully updated LDAP entries'
errs = []
success_dn_set = OrderedDict()
for dn in dn_set:
o = old.get(dn, {})
n = new.get(dn, {})
try:
# perform the operation
if o:
if n:
op = 'modify'
assert o != n
__salt__['ldap3.change'](l, dn, o, n)
else:
op = 'delete'
__salt__['ldap3.delete'](l, dn)
else:
op = 'add'
assert n
__salt__['ldap3.add'](l, dn, n)
# update these after the op in case an exception
# is raised
changed_old[dn] = o
changed_new[dn] = n
success_dn_set[dn] = True
except ldap3.LDAPError as err:
log.exception('failed to %s entry %s (%s)', op, dn, err)
errs.append((op, dn, err))
continue
if errs:
ret['result'] = False
ret['comment'] = 'failed to ' \
+ ', '.join((op + ' entry ' + dn + '(' + six.text_type(err) + ')'
for op, dn, err in errs))
# set ret['changes']. filter out any unchanged attributes, and
# convert the value sets to lists before returning them to the
# user (sorted for easier comparisons)
for dn in success_dn_set:
o = changed_old.get(dn, {})
n = changed_new.get(dn, {})
changes = {}
ret['changes'][dn] = changes
for x, xn in ((o, 'old'), (n, 'new')):
if not x:
changes[xn] = None
continue
changes[xn] = dict(((attr, sorted(vals))
for attr, vals in six.iteritems(x)
if o.get(attr, ()) != n.get(attr, ())))
return ret | python | def managed(name, entries, connect_spec=None):
'''Ensure the existence (or not) of LDAP entries and their attributes
Example:
.. code-block:: yaml
ldapi:///:
ldap.managed:
- connect_spec:
bind:
method: sasl
- entries:
# make sure the entry doesn't exist
- cn=foo,ou=users,dc=example,dc=com:
- delete_others: True
# make sure the entry exists with only the specified
# attribute values
- cn=admin,dc=example,dc=com:
- delete_others: True
- replace:
cn:
- admin
description:
- LDAP administrator
objectClass:
- simpleSecurityObject
- organizationalRole
userPassword:
- {{pillar.ldap_admin_password}}
# make sure the entry exists, its olcRootDN attribute
# has only the specified value, the olcRootDN attribute
# doesn't exist, and all other attributes are ignored
- 'olcDatabase={1}hdb,cn=config':
- replace:
olcRootDN:
- cn=admin,dc=example,dc=com
# the admin entry has its own password attribute
olcRootPW: []
# note the use of 'default'. also note how you don't
# have to use list syntax if there is only one attribute
# value
- cn=foo,ou=users,dc=example,dc=com:
- delete_others: True
- default:
userPassword: changeme
shadowLastChange: 0
# keep sshPublicKey if present, but don't create
# the attribute if it is missing
sshPublicKey: []
- replace:
cn: foo
uid: foo
uidNumber: 1000
gidNumber: 1000
gecos: Foo Bar
givenName: Foo
sn: Bar
homeDirectory: /home/foo
loginShell: /bin/bash
objectClass:
- inetOrgPerson
- posixAccount
- top
- ldapPublicKey
- shadowAccount
:param name:
The URL of the LDAP server. This is ignored if
``connect_spec`` is either a connection object or a dict with
a ``'url'`` entry.
:param entries:
A description of the desired state of zero or more LDAP
entries.
``entries`` is an iterable of dicts. Each of these dict's
keys are the distinguished names (DNs) of LDAP entries to
manage. Each of these dicts is processed in order. A later
dict can reference an LDAP entry that was already mentioned in
an earlier dict, which makes it possible for later dicts to
enhance or alter the desired state of an LDAP entry.
The DNs are mapped to a description of the LDAP entry's
desired state. These LDAP entry descriptions are themselves
iterables of dicts. Each dict in the iterable is processed in
order. They contain directives controlling the entry's state.
The key names the directive type and the value is state
information for the directive. The specific structure of the
state information depends on the directive type.
The structure of ``entries`` looks like this::
[{dn1: [{directive1: directive1_state,
directive2: directive2_state},
{directive3: directive3_state}],
dn2: [{directive4: directive4_state,
directive5: directive5_state}]},
{dn3: [{directive6: directive6_state}]}]
These are the directives:
* ``'delete_others'``
Boolean indicating whether to delete attributes not
mentioned in this dict or any of the other directive
dicts for this DN. Defaults to ``False``.
If you don't want to delete an attribute if present, but
you also don't want to add it if it is missing or modify
it if it is present, you can use either the ``'default'``
directive or the ``'add'`` directive with an empty value
list.
* ``'default'``
A dict mapping an attribute name to an iterable of default
values for that attribute. If the attribute already
exists, it is left alone. If not, it is created using the
given list of values.
An empty value list is useful when you don't want to
create an attribute if it is missing but you do want to
preserve it if the ``'delete_others'`` key is ``True``.
* ``'add'``
Attribute values to add to the entry. This is a dict
mapping an attribute name to an iterable of values to add.
An empty value list is useful when you don't want to
create an attribute if it is missing but you do want to
preserve it if the ``'delete_others'`` key is ``True``.
* ``'delete'``
Attribute values to remove from the entry. This is a dict
mapping an attribute name to an iterable of values to
delete from the attribute. If the iterable is empty, all
of the attribute's values are deleted.
* ``'replace'``
Attributes to replace. This is a dict mapping an
attribute name to an iterable of values. Any existing
values for the attribute are deleted, then the given
values are added. The iterable may be empty.
In the above directives, the iterables of attribute values may
instead be ``None``, in which case an empty list is used, or a
scalar such as a string or number, in which case a new list
containing the scalar is used.
Note that if all attribute values are removed from an entry,
the entire entry is deleted.
:param connect_spec:
See the description of the ``connect_spec`` parameter of the
:py:func:`ldap3.connect <salt.modules.ldap3.connect>` function
in the :py:mod:`ldap3 <salt.modules.ldap3>` execution module.
If this is a dict and the ``'url'`` entry is not specified,
the ``'url'`` entry is set to the value of the ``name``
parameter.
:returns:
A dict with the following keys:
* ``'name'``
This is the same object passed to the ``name`` parameter.
* ``'changes'``
This is a dict describing the changes made (or, in test
mode, the changes that would have been attempted). If no
changes were made (or no changes would have been
attempted), then this dict is empty. Only successful
changes are included.
Each key is a DN of an entry that was changed (or would
have been changed). Entries that were not changed (or
would not have been changed) are not included. The value
is a dict with two keys:
* ``'old'``
The state of the entry before modification. If the
entry did not previously exist, this key maps to
``None``. Otherwise, the value is a dict mapping each
of the old entry's attributes to a list of its values
before any modifications were made. Unchanged
attributes are excluded from this dict.
* ``'new'``
The state of the entry after modification. If the
entry was deleted, this key maps to ``None``.
Otherwise, the value is a dict mapping each of the
entry's attributes to a list of its values after the
modifications were made. Unchanged attributes are
excluded from this dict.
Example ``'changes'`` dict where a new entry was created
with a single attribute containing two values::
{'dn1': {'old': None,
'new': {'attr1': ['val1', 'val2']}}}
Example ``'changes'`` dict where a new attribute was added
to an existing entry::
{'dn1': {'old': {},
'new': {'attr2': ['val3']}}}
* ``'result'``
One of the following values:
* ``True`` if no changes were necessary or if all changes
were applied successfully.
* ``False`` if at least one change was unable to be applied.
* ``None`` if changes would be applied but it is in test
mode.
'''
if connect_spec is None:
connect_spec = {}
try:
connect_spec.setdefault('url', name)
except AttributeError:
# already a connection object
pass
connect = __salt__['ldap3.connect']
# hack to get at the ldap3 module to access the ldap3.LDAPError
# exception class. https://github.com/saltstack/salt/issues/27578
ldap3 = inspect.getmodule(connect)
with connect(connect_spec) as l:
old, new = _process_entries(l, entries)
# collect all of the affected entries (only the key is
# important in this dict; would have used an OrderedSet if
# there was one)
dn_set = OrderedDict()
dn_set.update(old)
dn_set.update(new)
# do some cleanup
dn_to_delete = set()
for dn in dn_set:
o = old.get(dn, {})
n = new.get(dn, {})
for x in o, n:
to_delete = set()
for attr, vals in six.iteritems(x):
if not vals:
# clean out empty attribute lists
to_delete.add(attr)
for attr in to_delete:
del x[attr]
if o == n:
# clean out unchanged entries
dn_to_delete.add(dn)
for dn in dn_to_delete:
for x in old, new:
x.pop(dn, None)
del dn_set[dn]
ret = {
'name': name,
'changes': {},
'result': None,
'comment': '',
}
if old == new:
ret['comment'] = 'LDAP entries already set'
ret['result'] = True
return ret
if __opts__['test']:
ret['comment'] = 'Would change LDAP entries'
changed_old = old
changed_new = new
success_dn_set = dn_set
else:
# execute the changes
changed_old = OrderedDict()
changed_new = OrderedDict()
# assume success; these will be changed on error
ret['result'] = True
ret['comment'] = 'Successfully updated LDAP entries'
errs = []
success_dn_set = OrderedDict()
for dn in dn_set:
o = old.get(dn, {})
n = new.get(dn, {})
try:
# perform the operation
if o:
if n:
op = 'modify'
assert o != n
__salt__['ldap3.change'](l, dn, o, n)
else:
op = 'delete'
__salt__['ldap3.delete'](l, dn)
else:
op = 'add'
assert n
__salt__['ldap3.add'](l, dn, n)
# update these after the op in case an exception
# is raised
changed_old[dn] = o
changed_new[dn] = n
success_dn_set[dn] = True
except ldap3.LDAPError as err:
log.exception('failed to %s entry %s (%s)', op, dn, err)
errs.append((op, dn, err))
continue
if errs:
ret['result'] = False
ret['comment'] = 'failed to ' \
+ ', '.join((op + ' entry ' + dn + '(' + six.text_type(err) + ')'
for op, dn, err in errs))
# set ret['changes']. filter out any unchanged attributes, and
# convert the value sets to lists before returning them to the
# user (sorted for easier comparisons)
for dn in success_dn_set:
o = changed_old.get(dn, {})
n = changed_new.get(dn, {})
changes = {}
ret['changes'][dn] = changes
for x, xn in ((o, 'old'), (n, 'new')):
if not x:
changes[xn] = None
continue
changes[xn] = dict(((attr, sorted(vals))
for attr, vals in six.iteritems(x)
if o.get(attr, ()) != n.get(attr, ())))
return ret | [
"def",
"managed",
"(",
"name",
",",
"entries",
",",
"connect_spec",
"=",
"None",
")",
":",
"if",
"connect_spec",
"is",
"None",
":",
"connect_spec",
"=",
"{",
"}",
"try",
":",
"connect_spec",
".",
"setdefault",
"(",
"'url'",
",",
"name",
")",
"except",
... | Ensure the existence (or not) of LDAP entries and their attributes
Example:
.. code-block:: yaml
ldapi:///:
ldap.managed:
- connect_spec:
bind:
method: sasl
- entries:
# make sure the entry doesn't exist
- cn=foo,ou=users,dc=example,dc=com:
- delete_others: True
# make sure the entry exists with only the specified
# attribute values
- cn=admin,dc=example,dc=com:
- delete_others: True
- replace:
cn:
- admin
description:
- LDAP administrator
objectClass:
- simpleSecurityObject
- organizationalRole
userPassword:
- {{pillar.ldap_admin_password}}
# make sure the entry exists, its olcRootDN attribute
# has only the specified value, the olcRootDN attribute
# doesn't exist, and all other attributes are ignored
- 'olcDatabase={1}hdb,cn=config':
- replace:
olcRootDN:
- cn=admin,dc=example,dc=com
# the admin entry has its own password attribute
olcRootPW: []
# note the use of 'default'. also note how you don't
# have to use list syntax if there is only one attribute
# value
- cn=foo,ou=users,dc=example,dc=com:
- delete_others: True
- default:
userPassword: changeme
shadowLastChange: 0
# keep sshPublicKey if present, but don't create
# the attribute if it is missing
sshPublicKey: []
- replace:
cn: foo
uid: foo
uidNumber: 1000
gidNumber: 1000
gecos: Foo Bar
givenName: Foo
sn: Bar
homeDirectory: /home/foo
loginShell: /bin/bash
objectClass:
- inetOrgPerson
- posixAccount
- top
- ldapPublicKey
- shadowAccount
:param name:
The URL of the LDAP server. This is ignored if
``connect_spec`` is either a connection object or a dict with
a ``'url'`` entry.
:param entries:
A description of the desired state of zero or more LDAP
entries.
``entries`` is an iterable of dicts. Each of these dict's
keys are the distinguished names (DNs) of LDAP entries to
manage. Each of these dicts is processed in order. A later
dict can reference an LDAP entry that was already mentioned in
an earlier dict, which makes it possible for later dicts to
enhance or alter the desired state of an LDAP entry.
The DNs are mapped to a description of the LDAP entry's
desired state. These LDAP entry descriptions are themselves
iterables of dicts. Each dict in the iterable is processed in
order. They contain directives controlling the entry's state.
The key names the directive type and the value is state
information for the directive. The specific structure of the
state information depends on the directive type.
The structure of ``entries`` looks like this::
[{dn1: [{directive1: directive1_state,
directive2: directive2_state},
{directive3: directive3_state}],
dn2: [{directive4: directive4_state,
directive5: directive5_state}]},
{dn3: [{directive6: directive6_state}]}]
These are the directives:
* ``'delete_others'``
Boolean indicating whether to delete attributes not
mentioned in this dict or any of the other directive
dicts for this DN. Defaults to ``False``.
If you don't want to delete an attribute if present, but
you also don't want to add it if it is missing or modify
it if it is present, you can use either the ``'default'``
directive or the ``'add'`` directive with an empty value
list.
* ``'default'``
A dict mapping an attribute name to an iterable of default
values for that attribute. If the attribute already
exists, it is left alone. If not, it is created using the
given list of values.
An empty value list is useful when you don't want to
create an attribute if it is missing but you do want to
preserve it if the ``'delete_others'`` key is ``True``.
* ``'add'``
Attribute values to add to the entry. This is a dict
mapping an attribute name to an iterable of values to add.
An empty value list is useful when you don't want to
create an attribute if it is missing but you do want to
preserve it if the ``'delete_others'`` key is ``True``.
* ``'delete'``
Attribute values to remove from the entry. This is a dict
mapping an attribute name to an iterable of values to
delete from the attribute. If the iterable is empty, all
of the attribute's values are deleted.
* ``'replace'``
Attributes to replace. This is a dict mapping an
attribute name to an iterable of values. Any existing
values for the attribute are deleted, then the given
values are added. The iterable may be empty.
In the above directives, the iterables of attribute values may
instead be ``None``, in which case an empty list is used, or a
scalar such as a string or number, in which case a new list
containing the scalar is used.
Note that if all attribute values are removed from an entry,
the entire entry is deleted.
:param connect_spec:
See the description of the ``connect_spec`` parameter of the
:py:func:`ldap3.connect <salt.modules.ldap3.connect>` function
in the :py:mod:`ldap3 <salt.modules.ldap3>` execution module.
If this is a dict and the ``'url'`` entry is not specified,
the ``'url'`` entry is set to the value of the ``name``
parameter.
:returns:
A dict with the following keys:
* ``'name'``
This is the same object passed to the ``name`` parameter.
* ``'changes'``
This is a dict describing the changes made (or, in test
mode, the changes that would have been attempted). If no
changes were made (or no changes would have been
attempted), then this dict is empty. Only successful
changes are included.
Each key is a DN of an entry that was changed (or would
have been changed). Entries that were not changed (or
would not have been changed) are not included. The value
is a dict with two keys:
* ``'old'``
The state of the entry before modification. If the
entry did not previously exist, this key maps to
``None``. Otherwise, the value is a dict mapping each
of the old entry's attributes to a list of its values
before any modifications were made. Unchanged
attributes are excluded from this dict.
* ``'new'``
The state of the entry after modification. If the
entry was deleted, this key maps to ``None``.
Otherwise, the value is a dict mapping each of the
entry's attributes to a list of its values after the
modifications were made. Unchanged attributes are
excluded from this dict.
Example ``'changes'`` dict where a new entry was created
with a single attribute containing two values::
{'dn1': {'old': None,
'new': {'attr1': ['val1', 'val2']}}}
Example ``'changes'`` dict where a new attribute was added
to an existing entry::
{'dn1': {'old': {},
'new': {'attr2': ['val3']}}}
* ``'result'``
One of the following values:
* ``True`` if no changes were necessary or if all changes
were applied successfully.
* ``False`` if at least one change was unable to be applied.
* ``None`` if changes would be applied but it is in test
mode. | [
"Ensure",
"the",
"existence",
"(",
"or",
"not",
")",
"of",
"LDAP",
"entries",
"and",
"their",
"attributes"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/ldap.py#L26-L368 | train |
saltstack/salt | salt/states/ldap.py | _process_entries | def _process_entries(l, entries):
'''Helper for managed() to process entries and return before/after views
Collect the current database state and update it according to the
data in :py:func:`managed`'s ``entries`` parameter. Return the
current database state and what it will look like after
modification.
:param l:
the LDAP connection object
:param entries:
the same object passed to the ``entries`` parameter of
:py:func:`manage`
:return:
an ``(old, new)`` tuple that describes the current state of
the entries and what they will look like after modification.
Each item in the tuple is an OrderedDict that maps an entry DN
to another dict that maps an attribute name to a set of its
values (it's a set because according to the LDAP spec,
attribute value ordering is unspecified and there can't be
duplicates). The structure looks like this:
{dn1: {attr1: set([val1])},
dn2: {attr1: set([val2]), attr2: set([val3, val4])}}
All of an entry's attributes and values will be included, even
if they will not be modified. If an entry mentioned in the
entries variable doesn't yet exist in the database, the DN in
``old`` will be mapped to an empty dict. If an entry in the
database will be deleted, the DN in ``new`` will be mapped to
an empty dict. All value sets are non-empty: An attribute
that will be added to an entry is not included in ``old``, and
an attribute that will be deleted frm an entry is not included
in ``new``.
These are OrderedDicts to ensure that the user-supplied
entries are processed in the user-specified order (in case
there are dependencies, such as ACL rules specified in an
early entry that make it possible to modify a later entry).
'''
old = OrderedDict()
new = OrderedDict()
for entries_dict in entries:
for dn, directives_seq in six.iteritems(entries_dict):
# get the old entry's state. first check to see if we've
# previously processed the entry.
olde = new.get(dn, None)
if olde is None:
# next check the database
results = __salt__['ldap3.search'](l, dn, 'base')
if len(results) == 1:
attrs = results[dn]
olde = dict(((attr, OrderedSet(attrs[attr]))
for attr in attrs
if len(attrs[attr])))
else:
# nothing, so it must be a brand new entry
assert not results
olde = {}
old[dn] = olde
# copy the old entry to create the new (don't do a simple
# assignment or else modifications to newe will affect
# olde)
newe = copy.deepcopy(olde)
new[dn] = newe
# process the directives
entry_status = {
'delete_others': False,
'mentioned_attributes': set(),
}
for directives in directives_seq:
_update_entry(newe, entry_status, directives)
if entry_status['delete_others']:
to_delete = set()
for attr in newe:
if attr not in entry_status['mentioned_attributes']:
to_delete.add(attr)
for attr in to_delete:
del newe[attr]
return old, new | python | def _process_entries(l, entries):
'''Helper for managed() to process entries and return before/after views
Collect the current database state and update it according to the
data in :py:func:`managed`'s ``entries`` parameter. Return the
current database state and what it will look like after
modification.
:param l:
the LDAP connection object
:param entries:
the same object passed to the ``entries`` parameter of
:py:func:`manage`
:return:
an ``(old, new)`` tuple that describes the current state of
the entries and what they will look like after modification.
Each item in the tuple is an OrderedDict that maps an entry DN
to another dict that maps an attribute name to a set of its
values (it's a set because according to the LDAP spec,
attribute value ordering is unspecified and there can't be
duplicates). The structure looks like this:
{dn1: {attr1: set([val1])},
dn2: {attr1: set([val2]), attr2: set([val3, val4])}}
All of an entry's attributes and values will be included, even
if they will not be modified. If an entry mentioned in the
entries variable doesn't yet exist in the database, the DN in
``old`` will be mapped to an empty dict. If an entry in the
database will be deleted, the DN in ``new`` will be mapped to
an empty dict. All value sets are non-empty: An attribute
that will be added to an entry is not included in ``old``, and
an attribute that will be deleted frm an entry is not included
in ``new``.
These are OrderedDicts to ensure that the user-supplied
entries are processed in the user-specified order (in case
there are dependencies, such as ACL rules specified in an
early entry that make it possible to modify a later entry).
'''
old = OrderedDict()
new = OrderedDict()
for entries_dict in entries:
for dn, directives_seq in six.iteritems(entries_dict):
# get the old entry's state. first check to see if we've
# previously processed the entry.
olde = new.get(dn, None)
if olde is None:
# next check the database
results = __salt__['ldap3.search'](l, dn, 'base')
if len(results) == 1:
attrs = results[dn]
olde = dict(((attr, OrderedSet(attrs[attr]))
for attr in attrs
if len(attrs[attr])))
else:
# nothing, so it must be a brand new entry
assert not results
olde = {}
old[dn] = olde
# copy the old entry to create the new (don't do a simple
# assignment or else modifications to newe will affect
# olde)
newe = copy.deepcopy(olde)
new[dn] = newe
# process the directives
entry_status = {
'delete_others': False,
'mentioned_attributes': set(),
}
for directives in directives_seq:
_update_entry(newe, entry_status, directives)
if entry_status['delete_others']:
to_delete = set()
for attr in newe:
if attr not in entry_status['mentioned_attributes']:
to_delete.add(attr)
for attr in to_delete:
del newe[attr]
return old, new | [
"def",
"_process_entries",
"(",
"l",
",",
"entries",
")",
":",
"old",
"=",
"OrderedDict",
"(",
")",
"new",
"=",
"OrderedDict",
"(",
")",
"for",
"entries_dict",
"in",
"entries",
":",
"for",
"dn",
",",
"directives_seq",
"in",
"six",
".",
"iteritems",
"(",
... | Helper for managed() to process entries and return before/after views
Collect the current database state and update it according to the
data in :py:func:`managed`'s ``entries`` parameter. Return the
current database state and what it will look like after
modification.
:param l:
the LDAP connection object
:param entries:
the same object passed to the ``entries`` parameter of
:py:func:`manage`
:return:
an ``(old, new)`` tuple that describes the current state of
the entries and what they will look like after modification.
Each item in the tuple is an OrderedDict that maps an entry DN
to another dict that maps an attribute name to a set of its
values (it's a set because according to the LDAP spec,
attribute value ordering is unspecified and there can't be
duplicates). The structure looks like this:
{dn1: {attr1: set([val1])},
dn2: {attr1: set([val2]), attr2: set([val3, val4])}}
All of an entry's attributes and values will be included, even
if they will not be modified. If an entry mentioned in the
entries variable doesn't yet exist in the database, the DN in
``old`` will be mapped to an empty dict. If an entry in the
database will be deleted, the DN in ``new`` will be mapped to
an empty dict. All value sets are non-empty: An attribute
that will be added to an entry is not included in ``old``, and
an attribute that will be deleted frm an entry is not included
in ``new``.
These are OrderedDicts to ensure that the user-supplied
entries are processed in the user-specified order (in case
there are dependencies, such as ACL rules specified in an
early entry that make it possible to modify a later entry). | [
"Helper",
"for",
"managed",
"()",
"to",
"process",
"entries",
"and",
"return",
"before",
"/",
"after",
"views"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/ldap.py#L371-L455 | train |
saltstack/salt | salt/states/ldap.py | _update_entry | def _update_entry(entry, status, directives):
'''Update an entry's attributes using the provided directives
:param entry:
A dict mapping each attribute name to a set of its values
:param status:
A dict holding cross-invocation status (whether delete_others
is True or not, and the set of mentioned attributes)
:param directives:
A dict mapping directive types to directive-specific state
'''
for directive, state in six.iteritems(directives):
if directive == 'delete_others':
status['delete_others'] = state
continue
for attr, vals in six.iteritems(state):
status['mentioned_attributes'].add(attr)
vals = _toset(vals)
if directive == 'default':
if vals and (attr not in entry or not entry[attr]):
entry[attr] = vals
elif directive == 'add':
vals.update(entry.get(attr, ()))
if vals:
entry[attr] = vals
elif directive == 'delete':
existing_vals = entry.pop(attr, OrderedSet())
if vals:
existing_vals -= vals
if existing_vals:
entry[attr] = existing_vals
elif directive == 'replace':
entry.pop(attr, None)
if vals:
entry[attr] = vals
else:
raise ValueError('unknown directive: ' + directive) | python | def _update_entry(entry, status, directives):
'''Update an entry's attributes using the provided directives
:param entry:
A dict mapping each attribute name to a set of its values
:param status:
A dict holding cross-invocation status (whether delete_others
is True or not, and the set of mentioned attributes)
:param directives:
A dict mapping directive types to directive-specific state
'''
for directive, state in six.iteritems(directives):
if directive == 'delete_others':
status['delete_others'] = state
continue
for attr, vals in six.iteritems(state):
status['mentioned_attributes'].add(attr)
vals = _toset(vals)
if directive == 'default':
if vals and (attr not in entry or not entry[attr]):
entry[attr] = vals
elif directive == 'add':
vals.update(entry.get(attr, ()))
if vals:
entry[attr] = vals
elif directive == 'delete':
existing_vals = entry.pop(attr, OrderedSet())
if vals:
existing_vals -= vals
if existing_vals:
entry[attr] = existing_vals
elif directive == 'replace':
entry.pop(attr, None)
if vals:
entry[attr] = vals
else:
raise ValueError('unknown directive: ' + directive) | [
"def",
"_update_entry",
"(",
"entry",
",",
"status",
",",
"directives",
")",
":",
"for",
"directive",
",",
"state",
"in",
"six",
".",
"iteritems",
"(",
"directives",
")",
":",
"if",
"directive",
"==",
"'delete_others'",
":",
"status",
"[",
"'delete_others'",... | Update an entry's attributes using the provided directives
:param entry:
A dict mapping each attribute name to a set of its values
:param status:
A dict holding cross-invocation status (whether delete_others
is True or not, and the set of mentioned attributes)
:param directives:
A dict mapping directive types to directive-specific state | [
"Update",
"an",
"entry",
"s",
"attributes",
"using",
"the",
"provided",
"directives"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/ldap.py#L458-L494 | train |
saltstack/salt | salt/states/ldap.py | _toset | def _toset(thing):
'''helper to convert various things to a set
This enables flexibility in what users provide as the list of LDAP
entry attribute values. Note that the LDAP spec prohibits
duplicate values in an attribute.
RFC 2251 states that:
"The order of attribute values within the vals set is undefined and
implementation-dependent, and MUST NOT be relied upon."
However, OpenLDAP have an X-ORDERED that is used in the config schema.
Using sets would mean we can't pass ordered values and therefore can't
manage parts of the OpenLDAP configuration, hence the use of OrderedSet.
Sets are also good for automatically removing duplicates.
None becomes an empty set. Iterables except for strings have
their elements added to a new set. Non-None scalars (strings,
numbers, non-iterable objects, etc.) are added as the only member
of a new set.
'''
if thing is None:
return OrderedSet()
if isinstance(thing, six.string_types):
return OrderedSet((thing,))
# convert numbers to strings so that equality checks work
# (LDAP stores numbers as strings)
try:
return OrderedSet((six.text_type(x) for x in thing))
except TypeError:
return OrderedSet((six.text_type(thing),)) | python | def _toset(thing):
'''helper to convert various things to a set
This enables flexibility in what users provide as the list of LDAP
entry attribute values. Note that the LDAP spec prohibits
duplicate values in an attribute.
RFC 2251 states that:
"The order of attribute values within the vals set is undefined and
implementation-dependent, and MUST NOT be relied upon."
However, OpenLDAP have an X-ORDERED that is used in the config schema.
Using sets would mean we can't pass ordered values and therefore can't
manage parts of the OpenLDAP configuration, hence the use of OrderedSet.
Sets are also good for automatically removing duplicates.
None becomes an empty set. Iterables except for strings have
their elements added to a new set. Non-None scalars (strings,
numbers, non-iterable objects, etc.) are added as the only member
of a new set.
'''
if thing is None:
return OrderedSet()
if isinstance(thing, six.string_types):
return OrderedSet((thing,))
# convert numbers to strings so that equality checks work
# (LDAP stores numbers as strings)
try:
return OrderedSet((six.text_type(x) for x in thing))
except TypeError:
return OrderedSet((six.text_type(thing),)) | [
"def",
"_toset",
"(",
"thing",
")",
":",
"if",
"thing",
"is",
"None",
":",
"return",
"OrderedSet",
"(",
")",
"if",
"isinstance",
"(",
"thing",
",",
"six",
".",
"string_types",
")",
":",
"return",
"OrderedSet",
"(",
"(",
"thing",
",",
")",
")",
"# con... | helper to convert various things to a set
This enables flexibility in what users provide as the list of LDAP
entry attribute values. Note that the LDAP spec prohibits
duplicate values in an attribute.
RFC 2251 states that:
"The order of attribute values within the vals set is undefined and
implementation-dependent, and MUST NOT be relied upon."
However, OpenLDAP have an X-ORDERED that is used in the config schema.
Using sets would mean we can't pass ordered values and therefore can't
manage parts of the OpenLDAP configuration, hence the use of OrderedSet.
Sets are also good for automatically removing duplicates.
None becomes an empty set. Iterables except for strings have
their elements added to a new set. Non-None scalars (strings,
numbers, non-iterable objects, etc.) are added as the only member
of a new set. | [
"helper",
"to",
"convert",
"various",
"things",
"to",
"a",
"set"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/ldap.py#L497-L528 | train |
saltstack/salt | salt/modules/shadow.py | info | def info(name, root=None):
'''
Return information for the specified user
name
User to get the information for
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' shadow.info root
'''
if root is not None:
getspnam = functools.partial(_getspnam, root=root)
else:
getspnam = functools.partial(spwd.getspnam)
try:
data = getspnam(name)
ret = {
'name': data.sp_namp if hasattr(data, 'sp_namp') else data.sp_nam,
'passwd': data.sp_pwdp if hasattr(data, 'sp_pwdp') else data.sp_pwd,
'lstchg': data.sp_lstchg,
'min': data.sp_min,
'max': data.sp_max,
'warn': data.sp_warn,
'inact': data.sp_inact,
'expire': data.sp_expire}
except KeyError:
return {
'name': '',
'passwd': '',
'lstchg': '',
'min': '',
'max': '',
'warn': '',
'inact': '',
'expire': ''}
return ret | python | def info(name, root=None):
'''
Return information for the specified user
name
User to get the information for
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' shadow.info root
'''
if root is not None:
getspnam = functools.partial(_getspnam, root=root)
else:
getspnam = functools.partial(spwd.getspnam)
try:
data = getspnam(name)
ret = {
'name': data.sp_namp if hasattr(data, 'sp_namp') else data.sp_nam,
'passwd': data.sp_pwdp if hasattr(data, 'sp_pwdp') else data.sp_pwd,
'lstchg': data.sp_lstchg,
'min': data.sp_min,
'max': data.sp_max,
'warn': data.sp_warn,
'inact': data.sp_inact,
'expire': data.sp_expire}
except KeyError:
return {
'name': '',
'passwd': '',
'lstchg': '',
'min': '',
'max': '',
'warn': '',
'inact': '',
'expire': ''}
return ret | [
"def",
"info",
"(",
"name",
",",
"root",
"=",
"None",
")",
":",
"if",
"root",
"is",
"not",
"None",
":",
"getspnam",
"=",
"functools",
".",
"partial",
"(",
"_getspnam",
",",
"root",
"=",
"root",
")",
"else",
":",
"getspnam",
"=",
"functools",
".",
"... | Return information for the specified user
name
User to get the information for
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' shadow.info root | [
"Return",
"information",
"for",
"the",
"specified",
"user"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/shadow.py#L53-L95 | train |
saltstack/salt | salt/modules/shadow.py | _set_attrib | def _set_attrib(name, key, value, param, root=None, validate=True):
'''
Set a parameter in /etc/shadow
'''
pre_info = info(name, root=root)
# If the user is not present or the attribute is already present,
# we return early
if not pre_info['name']:
return False
if value == pre_info[key]:
return True
cmd = ['chage']
if root is not None:
cmd.extend(('-R', root))
cmd.extend((param, value, name))
ret = not __salt__['cmd.run'](cmd, python_shell=False)
if validate:
ret = info(name, root=root).get(key) == value
return ret | python | def _set_attrib(name, key, value, param, root=None, validate=True):
'''
Set a parameter in /etc/shadow
'''
pre_info = info(name, root=root)
# If the user is not present or the attribute is already present,
# we return early
if not pre_info['name']:
return False
if value == pre_info[key]:
return True
cmd = ['chage']
if root is not None:
cmd.extend(('-R', root))
cmd.extend((param, value, name))
ret = not __salt__['cmd.run'](cmd, python_shell=False)
if validate:
ret = info(name, root=root).get(key) == value
return ret | [
"def",
"_set_attrib",
"(",
"name",
",",
"key",
",",
"value",
",",
"param",
",",
"root",
"=",
"None",
",",
"validate",
"=",
"True",
")",
":",
"pre_info",
"=",
"info",
"(",
"name",
",",
"root",
"=",
"root",
")",
"# If the user is not present or the attribute... | Set a parameter in /etc/shadow | [
"Set",
"a",
"parameter",
"in",
"/",
"etc",
"/",
"shadow"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/shadow.py#L98-L122 | train |
saltstack/salt | salt/modules/shadow.py | gen_password | def gen_password(password, crypt_salt=None, algorithm='sha512'):
'''
.. versionadded:: 2014.7.0
Generate hashed password
.. note::
When called this function is called directly via remote-execution,
the password argument may be displayed in the system's process list.
This may be a security risk on certain systems.
password
Plaintext password to be hashed.
crypt_salt
Crpytographic salt. If not given, a random 8-character salt will be
generated.
algorithm
The following hash algorithms are supported:
* md5
* blowfish (not in mainline glibc, only available in distros that add it)
* sha256
* sha512 (default)
CLI Example:
.. code-block:: bash
salt '*' shadow.gen_password 'I_am_password'
salt '*' shadow.gen_password 'I_am_password' crypt_salt='I_am_salt' algorithm=sha256
'''
if not HAS_CRYPT:
raise CommandExecutionError(
'gen_password is not available on this operating system '
'because the "crypt" python module is not available.'
)
return salt.utils.pycrypto.gen_hash(crypt_salt, password, algorithm) | python | def gen_password(password, crypt_salt=None, algorithm='sha512'):
'''
.. versionadded:: 2014.7.0
Generate hashed password
.. note::
When called this function is called directly via remote-execution,
the password argument may be displayed in the system's process list.
This may be a security risk on certain systems.
password
Plaintext password to be hashed.
crypt_salt
Crpytographic salt. If not given, a random 8-character salt will be
generated.
algorithm
The following hash algorithms are supported:
* md5
* blowfish (not in mainline glibc, only available in distros that add it)
* sha256
* sha512 (default)
CLI Example:
.. code-block:: bash
salt '*' shadow.gen_password 'I_am_password'
salt '*' shadow.gen_password 'I_am_password' crypt_salt='I_am_salt' algorithm=sha256
'''
if not HAS_CRYPT:
raise CommandExecutionError(
'gen_password is not available on this operating system '
'because the "crypt" python module is not available.'
)
return salt.utils.pycrypto.gen_hash(crypt_salt, password, algorithm) | [
"def",
"gen_password",
"(",
"password",
",",
"crypt_salt",
"=",
"None",
",",
"algorithm",
"=",
"'sha512'",
")",
":",
"if",
"not",
"HAS_CRYPT",
":",
"raise",
"CommandExecutionError",
"(",
"'gen_password is not available on this operating system '",
"'because the \"crypt\" ... | .. versionadded:: 2014.7.0
Generate hashed password
.. note::
When called this function is called directly via remote-execution,
the password argument may be displayed in the system's process list.
This may be a security risk on certain systems.
password
Plaintext password to be hashed.
crypt_salt
Crpytographic salt. If not given, a random 8-character salt will be
generated.
algorithm
The following hash algorithms are supported:
* md5
* blowfish (not in mainline glibc, only available in distros that add it)
* sha256
* sha512 (default)
CLI Example:
.. code-block:: bash
salt '*' shadow.gen_password 'I_am_password'
salt '*' shadow.gen_password 'I_am_password' crypt_salt='I_am_salt' algorithm=sha256 | [
"..",
"versionadded",
"::",
"2014",
".",
"7",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/shadow.py#L193-L232 | train |
saltstack/salt | salt/modules/shadow.py | del_password | def del_password(name, root=None):
'''
.. versionadded:: 2014.7.0
Delete the password from name user
name
User to delete
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' shadow.del_password username
'''
cmd = ['passwd']
if root is not None:
cmd.extend(('-R', root))
cmd.extend(('-d', name))
__salt__['cmd.run'](cmd, python_shell=False, output_loglevel='quiet')
uinfo = info(name, root=root)
return not uinfo['passwd'] and uinfo['name'] == name | python | def del_password(name, root=None):
'''
.. versionadded:: 2014.7.0
Delete the password from name user
name
User to delete
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' shadow.del_password username
'''
cmd = ['passwd']
if root is not None:
cmd.extend(('-R', root))
cmd.extend(('-d', name))
__salt__['cmd.run'](cmd, python_shell=False, output_loglevel='quiet')
uinfo = info(name, root=root)
return not uinfo['passwd'] and uinfo['name'] == name | [
"def",
"del_password",
"(",
"name",
",",
"root",
"=",
"None",
")",
":",
"cmd",
"=",
"[",
"'passwd'",
"]",
"if",
"root",
"is",
"not",
"None",
":",
"cmd",
".",
"extend",
"(",
"(",
"'-R'",
",",
"root",
")",
")",
"cmd",
".",
"extend",
"(",
"(",
"'-... | .. versionadded:: 2014.7.0
Delete the password from name user
name
User to delete
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' shadow.del_password username | [
"..",
"versionadded",
"::",
"2014",
".",
"7",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/shadow.py#L235-L260 | train |
saltstack/salt | salt/modules/shadow.py | unlock_password | def unlock_password(name, root=None):
'''
.. versionadded:: 2016.11.0
Unlock the password from name user
name
User to unlock
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' shadow.unlock_password username
'''
pre_info = info(name, root=root)
if not pre_info['name']:
return False
if not pre_info['passwd'].startswith('!'):
return True
cmd = ['passwd']
if root is not None:
cmd.extend(('-R', root))
cmd.extend(('-u', name))
__salt__['cmd.run'](cmd, python_shell=False)
return not info(name, root=root)['passwd'].startswith('!') | python | def unlock_password(name, root=None):
'''
.. versionadded:: 2016.11.0
Unlock the password from name user
name
User to unlock
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' shadow.unlock_password username
'''
pre_info = info(name, root=root)
if not pre_info['name']:
return False
if not pre_info['passwd'].startswith('!'):
return True
cmd = ['passwd']
if root is not None:
cmd.extend(('-R', root))
cmd.extend(('-u', name))
__salt__['cmd.run'](cmd, python_shell=False)
return not info(name, root=root)['passwd'].startswith('!') | [
"def",
"unlock_password",
"(",
"name",
",",
"root",
"=",
"None",
")",
":",
"pre_info",
"=",
"info",
"(",
"name",
",",
"root",
"=",
"root",
")",
"if",
"not",
"pre_info",
"[",
"'name'",
"]",
":",
"return",
"False",
"if",
"not",
"pre_info",
"[",
"'passw... | .. versionadded:: 2016.11.0
Unlock the password from name user
name
User to unlock
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' shadow.unlock_password username | [
"..",
"versionadded",
"::",
"2016",
".",
"11",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/shadow.py#L299-L332 | train |
saltstack/salt | salt/modules/shadow.py | set_password | def set_password(name, password, use_usermod=False, root=None):
'''
Set the password for a named user. The password must be a properly defined
hash. The password hash can be generated with this command:
``python -c "import crypt; print crypt.crypt('password',
'\\$6\\$SALTsalt')"``
``SALTsalt`` is the 8-character crpytographic salt. Valid characters in the
salt are ``.``, ``/``, and any alphanumeric character.
Keep in mind that the $6 represents a sha512 hash, if your OS is using a
different hashing algorithm this needs to be changed accordingly
name
User to set the password
password
Password already hashed
use_usermod
Use usermod command to better compatibility
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' shadow.set_password root '$1$UYCIxa628.9qXjpQCjM4a..'
'''
if not salt.utils.data.is_true(use_usermod):
# Edit the shadow file directly
# ALT Linux uses tcb to store password hashes. More information found
# in manpage (http://docs.altlinux.org/manpages/tcb.5.html)
if __grains__['os'] == 'ALT':
s_file = '/etc/tcb/{0}/shadow'.format(name)
else:
s_file = '/etc/shadow'
if root:
s_file = os.path.join(root, os.path.relpath(s_file, os.path.sep))
ret = {}
if not os.path.isfile(s_file):
return ret
lines = []
with salt.utils.files.fopen(s_file, 'rb') as fp_:
for line in fp_:
line = salt.utils.stringutils.to_unicode(line)
comps = line.strip().split(':')
if comps[0] != name:
lines.append(line)
continue
changed_date = datetime.datetime.today() - datetime.datetime(1970, 1, 1)
comps[1] = password
comps[2] = six.text_type(changed_date.days)
line = ':'.join(comps)
lines.append('{0}\n'.format(line))
with salt.utils.files.fopen(s_file, 'w+') as fp_:
lines = [salt.utils.stringutils.to_str(_l) for _l in lines]
fp_.writelines(lines)
uinfo = info(name, root=root)
return uinfo['passwd'] == password
else:
# Use usermod -p (less secure, but more feature-complete)
cmd = ['usermod']
if root is not None:
cmd.extend(('-R', root))
cmd.extend(('-p', password, name))
__salt__['cmd.run'](cmd, python_shell=False, output_loglevel='quiet')
uinfo = info(name, root=root)
return uinfo['passwd'] == password | python | def set_password(name, password, use_usermod=False, root=None):
'''
Set the password for a named user. The password must be a properly defined
hash. The password hash can be generated with this command:
``python -c "import crypt; print crypt.crypt('password',
'\\$6\\$SALTsalt')"``
``SALTsalt`` is the 8-character crpytographic salt. Valid characters in the
salt are ``.``, ``/``, and any alphanumeric character.
Keep in mind that the $6 represents a sha512 hash, if your OS is using a
different hashing algorithm this needs to be changed accordingly
name
User to set the password
password
Password already hashed
use_usermod
Use usermod command to better compatibility
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' shadow.set_password root '$1$UYCIxa628.9qXjpQCjM4a..'
'''
if not salt.utils.data.is_true(use_usermod):
# Edit the shadow file directly
# ALT Linux uses tcb to store password hashes. More information found
# in manpage (http://docs.altlinux.org/manpages/tcb.5.html)
if __grains__['os'] == 'ALT':
s_file = '/etc/tcb/{0}/shadow'.format(name)
else:
s_file = '/etc/shadow'
if root:
s_file = os.path.join(root, os.path.relpath(s_file, os.path.sep))
ret = {}
if not os.path.isfile(s_file):
return ret
lines = []
with salt.utils.files.fopen(s_file, 'rb') as fp_:
for line in fp_:
line = salt.utils.stringutils.to_unicode(line)
comps = line.strip().split(':')
if comps[0] != name:
lines.append(line)
continue
changed_date = datetime.datetime.today() - datetime.datetime(1970, 1, 1)
comps[1] = password
comps[2] = six.text_type(changed_date.days)
line = ':'.join(comps)
lines.append('{0}\n'.format(line))
with salt.utils.files.fopen(s_file, 'w+') as fp_:
lines = [salt.utils.stringutils.to_str(_l) for _l in lines]
fp_.writelines(lines)
uinfo = info(name, root=root)
return uinfo['passwd'] == password
else:
# Use usermod -p (less secure, but more feature-complete)
cmd = ['usermod']
if root is not None:
cmd.extend(('-R', root))
cmd.extend(('-p', password, name))
__salt__['cmd.run'](cmd, python_shell=False, output_loglevel='quiet')
uinfo = info(name, root=root)
return uinfo['passwd'] == password | [
"def",
"set_password",
"(",
"name",
",",
"password",
",",
"use_usermod",
"=",
"False",
",",
"root",
"=",
"None",
")",
":",
"if",
"not",
"salt",
".",
"utils",
".",
"data",
".",
"is_true",
"(",
"use_usermod",
")",
":",
"# Edit the shadow file directly",
"# A... | Set the password for a named user. The password must be a properly defined
hash. The password hash can be generated with this command:
``python -c "import crypt; print crypt.crypt('password',
'\\$6\\$SALTsalt')"``
``SALTsalt`` is the 8-character crpytographic salt. Valid characters in the
salt are ``.``, ``/``, and any alphanumeric character.
Keep in mind that the $6 represents a sha512 hash, if your OS is using a
different hashing algorithm this needs to be changed accordingly
name
User to set the password
password
Password already hashed
use_usermod
Use usermod command to better compatibility
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' shadow.set_password root '$1$UYCIxa628.9qXjpQCjM4a..' | [
"Set",
"the",
"password",
"for",
"a",
"named",
"user",
".",
"The",
"password",
"must",
"be",
"a",
"properly",
"defined",
"hash",
".",
"The",
"password",
"hash",
"can",
"be",
"generated",
"with",
"this",
"command",
":"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/shadow.py#L335-L408 | train |
saltstack/salt | salt/modules/shadow.py | set_date | def set_date(name, date, root=None):
'''
Sets the value for the date the password was last changed to days since the
epoch (January 1, 1970). See man chage.
name
User to modify
date
Date the password was last changed
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' shadow.set_date username 0
'''
return _set_attrib(name, 'lstchg', date, '-d', root=root, validate=False) | python | def set_date(name, date, root=None):
'''
Sets the value for the date the password was last changed to days since the
epoch (January 1, 1970). See man chage.
name
User to modify
date
Date the password was last changed
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' shadow.set_date username 0
'''
return _set_attrib(name, 'lstchg', date, '-d', root=root, validate=False) | [
"def",
"set_date",
"(",
"name",
",",
"date",
",",
"root",
"=",
"None",
")",
":",
"return",
"_set_attrib",
"(",
"name",
",",
"'lstchg'",
",",
"date",
",",
"'-d'",
",",
"root",
"=",
"root",
",",
"validate",
"=",
"False",
")"
] | Sets the value for the date the password was last changed to days since the
epoch (January 1, 1970). See man chage.
name
User to modify
date
Date the password was last changed
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' shadow.set_date username 0 | [
"Sets",
"the",
"value",
"for",
"the",
"date",
"the",
"password",
"was",
"last",
"changed",
"to",
"days",
"since",
"the",
"epoch",
"(",
"January",
"1",
"1970",
")",
".",
"See",
"man",
"chage",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/shadow.py#L434-L454 | train |
saltstack/salt | salt/modules/shadow.py | set_expire | def set_expire(name, expire, root=None):
'''
.. versionchanged:: 2014.7.0
Sets the value for the date the account expires as days since the epoch
(January 1, 1970). Using a value of -1 will clear expiration. See man
chage.
name
User to modify
date
Date the account expires
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' shadow.set_expire username -1
'''
return _set_attrib(name, 'expire', expire, '-E', root=root, validate=False) | python | def set_expire(name, expire, root=None):
'''
.. versionchanged:: 2014.7.0
Sets the value for the date the account expires as days since the epoch
(January 1, 1970). Using a value of -1 will clear expiration. See man
chage.
name
User to modify
date
Date the account expires
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' shadow.set_expire username -1
'''
return _set_attrib(name, 'expire', expire, '-E', root=root, validate=False) | [
"def",
"set_expire",
"(",
"name",
",",
"expire",
",",
"root",
"=",
"None",
")",
":",
"return",
"_set_attrib",
"(",
"name",
",",
"'expire'",
",",
"expire",
",",
"'-E'",
",",
"root",
"=",
"root",
",",
"validate",
"=",
"False",
")"
] | .. versionchanged:: 2014.7.0
Sets the value for the date the account expires as days since the epoch
(January 1, 1970). Using a value of -1 will clear expiration. See man
chage.
name
User to modify
date
Date the account expires
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' shadow.set_expire username -1 | [
"..",
"versionchanged",
"::",
"2014",
".",
"7",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/shadow.py#L457-L480 | train |
saltstack/salt | salt/modules/shadow.py | list_users | def list_users(root=None):
'''
.. versionadded:: 2018.3.0
Return a list of all shadow users
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' shadow.list_users
'''
if root is not None:
getspall = functools.partial(_getspall, root=root)
else:
getspall = functools.partial(spwd.getspall)
return sorted([user.sp_namp if hasattr(user, 'sp_namp') else user.sp_nam
for user in getspall()]) | python | def list_users(root=None):
'''
.. versionadded:: 2018.3.0
Return a list of all shadow users
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' shadow.list_users
'''
if root is not None:
getspall = functools.partial(_getspall, root=root)
else:
getspall = functools.partial(spwd.getspall)
return sorted([user.sp_namp if hasattr(user, 'sp_namp') else user.sp_nam
for user in getspall()]) | [
"def",
"list_users",
"(",
"root",
"=",
"None",
")",
":",
"if",
"root",
"is",
"not",
"None",
":",
"getspall",
"=",
"functools",
".",
"partial",
"(",
"_getspall",
",",
"root",
"=",
"root",
")",
"else",
":",
"getspall",
"=",
"functools",
".",
"partial",
... | .. versionadded:: 2018.3.0
Return a list of all shadow users
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' shadow.list_users | [
"..",
"versionadded",
"::",
"2018",
".",
"3",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/shadow.py#L483-L504 | train |
saltstack/salt | salt/modules/shadow.py | _getspnam | def _getspnam(name, root=None):
'''
Alternative implementation for getspnam, that use only /etc/shadow
'''
root = '/' if not root else root
passwd = os.path.join(root, 'etc/shadow')
with salt.utils.files.fopen(passwd) as fp_:
for line in fp_:
line = salt.utils.stringutils.to_unicode(line)
comps = line.strip().split(':')
if comps[0] == name:
# Generate a getspnam compatible output
for i in range(2, 9):
comps[i] = int(comps[i]) if comps[i] else -1
return spwd.struct_spwd(comps)
raise KeyError | python | def _getspnam(name, root=None):
'''
Alternative implementation for getspnam, that use only /etc/shadow
'''
root = '/' if not root else root
passwd = os.path.join(root, 'etc/shadow')
with salt.utils.files.fopen(passwd) as fp_:
for line in fp_:
line = salt.utils.stringutils.to_unicode(line)
comps = line.strip().split(':')
if comps[0] == name:
# Generate a getspnam compatible output
for i in range(2, 9):
comps[i] = int(comps[i]) if comps[i] else -1
return spwd.struct_spwd(comps)
raise KeyError | [
"def",
"_getspnam",
"(",
"name",
",",
"root",
"=",
"None",
")",
":",
"root",
"=",
"'/'",
"if",
"not",
"root",
"else",
"root",
"passwd",
"=",
"os",
".",
"path",
".",
"join",
"(",
"root",
",",
"'etc/shadow'",
")",
"with",
"salt",
".",
"utils",
".",
... | Alternative implementation for getspnam, that use only /etc/shadow | [
"Alternative",
"implementation",
"for",
"getspnam",
"that",
"use",
"only",
"/",
"etc",
"/",
"shadow"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/shadow.py#L507-L522 | train |
saltstack/salt | salt/modules/boto_route53.py | _get_split_zone | def _get_split_zone(zone, _conn, private_zone):
'''
With boto route53, zones can only be matched by name
or iterated over in a list. Since the name will be the
same for public and private zones in a split DNS situation,
iterate over the list and match the zone name and public/private
status.
'''
for _zone in _conn.get_zones():
if _zone.name == zone:
_private_zone = True if _zone.config['PrivateZone'].lower() == 'true' else False
if _private_zone == private_zone:
return _zone
return False | python | def _get_split_zone(zone, _conn, private_zone):
'''
With boto route53, zones can only be matched by name
or iterated over in a list. Since the name will be the
same for public and private zones in a split DNS situation,
iterate over the list and match the zone name and public/private
status.
'''
for _zone in _conn.get_zones():
if _zone.name == zone:
_private_zone = True if _zone.config['PrivateZone'].lower() == 'true' else False
if _private_zone == private_zone:
return _zone
return False | [
"def",
"_get_split_zone",
"(",
"zone",
",",
"_conn",
",",
"private_zone",
")",
":",
"for",
"_zone",
"in",
"_conn",
".",
"get_zones",
"(",
")",
":",
"if",
"_zone",
".",
"name",
"==",
"zone",
":",
"_private_zone",
"=",
"True",
"if",
"_zone",
".",
"config... | With boto route53, zones can only be matched by name
or iterated over in a list. Since the name will be the
same for public and private zones in a split DNS situation,
iterate over the list and match the zone name and public/private
status. | [
"With",
"boto",
"route53",
"zones",
"can",
"only",
"be",
"matched",
"by",
"name",
"or",
"iterated",
"over",
"in",
"a",
"list",
".",
"Since",
"the",
"name",
"will",
"be",
"the",
"same",
"for",
"public",
"and",
"private",
"zones",
"in",
"a",
"split",
"DN... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_route53.py#L94-L107 | train |
saltstack/salt | salt/modules/boto_route53.py | describe_hosted_zones | def describe_hosted_zones(zone_id=None, domain_name=None, region=None,
key=None, keyid=None, profile=None):
'''
Return detailed info about one, or all, zones in the bound account.
If neither zone_id nor domain_name is provided, return all zones.
Note that the return format is slightly different between the 'all'
and 'single' description types.
zone_id
The unique identifier for the Hosted Zone
domain_name
The FQDN of the Hosted Zone (including final period)
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
CLI Example:
.. code-block:: bash
salt myminion boto_route53.describe_hosted_zones domain_name=foo.bar.com. \
profile='{"region": "us-east-1", "keyid": "A12345678AB", "key": "xblahblahblah"}'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if zone_id and domain_name:
raise SaltInvocationError('At most one of zone_id or domain_name may '
'be provided')
retries = 10
while retries:
try:
if zone_id:
zone_id = zone_id.replace('/hostedzone/',
'') if zone_id.startswith('/hostedzone/') else zone_id
ret = getattr(conn.get_hosted_zone(zone_id),
'GetHostedZoneResponse', None)
elif domain_name:
ret = getattr(conn.get_hosted_zone_by_name(domain_name),
'GetHostedZoneResponse', None)
else:
marker = None
ret = None
while marker is not '':
r = conn.get_all_hosted_zones(start_marker=marker,
zone_list=ret)
ret = r['ListHostedZonesResponse']['HostedZones']
marker = r['ListHostedZonesResponse'].get('NextMarker', '')
return ret if ret else []
except DNSServerError as e:
if retries:
if 'Throttling' == e.code:
log.debug('Throttled by AWS API.')
elif 'PriorRequestNotComplete' == e.code:
log.debug('The request was rejected by AWS API.\
Route 53 was still processing a prior request')
time.sleep(3)
retries -= 1
continue
log.error('Could not list zones: %s', e.message)
return [] | python | def describe_hosted_zones(zone_id=None, domain_name=None, region=None,
key=None, keyid=None, profile=None):
'''
Return detailed info about one, or all, zones in the bound account.
If neither zone_id nor domain_name is provided, return all zones.
Note that the return format is slightly different between the 'all'
and 'single' description types.
zone_id
The unique identifier for the Hosted Zone
domain_name
The FQDN of the Hosted Zone (including final period)
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
CLI Example:
.. code-block:: bash
salt myminion boto_route53.describe_hosted_zones domain_name=foo.bar.com. \
profile='{"region": "us-east-1", "keyid": "A12345678AB", "key": "xblahblahblah"}'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if zone_id and domain_name:
raise SaltInvocationError('At most one of zone_id or domain_name may '
'be provided')
retries = 10
while retries:
try:
if zone_id:
zone_id = zone_id.replace('/hostedzone/',
'') if zone_id.startswith('/hostedzone/') else zone_id
ret = getattr(conn.get_hosted_zone(zone_id),
'GetHostedZoneResponse', None)
elif domain_name:
ret = getattr(conn.get_hosted_zone_by_name(domain_name),
'GetHostedZoneResponse', None)
else:
marker = None
ret = None
while marker is not '':
r = conn.get_all_hosted_zones(start_marker=marker,
zone_list=ret)
ret = r['ListHostedZonesResponse']['HostedZones']
marker = r['ListHostedZonesResponse'].get('NextMarker', '')
return ret if ret else []
except DNSServerError as e:
if retries:
if 'Throttling' == e.code:
log.debug('Throttled by AWS API.')
elif 'PriorRequestNotComplete' == e.code:
log.debug('The request was rejected by AWS API.\
Route 53 was still processing a prior request')
time.sleep(3)
retries -= 1
continue
log.error('Could not list zones: %s', e.message)
return [] | [
"def",
"describe_hosted_zones",
"(",
"zone_id",
"=",
"None",
",",
"domain_name",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"conn",
"=",
"_get_conn",
"(",
"region"... | Return detailed info about one, or all, zones in the bound account.
If neither zone_id nor domain_name is provided, return all zones.
Note that the return format is slightly different between the 'all'
and 'single' description types.
zone_id
The unique identifier for the Hosted Zone
domain_name
The FQDN of the Hosted Zone (including final period)
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
CLI Example:
.. code-block:: bash
salt myminion boto_route53.describe_hosted_zones domain_name=foo.bar.com. \
profile='{"region": "us-east-1", "keyid": "A12345678AB", "key": "xblahblahblah"}' | [
"Return",
"detailed",
"info",
"about",
"one",
"or",
"all",
"zones",
"in",
"the",
"bound",
"account",
".",
"If",
"neither",
"zone_id",
"nor",
"domain_name",
"is",
"provided",
"return",
"all",
"zones",
".",
"Note",
"that",
"the",
"return",
"format",
"is",
"s... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_route53.py#L110-L179 | train |
saltstack/salt | salt/modules/boto_route53.py | list_all_zones_by_name | def list_all_zones_by_name(region=None, key=None, keyid=None, profile=None):
'''
List, by their FQDNs, all hosted zones in the bound account.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
CLI Example:
.. code-block:: bash
salt myminion boto_route53.list_all_zones_by_name
'''
ret = describe_hosted_zones(region=region, key=key, keyid=keyid,
profile=profile)
return [r['Name'] for r in ret] | python | def list_all_zones_by_name(region=None, key=None, keyid=None, profile=None):
'''
List, by their FQDNs, all hosted zones in the bound account.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
CLI Example:
.. code-block:: bash
salt myminion boto_route53.list_all_zones_by_name
'''
ret = describe_hosted_zones(region=region, key=key, keyid=keyid,
profile=profile)
return [r['Name'] for r in ret] | [
"def",
"list_all_zones_by_name",
"(",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"ret",
"=",
"describe_hosted_zones",
"(",
"region",
"=",
"region",
",",
"key",
"=",
"key",
",",
"key... | List, by their FQDNs, all hosted zones in the bound account.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
CLI Example:
.. code-block:: bash
salt myminion boto_route53.list_all_zones_by_name | [
"List",
"by",
"their",
"FQDNs",
"all",
"hosted",
"zones",
"in",
"the",
"bound",
"account",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_route53.py#L182-L207 | train |
saltstack/salt | salt/modules/boto_route53.py | list_all_zones_by_id | def list_all_zones_by_id(region=None, key=None, keyid=None, profile=None):
'''
List, by their IDs, all hosted zones in the bound account.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
CLI Example:
.. code-block:: bash
salt myminion boto_route53.list_all_zones_by_id
'''
ret = describe_hosted_zones(region=region, key=key, keyid=keyid,
profile=profile)
return [r['Id'].replace('/hostedzone/', '') for r in ret] | python | def list_all_zones_by_id(region=None, key=None, keyid=None, profile=None):
'''
List, by their IDs, all hosted zones in the bound account.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
CLI Example:
.. code-block:: bash
salt myminion boto_route53.list_all_zones_by_id
'''
ret = describe_hosted_zones(region=region, key=key, keyid=keyid,
profile=profile)
return [r['Id'].replace('/hostedzone/', '') for r in ret] | [
"def",
"list_all_zones_by_id",
"(",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"ret",
"=",
"describe_hosted_zones",
"(",
"region",
"=",
"region",
",",
"key",
"=",
"key",
",",
"keyid... | List, by their IDs, all hosted zones in the bound account.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
CLI Example:
.. code-block:: bash
salt myminion boto_route53.list_all_zones_by_id | [
"List",
"by",
"their",
"IDs",
"all",
"hosted",
"zones",
"in",
"the",
"bound",
"account",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_route53.py#L210-L235 | train |
saltstack/salt | salt/modules/boto_route53.py | zone_exists | def zone_exists(zone, region=None, key=None, keyid=None, profile=None,
retry_on_rate_limit=None, rate_limit_retries=None,
retry_on_errors=True, error_retries=5):
'''
Check for the existence of a Route53 hosted zone.
.. versionadded:: 2015.8.0
CLI Example::
salt myminion boto_route53.zone_exists example.org
'''
if region is None:
region = 'universal'
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if retry_on_rate_limit or rate_limit_retries is not None:
salt.utils.versions.warn_until(
'Neon',
'The \'retry_on_rate_limit\' and \'rate_limit_retries\' arguments '
'have been deprecated in favor of \'retry_on_errors\' and '
'\'error_retries\' respectively. Their functionality will be '
'removed, as such, their usage is no longer required.'
)
if retry_on_rate_limit is not None:
retry_on_errors = retry_on_rate_limit
if rate_limit_retries is not None:
error_retries = rate_limit_retries
while error_retries > 0:
try:
return bool(conn.get_zone(zone))
except DNSServerError as e:
if retry_on_errors:
if 'Throttling' == e.code:
log.debug('Throttled by AWS API.')
elif 'PriorRequestNotComplete' == e.code:
log.debug('The request was rejected by AWS API.\
Route 53 was still processing a prior request')
time.sleep(3)
error_retries -= 1
continue
raise e | python | def zone_exists(zone, region=None, key=None, keyid=None, profile=None,
retry_on_rate_limit=None, rate_limit_retries=None,
retry_on_errors=True, error_retries=5):
'''
Check for the existence of a Route53 hosted zone.
.. versionadded:: 2015.8.0
CLI Example::
salt myminion boto_route53.zone_exists example.org
'''
if region is None:
region = 'universal'
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if retry_on_rate_limit or rate_limit_retries is not None:
salt.utils.versions.warn_until(
'Neon',
'The \'retry_on_rate_limit\' and \'rate_limit_retries\' arguments '
'have been deprecated in favor of \'retry_on_errors\' and '
'\'error_retries\' respectively. Their functionality will be '
'removed, as such, their usage is no longer required.'
)
if retry_on_rate_limit is not None:
retry_on_errors = retry_on_rate_limit
if rate_limit_retries is not None:
error_retries = rate_limit_retries
while error_retries > 0:
try:
return bool(conn.get_zone(zone))
except DNSServerError as e:
if retry_on_errors:
if 'Throttling' == e.code:
log.debug('Throttled by AWS API.')
elif 'PriorRequestNotComplete' == e.code:
log.debug('The request was rejected by AWS API.\
Route 53 was still processing a prior request')
time.sleep(3)
error_retries -= 1
continue
raise e | [
"def",
"zone_exists",
"(",
"zone",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
",",
"retry_on_rate_limit",
"=",
"None",
",",
"rate_limit_retries",
"=",
"None",
",",
"retry_on_errors",
"=",
... | Check for the existence of a Route53 hosted zone.
.. versionadded:: 2015.8.0
CLI Example::
salt myminion boto_route53.zone_exists example.org | [
"Check",
"for",
"the",
"existence",
"of",
"a",
"Route53",
"hosted",
"zone",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_route53.py#L238-L282 | train |
saltstack/salt | salt/modules/boto_route53.py | create_zone | def create_zone(zone, private=False, vpc_id=None, vpc_region=None, region=None,
key=None, keyid=None, profile=None):
'''
Create a Route53 hosted zone.
.. versionadded:: 2015.8.0
zone
DNS zone to create
private
True/False if the zone will be a private zone
vpc_id
VPC ID to associate the zone to (required if private is True)
vpc_region
VPC Region (required if private is True)
region
region endpoint to connect to
key
AWS key
keyid
AWS keyid
profile
AWS pillar profile
CLI Example::
salt myminion boto_route53.create_zone example.org
'''
if region is None:
region = 'universal'
if private:
if not vpc_id or not vpc_region:
msg = 'vpc_id and vpc_region must be specified for a private zone'
raise SaltInvocationError(msg)
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
_zone = conn.get_zone(zone)
if _zone:
return False
conn.create_zone(zone, private_zone=private, vpc_id=vpc_id,
vpc_region=vpc_region)
return True | python | def create_zone(zone, private=False, vpc_id=None, vpc_region=None, region=None,
key=None, keyid=None, profile=None):
'''
Create a Route53 hosted zone.
.. versionadded:: 2015.8.0
zone
DNS zone to create
private
True/False if the zone will be a private zone
vpc_id
VPC ID to associate the zone to (required if private is True)
vpc_region
VPC Region (required if private is True)
region
region endpoint to connect to
key
AWS key
keyid
AWS keyid
profile
AWS pillar profile
CLI Example::
salt myminion boto_route53.create_zone example.org
'''
if region is None:
region = 'universal'
if private:
if not vpc_id or not vpc_region:
msg = 'vpc_id and vpc_region must be specified for a private zone'
raise SaltInvocationError(msg)
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
_zone = conn.get_zone(zone)
if _zone:
return False
conn.create_zone(zone, private_zone=private, vpc_id=vpc_id,
vpc_region=vpc_region)
return True | [
"def",
"create_zone",
"(",
"zone",
",",
"private",
"=",
"False",
",",
"vpc_id",
"=",
"None",
",",
"vpc_region",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"if"... | Create a Route53 hosted zone.
.. versionadded:: 2015.8.0
zone
DNS zone to create
private
True/False if the zone will be a private zone
vpc_id
VPC ID to associate the zone to (required if private is True)
vpc_region
VPC Region (required if private is True)
region
region endpoint to connect to
key
AWS key
keyid
AWS keyid
profile
AWS pillar profile
CLI Example::
salt myminion boto_route53.create_zone example.org | [
"Create",
"a",
"Route53",
"hosted",
"zone",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_route53.py#L285-L337 | train |
saltstack/salt | salt/modules/boto_route53.py | create_healthcheck | def create_healthcheck(ip_addr=None, fqdn=None, region=None, key=None, keyid=None, profile=None,
port=53, hc_type='TCP', resource_path='', string_match=None, request_interval=30,
failure_threshold=3, retry_on_errors=True, error_retries=5):
'''
Create a Route53 healthcheck
.. versionadded:: 2018.3.0
ip_addr
IP address to check. ip_addr or fqdn is required.
fqdn
Domain name of the endpoint to check. ip_addr or fqdn is required
port
Port to check
hc_type
Healthcheck type. HTTP | HTTPS | HTTP_STR_MATCH | HTTPS_STR_MATCH | TCP
resource_path
Path to check
string_match
If hc_type is HTTP_STR_MATCH or HTTPS_STR_MATCH, the string to search for in the
response body from the specified resource
request_interval
The number of seconds between the time that Amazon Route 53 gets a response from
your endpoint and the time that it sends the next health-check request.
failure_threshold
The number of consecutive health checks that an endpoint must pass or fail for
Amazon Route 53 to change the current status of the endpoint from unhealthy to
healthy or vice versa.
region
Region endpoint to connect to
key
AWS key
keyid
AWS keyid
profile
AWS pillar profile
CLI Example::
salt myminion boto_route53.create_healthcheck 192.168.0.1
salt myminion boto_route53.create_healthcheck 192.168.0.1 port=443 hc_type=HTTPS \
resource_path=/ fqdn=blog.saltstack.furniture
'''
if fqdn is None and ip_addr is None:
msg = 'One of the following must be specified: fqdn or ip_addr'
log.error(msg)
return {'error': msg}
hc_ = boto.route53.healthcheck.HealthCheck(ip_addr,
port,
hc_type,
resource_path,
fqdn=fqdn,
string_match=string_match,
request_interval=request_interval,
failure_threshold=failure_threshold)
if region is None:
region = 'universal'
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
while error_retries > 0:
try:
return {'result': conn.create_health_check(hc_)}
except DNSServerError as exc:
log.debug(exc)
if retry_on_errors:
if 'Throttling' == exc.code:
log.debug('Throttled by AWS API.')
elif 'PriorRequestNotComplete' == exc.code:
log.debug('The request was rejected by AWS API.\
Route 53 was still processing a prior request')
time.sleep(3)
error_retries -= 1
continue
return {'error': __utils__['boto.get_error'](exc)}
return False | python | def create_healthcheck(ip_addr=None, fqdn=None, region=None, key=None, keyid=None, profile=None,
port=53, hc_type='TCP', resource_path='', string_match=None, request_interval=30,
failure_threshold=3, retry_on_errors=True, error_retries=5):
'''
Create a Route53 healthcheck
.. versionadded:: 2018.3.0
ip_addr
IP address to check. ip_addr or fqdn is required.
fqdn
Domain name of the endpoint to check. ip_addr or fqdn is required
port
Port to check
hc_type
Healthcheck type. HTTP | HTTPS | HTTP_STR_MATCH | HTTPS_STR_MATCH | TCP
resource_path
Path to check
string_match
If hc_type is HTTP_STR_MATCH or HTTPS_STR_MATCH, the string to search for in the
response body from the specified resource
request_interval
The number of seconds between the time that Amazon Route 53 gets a response from
your endpoint and the time that it sends the next health-check request.
failure_threshold
The number of consecutive health checks that an endpoint must pass or fail for
Amazon Route 53 to change the current status of the endpoint from unhealthy to
healthy or vice versa.
region
Region endpoint to connect to
key
AWS key
keyid
AWS keyid
profile
AWS pillar profile
CLI Example::
salt myminion boto_route53.create_healthcheck 192.168.0.1
salt myminion boto_route53.create_healthcheck 192.168.0.1 port=443 hc_type=HTTPS \
resource_path=/ fqdn=blog.saltstack.furniture
'''
if fqdn is None and ip_addr is None:
msg = 'One of the following must be specified: fqdn or ip_addr'
log.error(msg)
return {'error': msg}
hc_ = boto.route53.healthcheck.HealthCheck(ip_addr,
port,
hc_type,
resource_path,
fqdn=fqdn,
string_match=string_match,
request_interval=request_interval,
failure_threshold=failure_threshold)
if region is None:
region = 'universal'
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
while error_retries > 0:
try:
return {'result': conn.create_health_check(hc_)}
except DNSServerError as exc:
log.debug(exc)
if retry_on_errors:
if 'Throttling' == exc.code:
log.debug('Throttled by AWS API.')
elif 'PriorRequestNotComplete' == exc.code:
log.debug('The request was rejected by AWS API.\
Route 53 was still processing a prior request')
time.sleep(3)
error_retries -= 1
continue
return {'error': __utils__['boto.get_error'](exc)}
return False | [
"def",
"create_healthcheck",
"(",
"ip_addr",
"=",
"None",
",",
"fqdn",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
",",
"port",
"=",
"53",
",",
"hc_type",
"=",
"'TCP'",
"... | Create a Route53 healthcheck
.. versionadded:: 2018.3.0
ip_addr
IP address to check. ip_addr or fqdn is required.
fqdn
Domain name of the endpoint to check. ip_addr or fqdn is required
port
Port to check
hc_type
Healthcheck type. HTTP | HTTPS | HTTP_STR_MATCH | HTTPS_STR_MATCH | TCP
resource_path
Path to check
string_match
If hc_type is HTTP_STR_MATCH or HTTPS_STR_MATCH, the string to search for in the
response body from the specified resource
request_interval
The number of seconds between the time that Amazon Route 53 gets a response from
your endpoint and the time that it sends the next health-check request.
failure_threshold
The number of consecutive health checks that an endpoint must pass or fail for
Amazon Route 53 to change the current status of the endpoint from unhealthy to
healthy or vice versa.
region
Region endpoint to connect to
key
AWS key
keyid
AWS keyid
profile
AWS pillar profile
CLI Example::
salt myminion boto_route53.create_healthcheck 192.168.0.1
salt myminion boto_route53.create_healthcheck 192.168.0.1 port=443 hc_type=HTTPS \
resource_path=/ fqdn=blog.saltstack.furniture | [
"Create",
"a",
"Route53",
"healthcheck"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_route53.py#L340-L439 | train |
saltstack/salt | salt/modules/boto_route53.py | delete_zone | def delete_zone(zone, region=None, key=None, keyid=None, profile=None):
'''
Delete a Route53 hosted zone.
.. versionadded:: 2015.8.0
CLI Example::
salt myminion boto_route53.delete_zone example.org
'''
if region is None:
region = 'universal'
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
_zone = conn.get_zone(zone)
if _zone:
conn.delete_hosted_zone(_zone.id)
return True
return False | python | def delete_zone(zone, region=None, key=None, keyid=None, profile=None):
'''
Delete a Route53 hosted zone.
.. versionadded:: 2015.8.0
CLI Example::
salt myminion boto_route53.delete_zone example.org
'''
if region is None:
region = 'universal'
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
_zone = conn.get_zone(zone)
if _zone:
conn.delete_hosted_zone(_zone.id)
return True
return False | [
"def",
"delete_zone",
"(",
"zone",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"if",
"region",
"is",
"None",
":",
"region",
"=",
"'universal'",
"conn",
"=",
"_get_conn",
"(",
... | Delete a Route53 hosted zone.
.. versionadded:: 2015.8.0
CLI Example::
salt myminion boto_route53.delete_zone example.org | [
"Delete",
"a",
"Route53",
"hosted",
"zone",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_route53.py#L442-L462 | train |
saltstack/salt | salt/modules/boto_route53.py | get_record | def get_record(name, zone, record_type, fetch_all=False, region=None, key=None,
keyid=None, profile=None, split_dns=False, private_zone=False,
identifier=None, retry_on_rate_limit=None,
rate_limit_retries=None, retry_on_errors=True, error_retries=5):
'''
Get a record from a zone.
CLI example::
salt myminion boto_route53.get_record test.example.org example.org A
'''
if region is None:
region = 'universal'
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if retry_on_rate_limit or rate_limit_retries is not None:
salt.utils.versions.warn_until(
'Neon',
'The \'retry_on_rate_limit\' and \'rate_limit_retries\' arguments '
'have been deprecated in favor of \'retry_on_errors\' and '
'\'error_retries\' respectively. Their functionality will be '
'removed, as such, their usage is no longer required.'
)
if retry_on_rate_limit is not None:
retry_on_errors = retry_on_rate_limit
if rate_limit_retries is not None:
error_retries = rate_limit_retries
while error_retries > 0:
try:
if split_dns:
_zone = _get_split_zone(zone, conn, private_zone)
else:
_zone = conn.get_zone(zone)
if not _zone:
msg = 'Failed to retrieve zone {0}'.format(zone)
log.error(msg)
return None
_type = record_type.upper()
ret = odict.OrderedDict()
name = _encode_name(name)
_record = _zone.find_records(name, _type, all=fetch_all, identifier=identifier)
break # the while True
except DNSServerError as e:
if retry_on_errors:
if 'Throttling' == e.code:
log.debug('Throttled by AWS API.')
elif 'PriorRequestNotComplete' == e.code:
log.debug('The request was rejected by AWS API.\
Route 53 was still processing a prior request')
time.sleep(3)
error_retries -= 1
continue
raise e
if _record:
ret['name'] = _decode_name(_record.name)
ret['value'] = _record.resource_records[0]
ret['record_type'] = _record.type
ret['ttl'] = _record.ttl
if _record.identifier:
ret['identifier'] = []
ret['identifier'].append(_record.identifier)
ret['identifier'].append(_record.weight)
return ret | python | def get_record(name, zone, record_type, fetch_all=False, region=None, key=None,
keyid=None, profile=None, split_dns=False, private_zone=False,
identifier=None, retry_on_rate_limit=None,
rate_limit_retries=None, retry_on_errors=True, error_retries=5):
'''
Get a record from a zone.
CLI example::
salt myminion boto_route53.get_record test.example.org example.org A
'''
if region is None:
region = 'universal'
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if retry_on_rate_limit or rate_limit_retries is not None:
salt.utils.versions.warn_until(
'Neon',
'The \'retry_on_rate_limit\' and \'rate_limit_retries\' arguments '
'have been deprecated in favor of \'retry_on_errors\' and '
'\'error_retries\' respectively. Their functionality will be '
'removed, as such, their usage is no longer required.'
)
if retry_on_rate_limit is not None:
retry_on_errors = retry_on_rate_limit
if rate_limit_retries is not None:
error_retries = rate_limit_retries
while error_retries > 0:
try:
if split_dns:
_zone = _get_split_zone(zone, conn, private_zone)
else:
_zone = conn.get_zone(zone)
if not _zone:
msg = 'Failed to retrieve zone {0}'.format(zone)
log.error(msg)
return None
_type = record_type.upper()
ret = odict.OrderedDict()
name = _encode_name(name)
_record = _zone.find_records(name, _type, all=fetch_all, identifier=identifier)
break # the while True
except DNSServerError as e:
if retry_on_errors:
if 'Throttling' == e.code:
log.debug('Throttled by AWS API.')
elif 'PriorRequestNotComplete' == e.code:
log.debug('The request was rejected by AWS API.\
Route 53 was still processing a prior request')
time.sleep(3)
error_retries -= 1
continue
raise e
if _record:
ret['name'] = _decode_name(_record.name)
ret['value'] = _record.resource_records[0]
ret['record_type'] = _record.type
ret['ttl'] = _record.ttl
if _record.identifier:
ret['identifier'] = []
ret['identifier'].append(_record.identifier)
ret['identifier'].append(_record.weight)
return ret | [
"def",
"get_record",
"(",
"name",
",",
"zone",
",",
"record_type",
",",
"fetch_all",
"=",
"False",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
",",
"split_dns",
"=",
"False",
",",
"priv... | Get a record from a zone.
CLI example::
salt myminion boto_route53.get_record test.example.org example.org A | [
"Get",
"a",
"record",
"from",
"a",
"zone",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_route53.py#L473-L543 | train |
saltstack/salt | salt/modules/boto_route53.py | delete_record | def delete_record(name, zone, record_type, identifier=None, all_records=False,
region=None, key=None, keyid=None, profile=None,
wait_for_sync=True, split_dns=False, private_zone=False,
retry_on_rate_limit=None, rate_limit_retries=None,
retry_on_errors=True, error_retries=5):
'''
Modify a record in a zone.
CLI example::
salt myminion boto_route53.delete_record test.example.org example.org A
'''
if region is None:
region = 'universal'
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if split_dns:
_zone = _get_split_zone(zone, conn, private_zone)
else:
_zone = conn.get_zone(zone)
if not _zone:
msg = 'Failed to retrieve zone {0}'.format(zone)
log.error(msg)
return False
_type = record_type.upper()
if retry_on_rate_limit or rate_limit_retries is not None:
salt.utils.versions.warn_until(
'Neon',
'The \'retry_on_rate_limit\' and \'rate_limit_retries\' arguments '
'have been deprecated in favor of \'retry_on_errors\' and '
'\'error_retries\' respectively. Their functionality will be '
'removed, as such, their usage is no longer required.'
)
if retry_on_rate_limit is not None:
retry_on_errors = retry_on_rate_limit
if rate_limit_retries is not None:
error_retries = rate_limit_retries
while error_retries > 0:
try:
old_record = _zone.find_records(name, _type, all=all_records, identifier=identifier)
if not old_record:
return False
status = _zone.delete_record(old_record)
return _wait_for_sync(status.id, conn, wait_for_sync)
except DNSServerError as e:
if retry_on_errors:
if 'Throttling' == e.code:
log.debug('Throttled by AWS API.')
elif 'PriorRequestNotComplete' == e.code:
log.debug('The request was rejected by AWS API.\
Route 53 was still processing a prior request')
time.sleep(3)
error_retries -= 1
continue
raise e | python | def delete_record(name, zone, record_type, identifier=None, all_records=False,
region=None, key=None, keyid=None, profile=None,
wait_for_sync=True, split_dns=False, private_zone=False,
retry_on_rate_limit=None, rate_limit_retries=None,
retry_on_errors=True, error_retries=5):
'''
Modify a record in a zone.
CLI example::
salt myminion boto_route53.delete_record test.example.org example.org A
'''
if region is None:
region = 'universal'
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if split_dns:
_zone = _get_split_zone(zone, conn, private_zone)
else:
_zone = conn.get_zone(zone)
if not _zone:
msg = 'Failed to retrieve zone {0}'.format(zone)
log.error(msg)
return False
_type = record_type.upper()
if retry_on_rate_limit or rate_limit_retries is not None:
salt.utils.versions.warn_until(
'Neon',
'The \'retry_on_rate_limit\' and \'rate_limit_retries\' arguments '
'have been deprecated in favor of \'retry_on_errors\' and '
'\'error_retries\' respectively. Their functionality will be '
'removed, as such, their usage is no longer required.'
)
if retry_on_rate_limit is not None:
retry_on_errors = retry_on_rate_limit
if rate_limit_retries is not None:
error_retries = rate_limit_retries
while error_retries > 0:
try:
old_record = _zone.find_records(name, _type, all=all_records, identifier=identifier)
if not old_record:
return False
status = _zone.delete_record(old_record)
return _wait_for_sync(status.id, conn, wait_for_sync)
except DNSServerError as e:
if retry_on_errors:
if 'Throttling' == e.code:
log.debug('Throttled by AWS API.')
elif 'PriorRequestNotComplete' == e.code:
log.debug('The request was rejected by AWS API.\
Route 53 was still processing a prior request')
time.sleep(3)
error_retries -= 1
continue
raise e | [
"def",
"delete_record",
"(",
"name",
",",
"zone",
",",
"record_type",
",",
"identifier",
"=",
"None",
",",
"all_records",
"=",
"False",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
",",
... | Modify a record in a zone.
CLI example::
salt myminion boto_route53.delete_record test.example.org example.org A | [
"Modify",
"a",
"record",
"in",
"a",
"zone",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_route53.py#L692-L750 | train |
saltstack/salt | salt/modules/boto_route53.py | create_hosted_zone | def create_hosted_zone(domain_name, caller_ref=None, comment='', private_zone=False, vpc_id=None,
vpc_name=None, vpc_region=None, region=None, key=None, keyid=None,
profile=None):
'''
Create a new Route53 Hosted Zone. Returns a Python data structure with information about the
newly created Hosted Zone.
domain_name
The name of the domain. This must be fully-qualified, terminating with a period. This is
the name you have registered with your domain registrar. It is also the name you will
delegate from your registrar to the Amazon Route 53 delegation servers returned in response
to this request.
caller_ref
A unique string that identifies the request and that allows create_hosted_zone() calls to
be retried without the risk of executing the operation twice. It can take several minutes
for the change to replicate globally, and change from PENDING to INSYNC status. Thus it's
best to provide some value for this where possible, since duplicate calls while the first
is in PENDING status will be accepted and can lead to multiple copies of the zone being
created. On the other hand, if a zone is created with a given caller_ref, then deleted,
a second attempt to create a zone with the same caller_ref will fail until that caller_ref
is flushed from the Route53 system, which can take upwards of 24 hours.
comment
Any comments you want to include about the hosted zone.
private_zone
Set True if creating a private hosted zone.
vpc_id
When creating a private hosted zone, either the VPC ID or VPC Name to associate with is
required. Exclusive with vpe_name. Ignored when creating a non-private zone.
vpc_name
When creating a private hosted zone, either the VPC ID or VPC Name to associate with is
required. Exclusive with vpe_id. Ignored when creating a non-private zone.
vpc_region
When creating a private hosted zone, the region of the associated VPC is required. If not
provided, an effort will be made to determine it from vpc_id or vpc_name, where possible.
If this fails, you'll need to provide an explicit value for this option. Ignored when
creating a non-private zone.
region
Region endpoint to connect to.
key
AWS key to bind with.
keyid
AWS keyid to bind with.
profile
Dict, or pillar key pointing to a dict, containing AWS region/key/keyid.
CLI Example::
salt myminion boto_route53.create_hosted_zone example.org
'''
if region is None:
region = 'universal'
if not domain_name.endswith('.'):
raise SaltInvocationError('Domain MUST be fully-qualified, complete '
'with ending period.')
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
deets = conn.get_hosted_zone_by_name(domain_name)
if deets:
log.info('Route53 hosted zone %s already exists', domain_name)
return None
args = {'domain_name': domain_name,
'caller_ref': caller_ref,
'comment': comment,
'private_zone': private_zone}
if private_zone:
if not _exactly_one((vpc_name, vpc_id)):
raise SaltInvocationError('Either vpc_name or vpc_id is required '
'when creating a private zone.')
vpcs = __salt__['boto_vpc.describe_vpcs'](
vpc_id=vpc_id, name=vpc_name, region=region, key=key,
keyid=keyid, profile=profile).get('vpcs', [])
if vpc_region and vpcs:
vpcs = [v for v in vpcs if v['region'] == vpc_region]
if not vpcs:
log.error('Private zone requested but a VPC matching given criteria'
' not found.')
return None
if len(vpcs) > 1:
log.error('Private zone requested but multiple VPCs matching given '
'criteria found: %s.', [v['id'] for v in vpcs])
return None
vpc = vpcs[0]
if vpc_name:
vpc_id = vpc['id']
if not vpc_region:
vpc_region = vpc['region']
args.update({'vpc_id': vpc_id, 'vpc_region': vpc_region})
else:
if any((vpc_id, vpc_name, vpc_region)):
log.info('Options vpc_id, vpc_name, and vpc_region are ignored '
'when creating non-private zones.')
r = _try_func(conn, 'create_hosted_zone', **args)
if r is None:
log.error('Failed to create hosted zone %s', domain_name)
return None
r = r.get('CreateHostedZoneResponse', {})
# Pop it since it'll be irrelevant by the time we return
status = r.pop('ChangeInfo', {}).get('Id', '').replace('/change/', '')
synced = _wait_for_sync(status, conn, wait=600)
if not synced:
log.error('Hosted zone %s not synced after 600 seconds.', domain_name)
return None
return r | python | def create_hosted_zone(domain_name, caller_ref=None, comment='', private_zone=False, vpc_id=None,
vpc_name=None, vpc_region=None, region=None, key=None, keyid=None,
profile=None):
'''
Create a new Route53 Hosted Zone. Returns a Python data structure with information about the
newly created Hosted Zone.
domain_name
The name of the domain. This must be fully-qualified, terminating with a period. This is
the name you have registered with your domain registrar. It is also the name you will
delegate from your registrar to the Amazon Route 53 delegation servers returned in response
to this request.
caller_ref
A unique string that identifies the request and that allows create_hosted_zone() calls to
be retried without the risk of executing the operation twice. It can take several minutes
for the change to replicate globally, and change from PENDING to INSYNC status. Thus it's
best to provide some value for this where possible, since duplicate calls while the first
is in PENDING status will be accepted and can lead to multiple copies of the zone being
created. On the other hand, if a zone is created with a given caller_ref, then deleted,
a second attempt to create a zone with the same caller_ref will fail until that caller_ref
is flushed from the Route53 system, which can take upwards of 24 hours.
comment
Any comments you want to include about the hosted zone.
private_zone
Set True if creating a private hosted zone.
vpc_id
When creating a private hosted zone, either the VPC ID or VPC Name to associate with is
required. Exclusive with vpe_name. Ignored when creating a non-private zone.
vpc_name
When creating a private hosted zone, either the VPC ID or VPC Name to associate with is
required. Exclusive with vpe_id. Ignored when creating a non-private zone.
vpc_region
When creating a private hosted zone, the region of the associated VPC is required. If not
provided, an effort will be made to determine it from vpc_id or vpc_name, where possible.
If this fails, you'll need to provide an explicit value for this option. Ignored when
creating a non-private zone.
region
Region endpoint to connect to.
key
AWS key to bind with.
keyid
AWS keyid to bind with.
profile
Dict, or pillar key pointing to a dict, containing AWS region/key/keyid.
CLI Example::
salt myminion boto_route53.create_hosted_zone example.org
'''
if region is None:
region = 'universal'
if not domain_name.endswith('.'):
raise SaltInvocationError('Domain MUST be fully-qualified, complete '
'with ending period.')
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
deets = conn.get_hosted_zone_by_name(domain_name)
if deets:
log.info('Route53 hosted zone %s already exists', domain_name)
return None
args = {'domain_name': domain_name,
'caller_ref': caller_ref,
'comment': comment,
'private_zone': private_zone}
if private_zone:
if not _exactly_one((vpc_name, vpc_id)):
raise SaltInvocationError('Either vpc_name or vpc_id is required '
'when creating a private zone.')
vpcs = __salt__['boto_vpc.describe_vpcs'](
vpc_id=vpc_id, name=vpc_name, region=region, key=key,
keyid=keyid, profile=profile).get('vpcs', [])
if vpc_region and vpcs:
vpcs = [v for v in vpcs if v['region'] == vpc_region]
if not vpcs:
log.error('Private zone requested but a VPC matching given criteria'
' not found.')
return None
if len(vpcs) > 1:
log.error('Private zone requested but multiple VPCs matching given '
'criteria found: %s.', [v['id'] for v in vpcs])
return None
vpc = vpcs[0]
if vpc_name:
vpc_id = vpc['id']
if not vpc_region:
vpc_region = vpc['region']
args.update({'vpc_id': vpc_id, 'vpc_region': vpc_region})
else:
if any((vpc_id, vpc_name, vpc_region)):
log.info('Options vpc_id, vpc_name, and vpc_region are ignored '
'when creating non-private zones.')
r = _try_func(conn, 'create_hosted_zone', **args)
if r is None:
log.error('Failed to create hosted zone %s', domain_name)
return None
r = r.get('CreateHostedZoneResponse', {})
# Pop it since it'll be irrelevant by the time we return
status = r.pop('ChangeInfo', {}).get('Id', '').replace('/change/', '')
synced = _wait_for_sync(status, conn, wait=600)
if not synced:
log.error('Hosted zone %s not synced after 600 seconds.', domain_name)
return None
return r | [
"def",
"create_hosted_zone",
"(",
"domain_name",
",",
"caller_ref",
"=",
"None",
",",
"comment",
"=",
"''",
",",
"private_zone",
"=",
"False",
",",
"vpc_id",
"=",
"None",
",",
"vpc_name",
"=",
"None",
",",
"vpc_region",
"=",
"None",
",",
"region",
"=",
"... | Create a new Route53 Hosted Zone. Returns a Python data structure with information about the
newly created Hosted Zone.
domain_name
The name of the domain. This must be fully-qualified, terminating with a period. This is
the name you have registered with your domain registrar. It is also the name you will
delegate from your registrar to the Amazon Route 53 delegation servers returned in response
to this request.
caller_ref
A unique string that identifies the request and that allows create_hosted_zone() calls to
be retried without the risk of executing the operation twice. It can take several minutes
for the change to replicate globally, and change from PENDING to INSYNC status. Thus it's
best to provide some value for this where possible, since duplicate calls while the first
is in PENDING status will be accepted and can lead to multiple copies of the zone being
created. On the other hand, if a zone is created with a given caller_ref, then deleted,
a second attempt to create a zone with the same caller_ref will fail until that caller_ref
is flushed from the Route53 system, which can take upwards of 24 hours.
comment
Any comments you want to include about the hosted zone.
private_zone
Set True if creating a private hosted zone.
vpc_id
When creating a private hosted zone, either the VPC ID or VPC Name to associate with is
required. Exclusive with vpe_name. Ignored when creating a non-private zone.
vpc_name
When creating a private hosted zone, either the VPC ID or VPC Name to associate with is
required. Exclusive with vpe_id. Ignored when creating a non-private zone.
vpc_region
When creating a private hosted zone, the region of the associated VPC is required. If not
provided, an effort will be made to determine it from vpc_id or vpc_name, where possible.
If this fails, you'll need to provide an explicit value for this option. Ignored when
creating a non-private zone.
region
Region endpoint to connect to.
key
AWS key to bind with.
keyid
AWS keyid to bind with.
profile
Dict, or pillar key pointing to a dict, containing AWS region/key/keyid.
CLI Example::
salt myminion boto_route53.create_hosted_zone example.org | [
"Create",
"a",
"new",
"Route53",
"Hosted",
"Zone",
".",
"Returns",
"a",
"Python",
"data",
"structure",
"with",
"information",
"about",
"the",
"newly",
"created",
"Hosted",
"Zone",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_route53.py#L798-L915 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.