repository_name
stringclasses 316
values | func_path_in_repository
stringlengths 6
223
| func_name
stringlengths 1
134
| language
stringclasses 1
value | func_code_string
stringlengths 57
65.5k
| func_documentation_string
stringlengths 1
46.3k
| split_name
stringclasses 1
value | func_code_url
stringlengths 91
315
| called_functions
listlengths 1
156
⌀ | enclosing_scope
stringlengths 2
1.48M
|
|---|---|---|---|---|---|---|---|---|---|
saltstack/salt
|
salt/modules/kmod.py
|
mod_list
|
python
|
def mod_list(only_persist=False):
'''
Return a list of the loaded module names
only_persist
Only return the list of loaded persistent modules
CLI Example:
.. code-block:: bash
salt '*' kmod.mod_list
'''
mods = set()
if only_persist:
conf = _get_modules_conf()
if os.path.exists(conf):
try:
with salt.utils.files.fopen(conf, 'r') as modules_file:
for line in modules_file:
line = line.strip()
mod_name = _strip_module_name(line)
if not line.startswith('#') and mod_name:
mods.add(mod_name)
except IOError:
log.error('kmod module could not open modules file at %s', conf)
else:
for mod in lsmod():
mods.add(mod['module'])
return sorted(list(mods))
|
Return a list of the loaded module names
only_persist
Only return the list of loaded persistent modules
CLI Example:
.. code-block:: bash
salt '*' kmod.mod_list
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/kmod.py#L196-L225
|
[
"def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n",
"def lsmod():\n '''\n Return a dict containing information about currently loaded modules\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' kmod.lsmod\n '''\n ret = []\n for line in __salt__['cmd.run']('lsmod').splitlines():\n comps = line.split()\n if not len(comps) > 2:\n continue\n if comps[0] == 'Module':\n continue\n mdat = {\n 'size': comps[1],\n 'module': comps[0],\n 'depcount': comps[2],\n }\n if len(comps) > 3:\n mdat['deps'] = comps[3].split(',')\n else:\n mdat['deps'] = []\n ret.append(mdat)\n return ret\n",
"def _get_modules_conf():\n '''\n Return location of modules config file.\n Default: /etc/modules\n '''\n if 'systemd' in __grains__:\n return '/etc/modules-load.d/salt_managed.conf'\n return '/etc/modules'\n",
"def _strip_module_name(mod):\n '''\n Return module name and strip configuration. It is possible insert modules\n in this format:\n bonding mode=4 miimon=1000\n This method return only 'bonding'\n '''\n if mod.strip() == '':\n return False\n return mod.split()[0]\n"
] |
# -*- coding: utf-8 -*-
'''
Module to manage Linux kernel modules
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
import re
import logging
# Import salt libs
import salt.utils.files
import salt.utils.path
log = logging.getLogger(__name__)
def __virtual__():
'''
Only runs on Linux systems
'''
return __grains__['kernel'] == 'Linux'
def _new_mods(pre_mods, post_mods):
'''
Return a list of the new modules, pass an lsmod dict before running
modprobe and one after modprobe has run
'''
pre = set()
post = set()
for mod in pre_mods:
pre.add(mod['module'])
for mod in post_mods:
post.add(mod['module'])
return post - pre
def _rm_mods(pre_mods, post_mods):
'''
Return a list of the new modules, pass an lsmod dict before running
modprobe and one after modprobe has run
'''
pre = set()
post = set()
for mod in pre_mods:
pre.add(mod['module'])
for mod in post_mods:
post.add(mod['module'])
return pre - post
def _get_modules_conf():
'''
Return location of modules config file.
Default: /etc/modules
'''
if 'systemd' in __grains__:
return '/etc/modules-load.d/salt_managed.conf'
return '/etc/modules'
def _strip_module_name(mod):
'''
Return module name and strip configuration. It is possible insert modules
in this format:
bonding mode=4 miimon=1000
This method return only 'bonding'
'''
if mod.strip() == '':
return False
return mod.split()[0]
def _set_persistent_module(mod):
'''
Add module to configuration file to make it persistent. If module is
commented uncomment it.
'''
conf = _get_modules_conf()
if not os.path.exists(conf):
__salt__['file.touch'](conf)
mod_name = _strip_module_name(mod)
if not mod_name or mod_name in mod_list(True) or mod_name \
not in available():
return set()
escape_mod = re.escape(mod)
# If module is commented only uncomment it
if __salt__['file.search'](conf,
'^#[\t ]*{0}[\t ]*$'.format(escape_mod),
multiline=True):
__salt__['file.uncomment'](conf, escape_mod)
else:
__salt__['file.append'](conf, mod)
return set([mod_name])
def _remove_persistent_module(mod, comment):
'''
Remove module from configuration file. If comment is true only comment line
where module is.
'''
conf = _get_modules_conf()
mod_name = _strip_module_name(mod)
if not mod_name or mod_name not in mod_list(True):
return set()
escape_mod = re.escape(mod)
if comment:
__salt__['file.comment'](conf, '^[\t ]*{0}[\t ]?'.format(escape_mod))
else:
__salt__['file.sed'](conf, '^[\t ]*{0}[\t ]?'.format(escape_mod), '')
return set([mod_name])
def available():
'''
Return a list of all available kernel modules
CLI Example:
.. code-block:: bash
salt '*' kmod.available
'''
ret = []
mod_dir = os.path.join('/lib/modules/', os.uname()[2])
built_in_file = os.path.join(mod_dir, 'modules.builtin')
if os.path.exists(built_in_file):
with salt.utils.files.fopen(built_in_file, 'r') as f:
for line in f:
# Strip .ko from the basename
ret.append(os.path.basename(line)[:-4])
for root, dirs, files in salt.utils.path.os_walk(mod_dir):
for fn_ in files:
if '.ko' in fn_:
ret.append(fn_[:fn_.index('.ko')].replace('-', '_'))
if 'Arch' in __grains__['os_family']:
# Sadly this path is relative to kernel major version but ignores minor version
mod_dir_arch = '/lib/modules/extramodules-' + os.uname()[2][0:3] + '-ARCH'
for root, dirs, files in salt.utils.path.os_walk(mod_dir_arch):
for fn_ in files:
if '.ko' in fn_:
ret.append(fn_[:fn_.index('.ko')].replace('-', '_'))
return sorted(list(ret))
def check_available(mod):
'''
Check to see if the specified kernel module is available
CLI Example:
.. code-block:: bash
salt '*' kmod.check_available kvm
'''
return mod in available()
def lsmod():
'''
Return a dict containing information about currently loaded modules
CLI Example:
.. code-block:: bash
salt '*' kmod.lsmod
'''
ret = []
for line in __salt__['cmd.run']('lsmod').splitlines():
comps = line.split()
if not len(comps) > 2:
continue
if comps[0] == 'Module':
continue
mdat = {
'size': comps[1],
'module': comps[0],
'depcount': comps[2],
}
if len(comps) > 3:
mdat['deps'] = comps[3].split(',')
else:
mdat['deps'] = []
ret.append(mdat)
return ret
def load(mod, persist=False):
'''
Load the specified kernel module
mod
Name of module to add
persist
Write module to /etc/modules to make it load on system reboot
CLI Example:
.. code-block:: bash
salt '*' kmod.load kvm
'''
pre_mods = lsmod()
res = __salt__['cmd.run_all']('modprobe {0}'.format(mod), python_shell=False)
if res['retcode'] == 0:
post_mods = lsmod()
mods = _new_mods(pre_mods, post_mods)
persist_mods = set()
if persist:
persist_mods = _set_persistent_module(mod)
return sorted(list(mods | persist_mods))
else:
return 'Error loading module {0}: {1}'.format(mod, res['stderr'])
def is_loaded(mod):
'''
Check to see if the specified kernel module is loaded
CLI Example:
.. code-block:: bash
salt '*' kmod.is_loaded kvm
'''
return mod in mod_list()
def remove(mod, persist=False, comment=True):
'''
Remove the specified kernel module
mod
Name of module to remove
persist
Also remove module from /etc/modules
comment
If persist is set don't remove line from /etc/modules but only
comment it
CLI Example:
.. code-block:: bash
salt '*' kmod.remove kvm
'''
pre_mods = lsmod()
res = __salt__['cmd.run_all']('rmmod {0}'.format(mod), python_shell=False)
if res['retcode'] == 0:
post_mods = lsmod()
mods = _rm_mods(pre_mods, post_mods)
persist_mods = set()
if persist:
persist_mods = _remove_persistent_module(mod, comment)
return sorted(list(mods | persist_mods))
else:
return 'Error removing module {0}: {1}'.format(mod, res['stderr'])
|
saltstack/salt
|
salt/modules/kmod.py
|
load
|
python
|
def load(mod, persist=False):
'''
Load the specified kernel module
mod
Name of module to add
persist
Write module to /etc/modules to make it load on system reboot
CLI Example:
.. code-block:: bash
salt '*' kmod.load kvm
'''
pre_mods = lsmod()
res = __salt__['cmd.run_all']('modprobe {0}'.format(mod), python_shell=False)
if res['retcode'] == 0:
post_mods = lsmod()
mods = _new_mods(pre_mods, post_mods)
persist_mods = set()
if persist:
persist_mods = _set_persistent_module(mod)
return sorted(list(mods | persist_mods))
else:
return 'Error loading module {0}: {1}'.format(mod, res['stderr'])
|
Load the specified kernel module
mod
Name of module to add
persist
Write module to /etc/modules to make it load on system reboot
CLI Example:
.. code-block:: bash
salt '*' kmod.load kvm
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/kmod.py#L228-L254
|
[
"def _new_mods(pre_mods, post_mods):\n '''\n Return a list of the new modules, pass an lsmod dict before running\n modprobe and one after modprobe has run\n '''\n pre = set()\n post = set()\n for mod in pre_mods:\n pre.add(mod['module'])\n for mod in post_mods:\n post.add(mod['module'])\n return post - pre\n",
"def _set_persistent_module(mod):\n '''\n Add module to configuration file to make it persistent. If module is\n commented uncomment it.\n '''\n conf = _get_modules_conf()\n if not os.path.exists(conf):\n __salt__['file.touch'](conf)\n mod_name = _strip_module_name(mod)\n if not mod_name or mod_name in mod_list(True) or mod_name \\\n not in available():\n return set()\n escape_mod = re.escape(mod)\n # If module is commented only uncomment it\n if __salt__['file.search'](conf,\n '^#[\\t ]*{0}[\\t ]*$'.format(escape_mod),\n multiline=True):\n __salt__['file.uncomment'](conf, escape_mod)\n else:\n __salt__['file.append'](conf, mod)\n return set([mod_name])\n",
"def lsmod():\n '''\n Return a dict containing information about currently loaded modules\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' kmod.lsmod\n '''\n ret = []\n for line in __salt__['cmd.run']('lsmod').splitlines():\n comps = line.split()\n if not len(comps) > 2:\n continue\n if comps[0] == 'Module':\n continue\n mdat = {\n 'size': comps[1],\n 'module': comps[0],\n 'depcount': comps[2],\n }\n if len(comps) > 3:\n mdat['deps'] = comps[3].split(',')\n else:\n mdat['deps'] = []\n ret.append(mdat)\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Module to manage Linux kernel modules
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
import re
import logging
# Import salt libs
import salt.utils.files
import salt.utils.path
log = logging.getLogger(__name__)
def __virtual__():
'''
Only runs on Linux systems
'''
return __grains__['kernel'] == 'Linux'
def _new_mods(pre_mods, post_mods):
'''
Return a list of the new modules, pass an lsmod dict before running
modprobe and one after modprobe has run
'''
pre = set()
post = set()
for mod in pre_mods:
pre.add(mod['module'])
for mod in post_mods:
post.add(mod['module'])
return post - pre
def _rm_mods(pre_mods, post_mods):
'''
Return a list of the new modules, pass an lsmod dict before running
modprobe and one after modprobe has run
'''
pre = set()
post = set()
for mod in pre_mods:
pre.add(mod['module'])
for mod in post_mods:
post.add(mod['module'])
return pre - post
def _get_modules_conf():
'''
Return location of modules config file.
Default: /etc/modules
'''
if 'systemd' in __grains__:
return '/etc/modules-load.d/salt_managed.conf'
return '/etc/modules'
def _strip_module_name(mod):
'''
Return module name and strip configuration. It is possible insert modules
in this format:
bonding mode=4 miimon=1000
This method return only 'bonding'
'''
if mod.strip() == '':
return False
return mod.split()[0]
def _set_persistent_module(mod):
'''
Add module to configuration file to make it persistent. If module is
commented uncomment it.
'''
conf = _get_modules_conf()
if not os.path.exists(conf):
__salt__['file.touch'](conf)
mod_name = _strip_module_name(mod)
if not mod_name or mod_name in mod_list(True) or mod_name \
not in available():
return set()
escape_mod = re.escape(mod)
# If module is commented only uncomment it
if __salt__['file.search'](conf,
'^#[\t ]*{0}[\t ]*$'.format(escape_mod),
multiline=True):
__salt__['file.uncomment'](conf, escape_mod)
else:
__salt__['file.append'](conf, mod)
return set([mod_name])
def _remove_persistent_module(mod, comment):
'''
Remove module from configuration file. If comment is true only comment line
where module is.
'''
conf = _get_modules_conf()
mod_name = _strip_module_name(mod)
if not mod_name or mod_name not in mod_list(True):
return set()
escape_mod = re.escape(mod)
if comment:
__salt__['file.comment'](conf, '^[\t ]*{0}[\t ]?'.format(escape_mod))
else:
__salt__['file.sed'](conf, '^[\t ]*{0}[\t ]?'.format(escape_mod), '')
return set([mod_name])
def available():
'''
Return a list of all available kernel modules
CLI Example:
.. code-block:: bash
salt '*' kmod.available
'''
ret = []
mod_dir = os.path.join('/lib/modules/', os.uname()[2])
built_in_file = os.path.join(mod_dir, 'modules.builtin')
if os.path.exists(built_in_file):
with salt.utils.files.fopen(built_in_file, 'r') as f:
for line in f:
# Strip .ko from the basename
ret.append(os.path.basename(line)[:-4])
for root, dirs, files in salt.utils.path.os_walk(mod_dir):
for fn_ in files:
if '.ko' in fn_:
ret.append(fn_[:fn_.index('.ko')].replace('-', '_'))
if 'Arch' in __grains__['os_family']:
# Sadly this path is relative to kernel major version but ignores minor version
mod_dir_arch = '/lib/modules/extramodules-' + os.uname()[2][0:3] + '-ARCH'
for root, dirs, files in salt.utils.path.os_walk(mod_dir_arch):
for fn_ in files:
if '.ko' in fn_:
ret.append(fn_[:fn_.index('.ko')].replace('-', '_'))
return sorted(list(ret))
def check_available(mod):
'''
Check to see if the specified kernel module is available
CLI Example:
.. code-block:: bash
salt '*' kmod.check_available kvm
'''
return mod in available()
def lsmod():
'''
Return a dict containing information about currently loaded modules
CLI Example:
.. code-block:: bash
salt '*' kmod.lsmod
'''
ret = []
for line in __salt__['cmd.run']('lsmod').splitlines():
comps = line.split()
if not len(comps) > 2:
continue
if comps[0] == 'Module':
continue
mdat = {
'size': comps[1],
'module': comps[0],
'depcount': comps[2],
}
if len(comps) > 3:
mdat['deps'] = comps[3].split(',')
else:
mdat['deps'] = []
ret.append(mdat)
return ret
def mod_list(only_persist=False):
'''
Return a list of the loaded module names
only_persist
Only return the list of loaded persistent modules
CLI Example:
.. code-block:: bash
salt '*' kmod.mod_list
'''
mods = set()
if only_persist:
conf = _get_modules_conf()
if os.path.exists(conf):
try:
with salt.utils.files.fopen(conf, 'r') as modules_file:
for line in modules_file:
line = line.strip()
mod_name = _strip_module_name(line)
if not line.startswith('#') and mod_name:
mods.add(mod_name)
except IOError:
log.error('kmod module could not open modules file at %s', conf)
else:
for mod in lsmod():
mods.add(mod['module'])
return sorted(list(mods))
def is_loaded(mod):
'''
Check to see if the specified kernel module is loaded
CLI Example:
.. code-block:: bash
salt '*' kmod.is_loaded kvm
'''
return mod in mod_list()
def remove(mod, persist=False, comment=True):
'''
Remove the specified kernel module
mod
Name of module to remove
persist
Also remove module from /etc/modules
comment
If persist is set don't remove line from /etc/modules but only
comment it
CLI Example:
.. code-block:: bash
salt '*' kmod.remove kvm
'''
pre_mods = lsmod()
res = __salt__['cmd.run_all']('rmmod {0}'.format(mod), python_shell=False)
if res['retcode'] == 0:
post_mods = lsmod()
mods = _rm_mods(pre_mods, post_mods)
persist_mods = set()
if persist:
persist_mods = _remove_persistent_module(mod, comment)
return sorted(list(mods | persist_mods))
else:
return 'Error removing module {0}: {1}'.format(mod, res['stderr'])
|
saltstack/salt
|
salt/proxy/onyx.py
|
init
|
python
|
def init(opts=None):
'''
Required.
Can be used to initialize the server connection.
'''
if opts is None:
opts = __opts__
try:
DETAILS[_worker_name()] = SSHConnection(
host=opts['proxy']['host'],
username=opts['proxy']['username'],
password=opts['proxy']['password'],
key_accept=opts['proxy'].get('key_accept', False),
ssh_args=opts['proxy'].get('ssh_args', ''),
prompt='{0}.*(#|>) '.format(opts['proxy']['prompt_name']))
DETAILS[_worker_name()].sendline('no cli session paging enable')
except TerminalException as e:
log.error(e)
return False
DETAILS['initialized'] = True
|
Required.
Can be used to initialize the server connection.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/onyx.py#L87-L107
|
[
"def _worker_name():\n return multiprocessing.current_process().name\n"
] |
# -*- coding: utf-8 -*-
'''
Proxy Minion for Onyx OS Switches
.. versionadded: Neon
The Onyx OS Proxy Minion uses the built in SSHConnection module
in :mod:`salt.utils.vt_helper <salt.utils.vt_helper>`
To configure the proxy minion:
.. code-block:: yaml
proxy:
proxytype: onyx
host: 192.168.187.100
username: admin
password: admin
prompt_name: switch
ssh_args: '-o PubkeyAuthentication=no'
key_accept: True
proxytype
(REQUIRED) Use this proxy minion `onyx`
host
(REQUIRED) ip address or hostname to connect to
username
(REQUIRED) username to login with
password
(REQUIRED) password to use to login with
prompt_name
(REQUIRED) The name in the prompt on the switch. By default, use your
devices hostname.
ssh_args
Any extra args to use to connect to the switch.
key_accept
Whether or not to accept a the host key of the switch on initial login.
Defaults to False.
The functions from the proxy minion can be run from the salt commandline using
the :mod:`salt.modules.onyx<salt.modules.onyx>` execution module.
.. note:
If `multiprocessing: True` is set for the proxy minion config, each forked
worker will open up a new connection to the Cisco NX OS Switch. If you
only want one consistent connection used for everything, use
`multiprocessing: False`
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import multiprocessing
import re
# Import Salt libs
from salt.utils.vt_helper import SSHConnection
from salt.utils.vt import TerminalException
log = logging.getLogger(__file__)
__proxyenabled__ = ['onyx']
__virtualname__ = 'onyx'
DETAILS = {'grains_cache': {}}
def __virtual__():
'''
Only return if all the modules are available
'''
log.info('onyx proxy __virtual__() called...')
return __virtualname__
def _worker_name():
return multiprocessing.current_process().name
def initialized():
'''
module initialization
'''
return DETAILS.get('initialized', False)
def ping():
'''
Ping the device on the other end of the connection
.. code-block: bash
salt '*' onyx.cmd ping
'''
if _worker_name() not in DETAILS:
init()
try:
return DETAILS[_worker_name()].conn.isalive()
except TerminalException as e:
log.error(e)
return False
def shutdown():
'''
Disconnect
'''
DETAILS[_worker_name()].close_connection()
def sendline(command):
'''
Run command through switch's cli
.. code-block: bash
salt '*' onyx.cmd sendline 'show run | include
"username admin password 7"'
'''
if ping() is False:
init()
out, _ = DETAILS[_worker_name()].sendline(command)
return out
def enable():
'''
Shortcut to run `enable` on switch
.. code-block:: bash
salt '*' onyx.cmd enable
'''
try:
ret = sendline('enable')
except TerminalException as e:
log.error(e)
return 'Failed to enable switch'
return ret
def configure_terminal():
'''
Shortcut to run `configure terminal` on switch
.. code-block:: bash
salt '*' onyx.cmd configure_terminal
'''
try:
ret = sendline('configure terminal ')
except TerminalException as e:
log.error(e)
return 'Failed to enable ' \
'configuration mode on switch'
return ret
def configure_terminal_exit():
'''
Shortcut to run `exit` from configuration mode on switch
.. code-block:: bash
salt '*' onyx.cmd configure_terminal_exit
'''
try:
ret = sendline('exit')
except TerminalException as e:
log.error(e)
return 'Failed to exit form configuration mode on switch'
return ret
def disable():
'''
Shortcut to run `disable` on switch
.. code-block:: bash
salt '*' onyx.cmd disable
'''
try:
ret = sendline('disable')
except TerminalException as e:
log.error(e)
return 'Failed to "configure terminal"'
return ret
def grains():
'''
Get grains for proxy minion
.. code-block: bash
salt '*' onyx.cmd grains
'''
if not DETAILS['grains_cache']:
ret = system_info()
log.debug(ret)
DETAILS['grains_cache'].update(ret)
return {'onyx': DETAILS['grains_cache']}
def grains_refresh():
'''
Refresh the grains from the proxy device.
.. code-block: bash
salt '*' onyx.cmd grains_refresh
'''
DETAILS['grains_cache'] = {}
return grains()
def get_user(username):
'''
Get username line from switch
.. code-block: bash
salt '*' onyx.cmd get_user username=admin
'''
try:
enable()
configure_terminal()
cmd_out = sendline('show running-config | include "username {0} password 7"'.format(username))
cmd_out.split('\n')
user = cmd_out[1:-1]
configure_terminal_exit()
disable()
return user
except TerminalException as e:
log.error(e)
return 'Failed to get user'
def get_roles(username):
'''
Get roles that the username is assigned from switch
.. code-block: bash
salt '*' onyx.cmd get_roles username=admin
'''
info = sendline('show user-account {0}'.format(username))
roles = re.search(r'^\s*roles:(.*)$', info, re.MULTILINE)
if roles:
roles = roles.group(1).strip().split(' ')
else:
roles = []
return roles
def check_role(username, role):
'''
Check if user is assigned a specific role on switch
.. code-block:: bash
salt '*' onyx.cmd check_role username=admin role=network-admin
'''
return role in get_roles(username)
def remove_user(username):
'''
Remove user from switch
.. code-block:: bash
salt '*' onyx.cmd remove_user username=daniel
'''
try:
sendline('config terminal')
user_line = 'no username {0}'.format(username)
ret = sendline(user_line)
sendline('end')
sendline('copy running-config startup-config')
return '\n'.join([user_line, ret])
except TerminalException as e:
log.error(e)
return 'Failed to set password'
def set_role(username, role):
'''
Assign role to username
.. code-block:: bash
salt '*' onyx.cmd set_role username=daniel role=vdc-admin
'''
try:
sendline('config terminal')
role_line = 'username {0} role {1}'.format(username, role)
ret = sendline(role_line)
sendline('end')
sendline('copy running-config startup-config')
return '\n'.join([role_line, ret])
except TerminalException as e:
log.error(e)
return 'Failed to set password'
def unset_role(username, role):
'''
Remove role from username
.. code-block:: bash
salt '*' onyx.cmd unset_role username=daniel role=vdc-admin
'''
try:
sendline('config terminal')
role_line = 'no username {0} role {1}'.format(username, role)
ret = sendline(role_line)
sendline('end')
sendline('copy running-config startup-config')
return '\n'.join([role_line, ret])
except TerminalException as e:
log.error(e)
return 'Failed to set password'
def show_run():
'''
Shortcut to run `show run` on switch
.. code-block:: bash
salt '*' onyx.cmd show_run
'''
try:
enable()
configure_terminal()
ret = sendline('show running-config')
configure_terminal_exit()
disable()
except TerminalException as e:
log.error(e)
return 'Failed to show running-config on switch'
return ret
def show_ver():
'''
Shortcut to run `show ver` on switch
.. code-block:: bash
salt '*' onyx.cmd show_ver
'''
try:
ret = sendline('show ver')
except TerminalException as e:
log.error(e)
return 'Failed to "show ver"'
return ret
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 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 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 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 _parser(block):
return re.compile('^{block}\n(?:^[ \n].*$\n?)+'.format(block=block), re.MULTILINE)
def _parse_software(data):
ret = {'software': {}}
software = _parser('Software').search(data).group(0)
matcher = re.compile('^ ([^:]+): *([^\n]+)', re.MULTILINE)
for line in matcher.finditer(software):
key, val = line.groups()
ret['software'][key] = val
return ret['software']
def _parse_hardware(data):
ret = {'hardware': {}}
hardware = _parser('Hardware').search(data).group(0)
matcher = re.compile('^ ([^:\n]+): *([^\n]+)', re.MULTILINE)
for line in matcher.finditer(hardware):
key, val = line.groups()
ret['hardware'][key] = val
return ret['hardware']
def _parse_plugins(data):
ret = {'plugins': []}
plugins = _parser('plugin').search(data).group(0)
matcher = re.compile('^ (?:([^,]+), )+([^\n]+)', re.MULTILINE)
for line in matcher.finditer(plugins):
ret['plugins'].extend(line.groups())
return ret['plugins']
def system_info():
'''
Return system information for grains of the NX OS proxy minion
.. code-block:: bash
salt '*' onyx.system_info
'''
# data = show_ver()
info = {
'software': 'Test',
'hardware': '',
'plugins': ''
}
return info
|
saltstack/salt
|
salt/proxy/onyx.py
|
ping
|
python
|
def ping():
'''
Ping the device on the other end of the connection
.. code-block: bash
salt '*' onyx.cmd ping
'''
if _worker_name() not in DETAILS:
init()
try:
return DETAILS[_worker_name()].conn.isalive()
except TerminalException as e:
log.error(e)
return False
|
Ping the device on the other end of the connection
.. code-block: bash
salt '*' onyx.cmd ping
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/onyx.py#L117-L131
|
[
"def init(opts=None):\n '''\n Required.\n Can be used to initialize the server connection.\n '''\n if opts is None:\n opts = __opts__\n try:\n DETAILS[_worker_name()] = SSHConnection(\n host=opts['proxy']['host'],\n username=opts['proxy']['username'],\n password=opts['proxy']['password'],\n key_accept=opts['proxy'].get('key_accept', False),\n ssh_args=opts['proxy'].get('ssh_args', ''),\n prompt='{0}.*(#|>) '.format(opts['proxy']['prompt_name']))\n DETAILS[_worker_name()].sendline('no cli session paging enable')\n\n except TerminalException as e:\n log.error(e)\n return False\n DETAILS['initialized'] = True\n",
"def _worker_name():\n return multiprocessing.current_process().name\n"
] |
# -*- coding: utf-8 -*-
'''
Proxy Minion for Onyx OS Switches
.. versionadded: Neon
The Onyx OS Proxy Minion uses the built in SSHConnection module
in :mod:`salt.utils.vt_helper <salt.utils.vt_helper>`
To configure the proxy minion:
.. code-block:: yaml
proxy:
proxytype: onyx
host: 192.168.187.100
username: admin
password: admin
prompt_name: switch
ssh_args: '-o PubkeyAuthentication=no'
key_accept: True
proxytype
(REQUIRED) Use this proxy minion `onyx`
host
(REQUIRED) ip address or hostname to connect to
username
(REQUIRED) username to login with
password
(REQUIRED) password to use to login with
prompt_name
(REQUIRED) The name in the prompt on the switch. By default, use your
devices hostname.
ssh_args
Any extra args to use to connect to the switch.
key_accept
Whether or not to accept a the host key of the switch on initial login.
Defaults to False.
The functions from the proxy minion can be run from the salt commandline using
the :mod:`salt.modules.onyx<salt.modules.onyx>` execution module.
.. note:
If `multiprocessing: True` is set for the proxy minion config, each forked
worker will open up a new connection to the Cisco NX OS Switch. If you
only want one consistent connection used for everything, use
`multiprocessing: False`
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import multiprocessing
import re
# Import Salt libs
from salt.utils.vt_helper import SSHConnection
from salt.utils.vt import TerminalException
log = logging.getLogger(__file__)
__proxyenabled__ = ['onyx']
__virtualname__ = 'onyx'
DETAILS = {'grains_cache': {}}
def __virtual__():
'''
Only return if all the modules are available
'''
log.info('onyx proxy __virtual__() called...')
return __virtualname__
def _worker_name():
return multiprocessing.current_process().name
def init(opts=None):
'''
Required.
Can be used to initialize the server connection.
'''
if opts is None:
opts = __opts__
try:
DETAILS[_worker_name()] = SSHConnection(
host=opts['proxy']['host'],
username=opts['proxy']['username'],
password=opts['proxy']['password'],
key_accept=opts['proxy'].get('key_accept', False),
ssh_args=opts['proxy'].get('ssh_args', ''),
prompt='{0}.*(#|>) '.format(opts['proxy']['prompt_name']))
DETAILS[_worker_name()].sendline('no cli session paging enable')
except TerminalException as e:
log.error(e)
return False
DETAILS['initialized'] = True
def initialized():
'''
module initialization
'''
return DETAILS.get('initialized', False)
def shutdown():
'''
Disconnect
'''
DETAILS[_worker_name()].close_connection()
def sendline(command):
'''
Run command through switch's cli
.. code-block: bash
salt '*' onyx.cmd sendline 'show run | include
"username admin password 7"'
'''
if ping() is False:
init()
out, _ = DETAILS[_worker_name()].sendline(command)
return out
def enable():
'''
Shortcut to run `enable` on switch
.. code-block:: bash
salt '*' onyx.cmd enable
'''
try:
ret = sendline('enable')
except TerminalException as e:
log.error(e)
return 'Failed to enable switch'
return ret
def configure_terminal():
'''
Shortcut to run `configure terminal` on switch
.. code-block:: bash
salt '*' onyx.cmd configure_terminal
'''
try:
ret = sendline('configure terminal ')
except TerminalException as e:
log.error(e)
return 'Failed to enable ' \
'configuration mode on switch'
return ret
def configure_terminal_exit():
'''
Shortcut to run `exit` from configuration mode on switch
.. code-block:: bash
salt '*' onyx.cmd configure_terminal_exit
'''
try:
ret = sendline('exit')
except TerminalException as e:
log.error(e)
return 'Failed to exit form configuration mode on switch'
return ret
def disable():
'''
Shortcut to run `disable` on switch
.. code-block:: bash
salt '*' onyx.cmd disable
'''
try:
ret = sendline('disable')
except TerminalException as e:
log.error(e)
return 'Failed to "configure terminal"'
return ret
def grains():
'''
Get grains for proxy minion
.. code-block: bash
salt '*' onyx.cmd grains
'''
if not DETAILS['grains_cache']:
ret = system_info()
log.debug(ret)
DETAILS['grains_cache'].update(ret)
return {'onyx': DETAILS['grains_cache']}
def grains_refresh():
'''
Refresh the grains from the proxy device.
.. code-block: bash
salt '*' onyx.cmd grains_refresh
'''
DETAILS['grains_cache'] = {}
return grains()
def get_user(username):
'''
Get username line from switch
.. code-block: bash
salt '*' onyx.cmd get_user username=admin
'''
try:
enable()
configure_terminal()
cmd_out = sendline('show running-config | include "username {0} password 7"'.format(username))
cmd_out.split('\n')
user = cmd_out[1:-1]
configure_terminal_exit()
disable()
return user
except TerminalException as e:
log.error(e)
return 'Failed to get user'
def get_roles(username):
'''
Get roles that the username is assigned from switch
.. code-block: bash
salt '*' onyx.cmd get_roles username=admin
'''
info = sendline('show user-account {0}'.format(username))
roles = re.search(r'^\s*roles:(.*)$', info, re.MULTILINE)
if roles:
roles = roles.group(1).strip().split(' ')
else:
roles = []
return roles
def check_role(username, role):
'''
Check if user is assigned a specific role on switch
.. code-block:: bash
salt '*' onyx.cmd check_role username=admin role=network-admin
'''
return role in get_roles(username)
def remove_user(username):
'''
Remove user from switch
.. code-block:: bash
salt '*' onyx.cmd remove_user username=daniel
'''
try:
sendline('config terminal')
user_line = 'no username {0}'.format(username)
ret = sendline(user_line)
sendline('end')
sendline('copy running-config startup-config')
return '\n'.join([user_line, ret])
except TerminalException as e:
log.error(e)
return 'Failed to set password'
def set_role(username, role):
'''
Assign role to username
.. code-block:: bash
salt '*' onyx.cmd set_role username=daniel role=vdc-admin
'''
try:
sendline('config terminal')
role_line = 'username {0} role {1}'.format(username, role)
ret = sendline(role_line)
sendline('end')
sendline('copy running-config startup-config')
return '\n'.join([role_line, ret])
except TerminalException as e:
log.error(e)
return 'Failed to set password'
def unset_role(username, role):
'''
Remove role from username
.. code-block:: bash
salt '*' onyx.cmd unset_role username=daniel role=vdc-admin
'''
try:
sendline('config terminal')
role_line = 'no username {0} role {1}'.format(username, role)
ret = sendline(role_line)
sendline('end')
sendline('copy running-config startup-config')
return '\n'.join([role_line, ret])
except TerminalException as e:
log.error(e)
return 'Failed to set password'
def show_run():
'''
Shortcut to run `show run` on switch
.. code-block:: bash
salt '*' onyx.cmd show_run
'''
try:
enable()
configure_terminal()
ret = sendline('show running-config')
configure_terminal_exit()
disable()
except TerminalException as e:
log.error(e)
return 'Failed to show running-config on switch'
return ret
def show_ver():
'''
Shortcut to run `show ver` on switch
.. code-block:: bash
salt '*' onyx.cmd show_ver
'''
try:
ret = sendline('show ver')
except TerminalException as e:
log.error(e)
return 'Failed to "show ver"'
return ret
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 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 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 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 _parser(block):
return re.compile('^{block}\n(?:^[ \n].*$\n?)+'.format(block=block), re.MULTILINE)
def _parse_software(data):
ret = {'software': {}}
software = _parser('Software').search(data).group(0)
matcher = re.compile('^ ([^:]+): *([^\n]+)', re.MULTILINE)
for line in matcher.finditer(software):
key, val = line.groups()
ret['software'][key] = val
return ret['software']
def _parse_hardware(data):
ret = {'hardware': {}}
hardware = _parser('Hardware').search(data).group(0)
matcher = re.compile('^ ([^:\n]+): *([^\n]+)', re.MULTILINE)
for line in matcher.finditer(hardware):
key, val = line.groups()
ret['hardware'][key] = val
return ret['hardware']
def _parse_plugins(data):
ret = {'plugins': []}
plugins = _parser('plugin').search(data).group(0)
matcher = re.compile('^ (?:([^,]+), )+([^\n]+)', re.MULTILINE)
for line in matcher.finditer(plugins):
ret['plugins'].extend(line.groups())
return ret['plugins']
def system_info():
'''
Return system information for grains of the NX OS proxy minion
.. code-block:: bash
salt '*' onyx.system_info
'''
# data = show_ver()
info = {
'software': 'Test',
'hardware': '',
'plugins': ''
}
return info
|
saltstack/salt
|
salt/proxy/onyx.py
|
sendline
|
python
|
def sendline(command):
'''
Run command through switch's cli
.. code-block: bash
salt '*' onyx.cmd sendline 'show run | include
"username admin password 7"'
'''
if ping() is False:
init()
out, _ = DETAILS[_worker_name()].sendline(command)
return out
|
Run command through switch's cli
.. code-block: bash
salt '*' onyx.cmd sendline 'show run | include
"username admin password 7"'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/onyx.py#L141-L153
|
[
"def init(opts=None):\n '''\n Required.\n Can be used to initialize the server connection.\n '''\n if opts is None:\n opts = __opts__\n try:\n DETAILS[_worker_name()] = SSHConnection(\n host=opts['proxy']['host'],\n username=opts['proxy']['username'],\n password=opts['proxy']['password'],\n key_accept=opts['proxy'].get('key_accept', False),\n ssh_args=opts['proxy'].get('ssh_args', ''),\n prompt='{0}.*(#|>) '.format(opts['proxy']['prompt_name']))\n DETAILS[_worker_name()].sendline('no cli session paging enable')\n\n except TerminalException as e:\n log.error(e)\n return False\n DETAILS['initialized'] = True\n",
"def ping():\n '''\n Ping the device on the other end of the connection\n\n .. code-block: bash\n\n salt '*' onyx.cmd ping\n '''\n if _worker_name() not in DETAILS:\n init()\n try:\n return DETAILS[_worker_name()].conn.isalive()\n except TerminalException as e:\n log.error(e)\n return False\n",
"def _worker_name():\n return multiprocessing.current_process().name\n"
] |
# -*- coding: utf-8 -*-
'''
Proxy Minion for Onyx OS Switches
.. versionadded: Neon
The Onyx OS Proxy Minion uses the built in SSHConnection module
in :mod:`salt.utils.vt_helper <salt.utils.vt_helper>`
To configure the proxy minion:
.. code-block:: yaml
proxy:
proxytype: onyx
host: 192.168.187.100
username: admin
password: admin
prompt_name: switch
ssh_args: '-o PubkeyAuthentication=no'
key_accept: True
proxytype
(REQUIRED) Use this proxy minion `onyx`
host
(REQUIRED) ip address or hostname to connect to
username
(REQUIRED) username to login with
password
(REQUIRED) password to use to login with
prompt_name
(REQUIRED) The name in the prompt on the switch. By default, use your
devices hostname.
ssh_args
Any extra args to use to connect to the switch.
key_accept
Whether or not to accept a the host key of the switch on initial login.
Defaults to False.
The functions from the proxy minion can be run from the salt commandline using
the :mod:`salt.modules.onyx<salt.modules.onyx>` execution module.
.. note:
If `multiprocessing: True` is set for the proxy minion config, each forked
worker will open up a new connection to the Cisco NX OS Switch. If you
only want one consistent connection used for everything, use
`multiprocessing: False`
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import multiprocessing
import re
# Import Salt libs
from salt.utils.vt_helper import SSHConnection
from salt.utils.vt import TerminalException
log = logging.getLogger(__file__)
__proxyenabled__ = ['onyx']
__virtualname__ = 'onyx'
DETAILS = {'grains_cache': {}}
def __virtual__():
'''
Only return if all the modules are available
'''
log.info('onyx proxy __virtual__() called...')
return __virtualname__
def _worker_name():
return multiprocessing.current_process().name
def init(opts=None):
'''
Required.
Can be used to initialize the server connection.
'''
if opts is None:
opts = __opts__
try:
DETAILS[_worker_name()] = SSHConnection(
host=opts['proxy']['host'],
username=opts['proxy']['username'],
password=opts['proxy']['password'],
key_accept=opts['proxy'].get('key_accept', False),
ssh_args=opts['proxy'].get('ssh_args', ''),
prompt='{0}.*(#|>) '.format(opts['proxy']['prompt_name']))
DETAILS[_worker_name()].sendline('no cli session paging enable')
except TerminalException as e:
log.error(e)
return False
DETAILS['initialized'] = True
def initialized():
'''
module initialization
'''
return DETAILS.get('initialized', False)
def ping():
'''
Ping the device on the other end of the connection
.. code-block: bash
salt '*' onyx.cmd ping
'''
if _worker_name() not in DETAILS:
init()
try:
return DETAILS[_worker_name()].conn.isalive()
except TerminalException as e:
log.error(e)
return False
def shutdown():
'''
Disconnect
'''
DETAILS[_worker_name()].close_connection()
def enable():
'''
Shortcut to run `enable` on switch
.. code-block:: bash
salt '*' onyx.cmd enable
'''
try:
ret = sendline('enable')
except TerminalException as e:
log.error(e)
return 'Failed to enable switch'
return ret
def configure_terminal():
'''
Shortcut to run `configure terminal` on switch
.. code-block:: bash
salt '*' onyx.cmd configure_terminal
'''
try:
ret = sendline('configure terminal ')
except TerminalException as e:
log.error(e)
return 'Failed to enable ' \
'configuration mode on switch'
return ret
def configure_terminal_exit():
'''
Shortcut to run `exit` from configuration mode on switch
.. code-block:: bash
salt '*' onyx.cmd configure_terminal_exit
'''
try:
ret = sendline('exit')
except TerminalException as e:
log.error(e)
return 'Failed to exit form configuration mode on switch'
return ret
def disable():
'''
Shortcut to run `disable` on switch
.. code-block:: bash
salt '*' onyx.cmd disable
'''
try:
ret = sendline('disable')
except TerminalException as e:
log.error(e)
return 'Failed to "configure terminal"'
return ret
def grains():
'''
Get grains for proxy minion
.. code-block: bash
salt '*' onyx.cmd grains
'''
if not DETAILS['grains_cache']:
ret = system_info()
log.debug(ret)
DETAILS['grains_cache'].update(ret)
return {'onyx': DETAILS['grains_cache']}
def grains_refresh():
'''
Refresh the grains from the proxy device.
.. code-block: bash
salt '*' onyx.cmd grains_refresh
'''
DETAILS['grains_cache'] = {}
return grains()
def get_user(username):
'''
Get username line from switch
.. code-block: bash
salt '*' onyx.cmd get_user username=admin
'''
try:
enable()
configure_terminal()
cmd_out = sendline('show running-config | include "username {0} password 7"'.format(username))
cmd_out.split('\n')
user = cmd_out[1:-1]
configure_terminal_exit()
disable()
return user
except TerminalException as e:
log.error(e)
return 'Failed to get user'
def get_roles(username):
'''
Get roles that the username is assigned from switch
.. code-block: bash
salt '*' onyx.cmd get_roles username=admin
'''
info = sendline('show user-account {0}'.format(username))
roles = re.search(r'^\s*roles:(.*)$', info, re.MULTILINE)
if roles:
roles = roles.group(1).strip().split(' ')
else:
roles = []
return roles
def check_role(username, role):
'''
Check if user is assigned a specific role on switch
.. code-block:: bash
salt '*' onyx.cmd check_role username=admin role=network-admin
'''
return role in get_roles(username)
def remove_user(username):
'''
Remove user from switch
.. code-block:: bash
salt '*' onyx.cmd remove_user username=daniel
'''
try:
sendline('config terminal')
user_line = 'no username {0}'.format(username)
ret = sendline(user_line)
sendline('end')
sendline('copy running-config startup-config')
return '\n'.join([user_line, ret])
except TerminalException as e:
log.error(e)
return 'Failed to set password'
def set_role(username, role):
'''
Assign role to username
.. code-block:: bash
salt '*' onyx.cmd set_role username=daniel role=vdc-admin
'''
try:
sendline('config terminal')
role_line = 'username {0} role {1}'.format(username, role)
ret = sendline(role_line)
sendline('end')
sendline('copy running-config startup-config')
return '\n'.join([role_line, ret])
except TerminalException as e:
log.error(e)
return 'Failed to set password'
def unset_role(username, role):
'''
Remove role from username
.. code-block:: bash
salt '*' onyx.cmd unset_role username=daniel role=vdc-admin
'''
try:
sendline('config terminal')
role_line = 'no username {0} role {1}'.format(username, role)
ret = sendline(role_line)
sendline('end')
sendline('copy running-config startup-config')
return '\n'.join([role_line, ret])
except TerminalException as e:
log.error(e)
return 'Failed to set password'
def show_run():
'''
Shortcut to run `show run` on switch
.. code-block:: bash
salt '*' onyx.cmd show_run
'''
try:
enable()
configure_terminal()
ret = sendline('show running-config')
configure_terminal_exit()
disable()
except TerminalException as e:
log.error(e)
return 'Failed to show running-config on switch'
return ret
def show_ver():
'''
Shortcut to run `show ver` on switch
.. code-block:: bash
salt '*' onyx.cmd show_ver
'''
try:
ret = sendline('show ver')
except TerminalException as e:
log.error(e)
return 'Failed to "show ver"'
return ret
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 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 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 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 _parser(block):
return re.compile('^{block}\n(?:^[ \n].*$\n?)+'.format(block=block), re.MULTILINE)
def _parse_software(data):
ret = {'software': {}}
software = _parser('Software').search(data).group(0)
matcher = re.compile('^ ([^:]+): *([^\n]+)', re.MULTILINE)
for line in matcher.finditer(software):
key, val = line.groups()
ret['software'][key] = val
return ret['software']
def _parse_hardware(data):
ret = {'hardware': {}}
hardware = _parser('Hardware').search(data).group(0)
matcher = re.compile('^ ([^:\n]+): *([^\n]+)', re.MULTILINE)
for line in matcher.finditer(hardware):
key, val = line.groups()
ret['hardware'][key] = val
return ret['hardware']
def _parse_plugins(data):
ret = {'plugins': []}
plugins = _parser('plugin').search(data).group(0)
matcher = re.compile('^ (?:([^,]+), )+([^\n]+)', re.MULTILINE)
for line in matcher.finditer(plugins):
ret['plugins'].extend(line.groups())
return ret['plugins']
def system_info():
'''
Return system information for grains of the NX OS proxy minion
.. code-block:: bash
salt '*' onyx.system_info
'''
# data = show_ver()
info = {
'software': 'Test',
'hardware': '',
'plugins': ''
}
return info
|
saltstack/salt
|
salt/proxy/onyx.py
|
grains
|
python
|
def grains():
'''
Get grains for proxy minion
.. code-block: bash
salt '*' onyx.cmd grains
'''
if not DETAILS['grains_cache']:
ret = system_info()
log.debug(ret)
DETAILS['grains_cache'].update(ret)
return {'onyx': DETAILS['grains_cache']}
|
Get grains for proxy minion
.. code-block: bash
salt '*' onyx.cmd grains
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/onyx.py#L221-L233
|
[
"def system_info():\n '''\n Return system information for grains of the NX OS proxy minion\n\n .. code-block:: bash\n\n salt '*' onyx.system_info\n '''\n # data = show_ver()\n info = {\n 'software': 'Test',\n 'hardware': '',\n 'plugins': ''\n }\n return info\n"
] |
# -*- coding: utf-8 -*-
'''
Proxy Minion for Onyx OS Switches
.. versionadded: Neon
The Onyx OS Proxy Minion uses the built in SSHConnection module
in :mod:`salt.utils.vt_helper <salt.utils.vt_helper>`
To configure the proxy minion:
.. code-block:: yaml
proxy:
proxytype: onyx
host: 192.168.187.100
username: admin
password: admin
prompt_name: switch
ssh_args: '-o PubkeyAuthentication=no'
key_accept: True
proxytype
(REQUIRED) Use this proxy minion `onyx`
host
(REQUIRED) ip address or hostname to connect to
username
(REQUIRED) username to login with
password
(REQUIRED) password to use to login with
prompt_name
(REQUIRED) The name in the prompt on the switch. By default, use your
devices hostname.
ssh_args
Any extra args to use to connect to the switch.
key_accept
Whether or not to accept a the host key of the switch on initial login.
Defaults to False.
The functions from the proxy minion can be run from the salt commandline using
the :mod:`salt.modules.onyx<salt.modules.onyx>` execution module.
.. note:
If `multiprocessing: True` is set for the proxy minion config, each forked
worker will open up a new connection to the Cisco NX OS Switch. If you
only want one consistent connection used for everything, use
`multiprocessing: False`
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import multiprocessing
import re
# Import Salt libs
from salt.utils.vt_helper import SSHConnection
from salt.utils.vt import TerminalException
log = logging.getLogger(__file__)
__proxyenabled__ = ['onyx']
__virtualname__ = 'onyx'
DETAILS = {'grains_cache': {}}
def __virtual__():
'''
Only return if all the modules are available
'''
log.info('onyx proxy __virtual__() called...')
return __virtualname__
def _worker_name():
return multiprocessing.current_process().name
def init(opts=None):
'''
Required.
Can be used to initialize the server connection.
'''
if opts is None:
opts = __opts__
try:
DETAILS[_worker_name()] = SSHConnection(
host=opts['proxy']['host'],
username=opts['proxy']['username'],
password=opts['proxy']['password'],
key_accept=opts['proxy'].get('key_accept', False),
ssh_args=opts['proxy'].get('ssh_args', ''),
prompt='{0}.*(#|>) '.format(opts['proxy']['prompt_name']))
DETAILS[_worker_name()].sendline('no cli session paging enable')
except TerminalException as e:
log.error(e)
return False
DETAILS['initialized'] = True
def initialized():
'''
module initialization
'''
return DETAILS.get('initialized', False)
def ping():
'''
Ping the device on the other end of the connection
.. code-block: bash
salt '*' onyx.cmd ping
'''
if _worker_name() not in DETAILS:
init()
try:
return DETAILS[_worker_name()].conn.isalive()
except TerminalException as e:
log.error(e)
return False
def shutdown():
'''
Disconnect
'''
DETAILS[_worker_name()].close_connection()
def sendline(command):
'''
Run command through switch's cli
.. code-block: bash
salt '*' onyx.cmd sendline 'show run | include
"username admin password 7"'
'''
if ping() is False:
init()
out, _ = DETAILS[_worker_name()].sendline(command)
return out
def enable():
'''
Shortcut to run `enable` on switch
.. code-block:: bash
salt '*' onyx.cmd enable
'''
try:
ret = sendline('enable')
except TerminalException as e:
log.error(e)
return 'Failed to enable switch'
return ret
def configure_terminal():
'''
Shortcut to run `configure terminal` on switch
.. code-block:: bash
salt '*' onyx.cmd configure_terminal
'''
try:
ret = sendline('configure terminal ')
except TerminalException as e:
log.error(e)
return 'Failed to enable ' \
'configuration mode on switch'
return ret
def configure_terminal_exit():
'''
Shortcut to run `exit` from configuration mode on switch
.. code-block:: bash
salt '*' onyx.cmd configure_terminal_exit
'''
try:
ret = sendline('exit')
except TerminalException as e:
log.error(e)
return 'Failed to exit form configuration mode on switch'
return ret
def disable():
'''
Shortcut to run `disable` on switch
.. code-block:: bash
salt '*' onyx.cmd disable
'''
try:
ret = sendline('disable')
except TerminalException as e:
log.error(e)
return 'Failed to "configure terminal"'
return ret
def grains_refresh():
'''
Refresh the grains from the proxy device.
.. code-block: bash
salt '*' onyx.cmd grains_refresh
'''
DETAILS['grains_cache'] = {}
return grains()
def get_user(username):
'''
Get username line from switch
.. code-block: bash
salt '*' onyx.cmd get_user username=admin
'''
try:
enable()
configure_terminal()
cmd_out = sendline('show running-config | include "username {0} password 7"'.format(username))
cmd_out.split('\n')
user = cmd_out[1:-1]
configure_terminal_exit()
disable()
return user
except TerminalException as e:
log.error(e)
return 'Failed to get user'
def get_roles(username):
'''
Get roles that the username is assigned from switch
.. code-block: bash
salt '*' onyx.cmd get_roles username=admin
'''
info = sendline('show user-account {0}'.format(username))
roles = re.search(r'^\s*roles:(.*)$', info, re.MULTILINE)
if roles:
roles = roles.group(1).strip().split(' ')
else:
roles = []
return roles
def check_role(username, role):
'''
Check if user is assigned a specific role on switch
.. code-block:: bash
salt '*' onyx.cmd check_role username=admin role=network-admin
'''
return role in get_roles(username)
def remove_user(username):
'''
Remove user from switch
.. code-block:: bash
salt '*' onyx.cmd remove_user username=daniel
'''
try:
sendline('config terminal')
user_line = 'no username {0}'.format(username)
ret = sendline(user_line)
sendline('end')
sendline('copy running-config startup-config')
return '\n'.join([user_line, ret])
except TerminalException as e:
log.error(e)
return 'Failed to set password'
def set_role(username, role):
'''
Assign role to username
.. code-block:: bash
salt '*' onyx.cmd set_role username=daniel role=vdc-admin
'''
try:
sendline('config terminal')
role_line = 'username {0} role {1}'.format(username, role)
ret = sendline(role_line)
sendline('end')
sendline('copy running-config startup-config')
return '\n'.join([role_line, ret])
except TerminalException as e:
log.error(e)
return 'Failed to set password'
def unset_role(username, role):
'''
Remove role from username
.. code-block:: bash
salt '*' onyx.cmd unset_role username=daniel role=vdc-admin
'''
try:
sendline('config terminal')
role_line = 'no username {0} role {1}'.format(username, role)
ret = sendline(role_line)
sendline('end')
sendline('copy running-config startup-config')
return '\n'.join([role_line, ret])
except TerminalException as e:
log.error(e)
return 'Failed to set password'
def show_run():
'''
Shortcut to run `show run` on switch
.. code-block:: bash
salt '*' onyx.cmd show_run
'''
try:
enable()
configure_terminal()
ret = sendline('show running-config')
configure_terminal_exit()
disable()
except TerminalException as e:
log.error(e)
return 'Failed to show running-config on switch'
return ret
def show_ver():
'''
Shortcut to run `show ver` on switch
.. code-block:: bash
salt '*' onyx.cmd show_ver
'''
try:
ret = sendline('show ver')
except TerminalException as e:
log.error(e)
return 'Failed to "show ver"'
return ret
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 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 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 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 _parser(block):
return re.compile('^{block}\n(?:^[ \n].*$\n?)+'.format(block=block), re.MULTILINE)
def _parse_software(data):
ret = {'software': {}}
software = _parser('Software').search(data).group(0)
matcher = re.compile('^ ([^:]+): *([^\n]+)', re.MULTILINE)
for line in matcher.finditer(software):
key, val = line.groups()
ret['software'][key] = val
return ret['software']
def _parse_hardware(data):
ret = {'hardware': {}}
hardware = _parser('Hardware').search(data).group(0)
matcher = re.compile('^ ([^:\n]+): *([^\n]+)', re.MULTILINE)
for line in matcher.finditer(hardware):
key, val = line.groups()
ret['hardware'][key] = val
return ret['hardware']
def _parse_plugins(data):
ret = {'plugins': []}
plugins = _parser('plugin').search(data).group(0)
matcher = re.compile('^ (?:([^,]+), )+([^\n]+)', re.MULTILINE)
for line in matcher.finditer(plugins):
ret['plugins'].extend(line.groups())
return ret['plugins']
def system_info():
'''
Return system information for grains of the NX OS proxy minion
.. code-block:: bash
salt '*' onyx.system_info
'''
# data = show_ver()
info = {
'software': 'Test',
'hardware': '',
'plugins': ''
}
return info
|
saltstack/salt
|
salt/proxy/onyx.py
|
get_user
|
python
|
def get_user(username):
'''
Get username line from switch
.. code-block: bash
salt '*' onyx.cmd get_user username=admin
'''
try:
enable()
configure_terminal()
cmd_out = sendline('show running-config | include "username {0} password 7"'.format(username))
cmd_out.split('\n')
user = cmd_out[1:-1]
configure_terminal_exit()
disable()
return user
except TerminalException as e:
log.error(e)
return 'Failed to get user'
|
Get username line from switch
.. code-block: bash
salt '*' onyx.cmd get_user username=admin
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/onyx.py#L248-L267
|
[
"def disable():\n '''\n Shortcut to run `disable` on switch\n\n .. code-block:: bash\n\n salt '*' onyx.cmd disable\n '''\n try:\n ret = sendline('disable')\n except TerminalException as e:\n log.error(e)\n return 'Failed to \"configure terminal\"'\n return ret\n",
"def enable():\n '''\n Shortcut to run `enable` on switch\n\n .. code-block:: bash\n\n salt '*' onyx.cmd enable\n '''\n try:\n ret = sendline('enable')\n except TerminalException as e:\n log.error(e)\n return 'Failed to enable switch'\n return ret\n",
"def sendline(command):\n '''\n Run command through switch's cli\n\n .. code-block: bash\n\n salt '*' onyx.cmd sendline 'show run | include\n \"username admin password 7\"'\n '''\n if ping() is False:\n init()\n out, _ = DETAILS[_worker_name()].sendline(command)\n return out\n",
"def configure_terminal():\n '''\n Shortcut to run `configure terminal` on switch\n\n .. code-block:: bash\n\n salt '*' onyx.cmd configure_terminal\n '''\n try:\n ret = sendline('configure terminal ')\n except TerminalException as e:\n log.error(e)\n return 'Failed to enable ' \\\n 'configuration mode on switch'\n return ret\n",
"def configure_terminal_exit():\n '''\n Shortcut to run `exit` from configuration mode on switch\n\n .. code-block:: bash\n\n salt '*' onyx.cmd configure_terminal_exit\n '''\n try:\n ret = sendline('exit')\n except TerminalException as e:\n log.error(e)\n return 'Failed to exit form configuration mode on switch'\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Proxy Minion for Onyx OS Switches
.. versionadded: Neon
The Onyx OS Proxy Minion uses the built in SSHConnection module
in :mod:`salt.utils.vt_helper <salt.utils.vt_helper>`
To configure the proxy minion:
.. code-block:: yaml
proxy:
proxytype: onyx
host: 192.168.187.100
username: admin
password: admin
prompt_name: switch
ssh_args: '-o PubkeyAuthentication=no'
key_accept: True
proxytype
(REQUIRED) Use this proxy minion `onyx`
host
(REQUIRED) ip address or hostname to connect to
username
(REQUIRED) username to login with
password
(REQUIRED) password to use to login with
prompt_name
(REQUIRED) The name in the prompt on the switch. By default, use your
devices hostname.
ssh_args
Any extra args to use to connect to the switch.
key_accept
Whether or not to accept a the host key of the switch on initial login.
Defaults to False.
The functions from the proxy minion can be run from the salt commandline using
the :mod:`salt.modules.onyx<salt.modules.onyx>` execution module.
.. note:
If `multiprocessing: True` is set for the proxy minion config, each forked
worker will open up a new connection to the Cisco NX OS Switch. If you
only want one consistent connection used for everything, use
`multiprocessing: False`
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import multiprocessing
import re
# Import Salt libs
from salt.utils.vt_helper import SSHConnection
from salt.utils.vt import TerminalException
log = logging.getLogger(__file__)
__proxyenabled__ = ['onyx']
__virtualname__ = 'onyx'
DETAILS = {'grains_cache': {}}
def __virtual__():
'''
Only return if all the modules are available
'''
log.info('onyx proxy __virtual__() called...')
return __virtualname__
def _worker_name():
return multiprocessing.current_process().name
def init(opts=None):
'''
Required.
Can be used to initialize the server connection.
'''
if opts is None:
opts = __opts__
try:
DETAILS[_worker_name()] = SSHConnection(
host=opts['proxy']['host'],
username=opts['proxy']['username'],
password=opts['proxy']['password'],
key_accept=opts['proxy'].get('key_accept', False),
ssh_args=opts['proxy'].get('ssh_args', ''),
prompt='{0}.*(#|>) '.format(opts['proxy']['prompt_name']))
DETAILS[_worker_name()].sendline('no cli session paging enable')
except TerminalException as e:
log.error(e)
return False
DETAILS['initialized'] = True
def initialized():
'''
module initialization
'''
return DETAILS.get('initialized', False)
def ping():
'''
Ping the device on the other end of the connection
.. code-block: bash
salt '*' onyx.cmd ping
'''
if _worker_name() not in DETAILS:
init()
try:
return DETAILS[_worker_name()].conn.isalive()
except TerminalException as e:
log.error(e)
return False
def shutdown():
'''
Disconnect
'''
DETAILS[_worker_name()].close_connection()
def sendline(command):
'''
Run command through switch's cli
.. code-block: bash
salt '*' onyx.cmd sendline 'show run | include
"username admin password 7"'
'''
if ping() is False:
init()
out, _ = DETAILS[_worker_name()].sendline(command)
return out
def enable():
'''
Shortcut to run `enable` on switch
.. code-block:: bash
salt '*' onyx.cmd enable
'''
try:
ret = sendline('enable')
except TerminalException as e:
log.error(e)
return 'Failed to enable switch'
return ret
def configure_terminal():
'''
Shortcut to run `configure terminal` on switch
.. code-block:: bash
salt '*' onyx.cmd configure_terminal
'''
try:
ret = sendline('configure terminal ')
except TerminalException as e:
log.error(e)
return 'Failed to enable ' \
'configuration mode on switch'
return ret
def configure_terminal_exit():
'''
Shortcut to run `exit` from configuration mode on switch
.. code-block:: bash
salt '*' onyx.cmd configure_terminal_exit
'''
try:
ret = sendline('exit')
except TerminalException as e:
log.error(e)
return 'Failed to exit form configuration mode on switch'
return ret
def disable():
'''
Shortcut to run `disable` on switch
.. code-block:: bash
salt '*' onyx.cmd disable
'''
try:
ret = sendline('disable')
except TerminalException as e:
log.error(e)
return 'Failed to "configure terminal"'
return ret
def grains():
'''
Get grains for proxy minion
.. code-block: bash
salt '*' onyx.cmd grains
'''
if not DETAILS['grains_cache']:
ret = system_info()
log.debug(ret)
DETAILS['grains_cache'].update(ret)
return {'onyx': DETAILS['grains_cache']}
def grains_refresh():
'''
Refresh the grains from the proxy device.
.. code-block: bash
salt '*' onyx.cmd grains_refresh
'''
DETAILS['grains_cache'] = {}
return grains()
def get_roles(username):
'''
Get roles that the username is assigned from switch
.. code-block: bash
salt '*' onyx.cmd get_roles username=admin
'''
info = sendline('show user-account {0}'.format(username))
roles = re.search(r'^\s*roles:(.*)$', info, re.MULTILINE)
if roles:
roles = roles.group(1).strip().split(' ')
else:
roles = []
return roles
def check_role(username, role):
'''
Check if user is assigned a specific role on switch
.. code-block:: bash
salt '*' onyx.cmd check_role username=admin role=network-admin
'''
return role in get_roles(username)
def remove_user(username):
'''
Remove user from switch
.. code-block:: bash
salt '*' onyx.cmd remove_user username=daniel
'''
try:
sendline('config terminal')
user_line = 'no username {0}'.format(username)
ret = sendline(user_line)
sendline('end')
sendline('copy running-config startup-config')
return '\n'.join([user_line, ret])
except TerminalException as e:
log.error(e)
return 'Failed to set password'
def set_role(username, role):
'''
Assign role to username
.. code-block:: bash
salt '*' onyx.cmd set_role username=daniel role=vdc-admin
'''
try:
sendline('config terminal')
role_line = 'username {0} role {1}'.format(username, role)
ret = sendline(role_line)
sendline('end')
sendline('copy running-config startup-config')
return '\n'.join([role_line, ret])
except TerminalException as e:
log.error(e)
return 'Failed to set password'
def unset_role(username, role):
'''
Remove role from username
.. code-block:: bash
salt '*' onyx.cmd unset_role username=daniel role=vdc-admin
'''
try:
sendline('config terminal')
role_line = 'no username {0} role {1}'.format(username, role)
ret = sendline(role_line)
sendline('end')
sendline('copy running-config startup-config')
return '\n'.join([role_line, ret])
except TerminalException as e:
log.error(e)
return 'Failed to set password'
def show_run():
'''
Shortcut to run `show run` on switch
.. code-block:: bash
salt '*' onyx.cmd show_run
'''
try:
enable()
configure_terminal()
ret = sendline('show running-config')
configure_terminal_exit()
disable()
except TerminalException as e:
log.error(e)
return 'Failed to show running-config on switch'
return ret
def show_ver():
'''
Shortcut to run `show ver` on switch
.. code-block:: bash
salt '*' onyx.cmd show_ver
'''
try:
ret = sendline('show ver')
except TerminalException as e:
log.error(e)
return 'Failed to "show ver"'
return ret
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 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 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 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 _parser(block):
return re.compile('^{block}\n(?:^[ \n].*$\n?)+'.format(block=block), re.MULTILINE)
def _parse_software(data):
ret = {'software': {}}
software = _parser('Software').search(data).group(0)
matcher = re.compile('^ ([^:]+): *([^\n]+)', re.MULTILINE)
for line in matcher.finditer(software):
key, val = line.groups()
ret['software'][key] = val
return ret['software']
def _parse_hardware(data):
ret = {'hardware': {}}
hardware = _parser('Hardware').search(data).group(0)
matcher = re.compile('^ ([^:\n]+): *([^\n]+)', re.MULTILINE)
for line in matcher.finditer(hardware):
key, val = line.groups()
ret['hardware'][key] = val
return ret['hardware']
def _parse_plugins(data):
ret = {'plugins': []}
plugins = _parser('plugin').search(data).group(0)
matcher = re.compile('^ (?:([^,]+), )+([^\n]+)', re.MULTILINE)
for line in matcher.finditer(plugins):
ret['plugins'].extend(line.groups())
return ret['plugins']
def system_info():
'''
Return system information for grains of the NX OS proxy minion
.. code-block:: bash
salt '*' onyx.system_info
'''
# data = show_ver()
info = {
'software': 'Test',
'hardware': '',
'plugins': ''
}
return info
|
saltstack/salt
|
salt/proxy/onyx.py
|
get_roles
|
python
|
def get_roles(username):
'''
Get roles that the username is assigned from switch
.. code-block: bash
salt '*' onyx.cmd get_roles username=admin
'''
info = sendline('show user-account {0}'.format(username))
roles = re.search(r'^\s*roles:(.*)$', info, re.MULTILINE)
if roles:
roles = roles.group(1).strip().split(' ')
else:
roles = []
return roles
|
Get roles that the username is assigned from switch
.. code-block: bash
salt '*' onyx.cmd get_roles username=admin
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/onyx.py#L270-L284
|
[
"def sendline(command):\n '''\n Run command through switch's cli\n\n .. code-block: bash\n\n salt '*' onyx.cmd sendline 'show run | include\n \"username admin password 7\"'\n '''\n if ping() is False:\n init()\n out, _ = DETAILS[_worker_name()].sendline(command)\n return out\n"
] |
# -*- coding: utf-8 -*-
'''
Proxy Minion for Onyx OS Switches
.. versionadded: Neon
The Onyx OS Proxy Minion uses the built in SSHConnection module
in :mod:`salt.utils.vt_helper <salt.utils.vt_helper>`
To configure the proxy minion:
.. code-block:: yaml
proxy:
proxytype: onyx
host: 192.168.187.100
username: admin
password: admin
prompt_name: switch
ssh_args: '-o PubkeyAuthentication=no'
key_accept: True
proxytype
(REQUIRED) Use this proxy minion `onyx`
host
(REQUIRED) ip address or hostname to connect to
username
(REQUIRED) username to login with
password
(REQUIRED) password to use to login with
prompt_name
(REQUIRED) The name in the prompt on the switch. By default, use your
devices hostname.
ssh_args
Any extra args to use to connect to the switch.
key_accept
Whether or not to accept a the host key of the switch on initial login.
Defaults to False.
The functions from the proxy minion can be run from the salt commandline using
the :mod:`salt.modules.onyx<salt.modules.onyx>` execution module.
.. note:
If `multiprocessing: True` is set for the proxy minion config, each forked
worker will open up a new connection to the Cisco NX OS Switch. If you
only want one consistent connection used for everything, use
`multiprocessing: False`
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import multiprocessing
import re
# Import Salt libs
from salt.utils.vt_helper import SSHConnection
from salt.utils.vt import TerminalException
log = logging.getLogger(__file__)
__proxyenabled__ = ['onyx']
__virtualname__ = 'onyx'
DETAILS = {'grains_cache': {}}
def __virtual__():
'''
Only return if all the modules are available
'''
log.info('onyx proxy __virtual__() called...')
return __virtualname__
def _worker_name():
return multiprocessing.current_process().name
def init(opts=None):
'''
Required.
Can be used to initialize the server connection.
'''
if opts is None:
opts = __opts__
try:
DETAILS[_worker_name()] = SSHConnection(
host=opts['proxy']['host'],
username=opts['proxy']['username'],
password=opts['proxy']['password'],
key_accept=opts['proxy'].get('key_accept', False),
ssh_args=opts['proxy'].get('ssh_args', ''),
prompt='{0}.*(#|>) '.format(opts['proxy']['prompt_name']))
DETAILS[_worker_name()].sendline('no cli session paging enable')
except TerminalException as e:
log.error(e)
return False
DETAILS['initialized'] = True
def initialized():
'''
module initialization
'''
return DETAILS.get('initialized', False)
def ping():
'''
Ping the device on the other end of the connection
.. code-block: bash
salt '*' onyx.cmd ping
'''
if _worker_name() not in DETAILS:
init()
try:
return DETAILS[_worker_name()].conn.isalive()
except TerminalException as e:
log.error(e)
return False
def shutdown():
'''
Disconnect
'''
DETAILS[_worker_name()].close_connection()
def sendline(command):
'''
Run command through switch's cli
.. code-block: bash
salt '*' onyx.cmd sendline 'show run | include
"username admin password 7"'
'''
if ping() is False:
init()
out, _ = DETAILS[_worker_name()].sendline(command)
return out
def enable():
'''
Shortcut to run `enable` on switch
.. code-block:: bash
salt '*' onyx.cmd enable
'''
try:
ret = sendline('enable')
except TerminalException as e:
log.error(e)
return 'Failed to enable switch'
return ret
def configure_terminal():
'''
Shortcut to run `configure terminal` on switch
.. code-block:: bash
salt '*' onyx.cmd configure_terminal
'''
try:
ret = sendline('configure terminal ')
except TerminalException as e:
log.error(e)
return 'Failed to enable ' \
'configuration mode on switch'
return ret
def configure_terminal_exit():
'''
Shortcut to run `exit` from configuration mode on switch
.. code-block:: bash
salt '*' onyx.cmd configure_terminal_exit
'''
try:
ret = sendline('exit')
except TerminalException as e:
log.error(e)
return 'Failed to exit form configuration mode on switch'
return ret
def disable():
'''
Shortcut to run `disable` on switch
.. code-block:: bash
salt '*' onyx.cmd disable
'''
try:
ret = sendline('disable')
except TerminalException as e:
log.error(e)
return 'Failed to "configure terminal"'
return ret
def grains():
'''
Get grains for proxy minion
.. code-block: bash
salt '*' onyx.cmd grains
'''
if not DETAILS['grains_cache']:
ret = system_info()
log.debug(ret)
DETAILS['grains_cache'].update(ret)
return {'onyx': DETAILS['grains_cache']}
def grains_refresh():
'''
Refresh the grains from the proxy device.
.. code-block: bash
salt '*' onyx.cmd grains_refresh
'''
DETAILS['grains_cache'] = {}
return grains()
def get_user(username):
'''
Get username line from switch
.. code-block: bash
salt '*' onyx.cmd get_user username=admin
'''
try:
enable()
configure_terminal()
cmd_out = sendline('show running-config | include "username {0} password 7"'.format(username))
cmd_out.split('\n')
user = cmd_out[1:-1]
configure_terminal_exit()
disable()
return user
except TerminalException as e:
log.error(e)
return 'Failed to get user'
def check_role(username, role):
'''
Check if user is assigned a specific role on switch
.. code-block:: bash
salt '*' onyx.cmd check_role username=admin role=network-admin
'''
return role in get_roles(username)
def remove_user(username):
'''
Remove user from switch
.. code-block:: bash
salt '*' onyx.cmd remove_user username=daniel
'''
try:
sendline('config terminal')
user_line = 'no username {0}'.format(username)
ret = sendline(user_line)
sendline('end')
sendline('copy running-config startup-config')
return '\n'.join([user_line, ret])
except TerminalException as e:
log.error(e)
return 'Failed to set password'
def set_role(username, role):
'''
Assign role to username
.. code-block:: bash
salt '*' onyx.cmd set_role username=daniel role=vdc-admin
'''
try:
sendline('config terminal')
role_line = 'username {0} role {1}'.format(username, role)
ret = sendline(role_line)
sendline('end')
sendline('copy running-config startup-config')
return '\n'.join([role_line, ret])
except TerminalException as e:
log.error(e)
return 'Failed to set password'
def unset_role(username, role):
'''
Remove role from username
.. code-block:: bash
salt '*' onyx.cmd unset_role username=daniel role=vdc-admin
'''
try:
sendline('config terminal')
role_line = 'no username {0} role {1}'.format(username, role)
ret = sendline(role_line)
sendline('end')
sendline('copy running-config startup-config')
return '\n'.join([role_line, ret])
except TerminalException as e:
log.error(e)
return 'Failed to set password'
def show_run():
'''
Shortcut to run `show run` on switch
.. code-block:: bash
salt '*' onyx.cmd show_run
'''
try:
enable()
configure_terminal()
ret = sendline('show running-config')
configure_terminal_exit()
disable()
except TerminalException as e:
log.error(e)
return 'Failed to show running-config on switch'
return ret
def show_ver():
'''
Shortcut to run `show ver` on switch
.. code-block:: bash
salt '*' onyx.cmd show_ver
'''
try:
ret = sendline('show ver')
except TerminalException as e:
log.error(e)
return 'Failed to "show ver"'
return ret
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 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 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 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 _parser(block):
return re.compile('^{block}\n(?:^[ \n].*$\n?)+'.format(block=block), re.MULTILINE)
def _parse_software(data):
ret = {'software': {}}
software = _parser('Software').search(data).group(0)
matcher = re.compile('^ ([^:]+): *([^\n]+)', re.MULTILINE)
for line in matcher.finditer(software):
key, val = line.groups()
ret['software'][key] = val
return ret['software']
def _parse_hardware(data):
ret = {'hardware': {}}
hardware = _parser('Hardware').search(data).group(0)
matcher = re.compile('^ ([^:\n]+): *([^\n]+)', re.MULTILINE)
for line in matcher.finditer(hardware):
key, val = line.groups()
ret['hardware'][key] = val
return ret['hardware']
def _parse_plugins(data):
ret = {'plugins': []}
plugins = _parser('plugin').search(data).group(0)
matcher = re.compile('^ (?:([^,]+), )+([^\n]+)', re.MULTILINE)
for line in matcher.finditer(plugins):
ret['plugins'].extend(line.groups())
return ret['plugins']
def system_info():
'''
Return system information for grains of the NX OS proxy minion
.. code-block:: bash
salt '*' onyx.system_info
'''
# data = show_ver()
info = {
'software': 'Test',
'hardware': '',
'plugins': ''
}
return info
|
saltstack/salt
|
salt/proxy/onyx.py
|
remove_user
|
python
|
def remove_user(username):
'''
Remove user from switch
.. code-block:: bash
salt '*' onyx.cmd remove_user username=daniel
'''
try:
sendline('config terminal')
user_line = 'no username {0}'.format(username)
ret = sendline(user_line)
sendline('end')
sendline('copy running-config startup-config')
return '\n'.join([user_line, ret])
except TerminalException as e:
log.error(e)
return 'Failed to set password'
|
Remove user from switch
.. code-block:: bash
salt '*' onyx.cmd remove_user username=daniel
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/onyx.py#L298-L315
|
[
"def sendline(command):\n '''\n Run command through switch's cli\n\n .. code-block: bash\n\n salt '*' onyx.cmd sendline 'show run | include\n \"username admin password 7\"'\n '''\n if ping() is False:\n init()\n out, _ = DETAILS[_worker_name()].sendline(command)\n return out\n"
] |
# -*- coding: utf-8 -*-
'''
Proxy Minion for Onyx OS Switches
.. versionadded: Neon
The Onyx OS Proxy Minion uses the built in SSHConnection module
in :mod:`salt.utils.vt_helper <salt.utils.vt_helper>`
To configure the proxy minion:
.. code-block:: yaml
proxy:
proxytype: onyx
host: 192.168.187.100
username: admin
password: admin
prompt_name: switch
ssh_args: '-o PubkeyAuthentication=no'
key_accept: True
proxytype
(REQUIRED) Use this proxy minion `onyx`
host
(REQUIRED) ip address or hostname to connect to
username
(REQUIRED) username to login with
password
(REQUIRED) password to use to login with
prompt_name
(REQUIRED) The name in the prompt on the switch. By default, use your
devices hostname.
ssh_args
Any extra args to use to connect to the switch.
key_accept
Whether or not to accept a the host key of the switch on initial login.
Defaults to False.
The functions from the proxy minion can be run from the salt commandline using
the :mod:`salt.modules.onyx<salt.modules.onyx>` execution module.
.. note:
If `multiprocessing: True` is set for the proxy minion config, each forked
worker will open up a new connection to the Cisco NX OS Switch. If you
only want one consistent connection used for everything, use
`multiprocessing: False`
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import multiprocessing
import re
# Import Salt libs
from salt.utils.vt_helper import SSHConnection
from salt.utils.vt import TerminalException
log = logging.getLogger(__file__)
__proxyenabled__ = ['onyx']
__virtualname__ = 'onyx'
DETAILS = {'grains_cache': {}}
def __virtual__():
'''
Only return if all the modules are available
'''
log.info('onyx proxy __virtual__() called...')
return __virtualname__
def _worker_name():
return multiprocessing.current_process().name
def init(opts=None):
'''
Required.
Can be used to initialize the server connection.
'''
if opts is None:
opts = __opts__
try:
DETAILS[_worker_name()] = SSHConnection(
host=opts['proxy']['host'],
username=opts['proxy']['username'],
password=opts['proxy']['password'],
key_accept=opts['proxy'].get('key_accept', False),
ssh_args=opts['proxy'].get('ssh_args', ''),
prompt='{0}.*(#|>) '.format(opts['proxy']['prompt_name']))
DETAILS[_worker_name()].sendline('no cli session paging enable')
except TerminalException as e:
log.error(e)
return False
DETAILS['initialized'] = True
def initialized():
'''
module initialization
'''
return DETAILS.get('initialized', False)
def ping():
'''
Ping the device on the other end of the connection
.. code-block: bash
salt '*' onyx.cmd ping
'''
if _worker_name() not in DETAILS:
init()
try:
return DETAILS[_worker_name()].conn.isalive()
except TerminalException as e:
log.error(e)
return False
def shutdown():
'''
Disconnect
'''
DETAILS[_worker_name()].close_connection()
def sendline(command):
'''
Run command through switch's cli
.. code-block: bash
salt '*' onyx.cmd sendline 'show run | include
"username admin password 7"'
'''
if ping() is False:
init()
out, _ = DETAILS[_worker_name()].sendline(command)
return out
def enable():
'''
Shortcut to run `enable` on switch
.. code-block:: bash
salt '*' onyx.cmd enable
'''
try:
ret = sendline('enable')
except TerminalException as e:
log.error(e)
return 'Failed to enable switch'
return ret
def configure_terminal():
'''
Shortcut to run `configure terminal` on switch
.. code-block:: bash
salt '*' onyx.cmd configure_terminal
'''
try:
ret = sendline('configure terminal ')
except TerminalException as e:
log.error(e)
return 'Failed to enable ' \
'configuration mode on switch'
return ret
def configure_terminal_exit():
'''
Shortcut to run `exit` from configuration mode on switch
.. code-block:: bash
salt '*' onyx.cmd configure_terminal_exit
'''
try:
ret = sendline('exit')
except TerminalException as e:
log.error(e)
return 'Failed to exit form configuration mode on switch'
return ret
def disable():
'''
Shortcut to run `disable` on switch
.. code-block:: bash
salt '*' onyx.cmd disable
'''
try:
ret = sendline('disable')
except TerminalException as e:
log.error(e)
return 'Failed to "configure terminal"'
return ret
def grains():
'''
Get grains for proxy minion
.. code-block: bash
salt '*' onyx.cmd grains
'''
if not DETAILS['grains_cache']:
ret = system_info()
log.debug(ret)
DETAILS['grains_cache'].update(ret)
return {'onyx': DETAILS['grains_cache']}
def grains_refresh():
'''
Refresh the grains from the proxy device.
.. code-block: bash
salt '*' onyx.cmd grains_refresh
'''
DETAILS['grains_cache'] = {}
return grains()
def get_user(username):
'''
Get username line from switch
.. code-block: bash
salt '*' onyx.cmd get_user username=admin
'''
try:
enable()
configure_terminal()
cmd_out = sendline('show running-config | include "username {0} password 7"'.format(username))
cmd_out.split('\n')
user = cmd_out[1:-1]
configure_terminal_exit()
disable()
return user
except TerminalException as e:
log.error(e)
return 'Failed to get user'
def get_roles(username):
'''
Get roles that the username is assigned from switch
.. code-block: bash
salt '*' onyx.cmd get_roles username=admin
'''
info = sendline('show user-account {0}'.format(username))
roles = re.search(r'^\s*roles:(.*)$', info, re.MULTILINE)
if roles:
roles = roles.group(1).strip().split(' ')
else:
roles = []
return roles
def check_role(username, role):
'''
Check if user is assigned a specific role on switch
.. code-block:: bash
salt '*' onyx.cmd check_role username=admin role=network-admin
'''
return role in get_roles(username)
def set_role(username, role):
'''
Assign role to username
.. code-block:: bash
salt '*' onyx.cmd set_role username=daniel role=vdc-admin
'''
try:
sendline('config terminal')
role_line = 'username {0} role {1}'.format(username, role)
ret = sendline(role_line)
sendline('end')
sendline('copy running-config startup-config')
return '\n'.join([role_line, ret])
except TerminalException as e:
log.error(e)
return 'Failed to set password'
def unset_role(username, role):
'''
Remove role from username
.. code-block:: bash
salt '*' onyx.cmd unset_role username=daniel role=vdc-admin
'''
try:
sendline('config terminal')
role_line = 'no username {0} role {1}'.format(username, role)
ret = sendline(role_line)
sendline('end')
sendline('copy running-config startup-config')
return '\n'.join([role_line, ret])
except TerminalException as e:
log.error(e)
return 'Failed to set password'
def show_run():
'''
Shortcut to run `show run` on switch
.. code-block:: bash
salt '*' onyx.cmd show_run
'''
try:
enable()
configure_terminal()
ret = sendline('show running-config')
configure_terminal_exit()
disable()
except TerminalException as e:
log.error(e)
return 'Failed to show running-config on switch'
return ret
def show_ver():
'''
Shortcut to run `show ver` on switch
.. code-block:: bash
salt '*' onyx.cmd show_ver
'''
try:
ret = sendline('show ver')
except TerminalException as e:
log.error(e)
return 'Failed to "show ver"'
return ret
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 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 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 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 _parser(block):
return re.compile('^{block}\n(?:^[ \n].*$\n?)+'.format(block=block), re.MULTILINE)
def _parse_software(data):
ret = {'software': {}}
software = _parser('Software').search(data).group(0)
matcher = re.compile('^ ([^:]+): *([^\n]+)', re.MULTILINE)
for line in matcher.finditer(software):
key, val = line.groups()
ret['software'][key] = val
return ret['software']
def _parse_hardware(data):
ret = {'hardware': {}}
hardware = _parser('Hardware').search(data).group(0)
matcher = re.compile('^ ([^:\n]+): *([^\n]+)', re.MULTILINE)
for line in matcher.finditer(hardware):
key, val = line.groups()
ret['hardware'][key] = val
return ret['hardware']
def _parse_plugins(data):
ret = {'plugins': []}
plugins = _parser('plugin').search(data).group(0)
matcher = re.compile('^ (?:([^,]+), )+([^\n]+)', re.MULTILINE)
for line in matcher.finditer(plugins):
ret['plugins'].extend(line.groups())
return ret['plugins']
def system_info():
'''
Return system information for grains of the NX OS proxy minion
.. code-block:: bash
salt '*' onyx.system_info
'''
# data = show_ver()
info = {
'software': 'Test',
'hardware': '',
'plugins': ''
}
return info
|
saltstack/salt
|
salt/proxy/onyx.py
|
set_role
|
python
|
def set_role(username, role):
'''
Assign role to username
.. code-block:: bash
salt '*' onyx.cmd set_role username=daniel role=vdc-admin
'''
try:
sendline('config terminal')
role_line = 'username {0} role {1}'.format(username, role)
ret = sendline(role_line)
sendline('end')
sendline('copy running-config startup-config')
return '\n'.join([role_line, ret])
except TerminalException as e:
log.error(e)
return 'Failed to set password'
|
Assign role to username
.. code-block:: bash
salt '*' onyx.cmd set_role username=daniel role=vdc-admin
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/onyx.py#L318-L335
|
[
"def sendline(command):\n '''\n Run command through switch's cli\n\n .. code-block: bash\n\n salt '*' onyx.cmd sendline 'show run | include\n \"username admin password 7\"'\n '''\n if ping() is False:\n init()\n out, _ = DETAILS[_worker_name()].sendline(command)\n return out\n"
] |
# -*- coding: utf-8 -*-
'''
Proxy Minion for Onyx OS Switches
.. versionadded: Neon
The Onyx OS Proxy Minion uses the built in SSHConnection module
in :mod:`salt.utils.vt_helper <salt.utils.vt_helper>`
To configure the proxy minion:
.. code-block:: yaml
proxy:
proxytype: onyx
host: 192.168.187.100
username: admin
password: admin
prompt_name: switch
ssh_args: '-o PubkeyAuthentication=no'
key_accept: True
proxytype
(REQUIRED) Use this proxy minion `onyx`
host
(REQUIRED) ip address or hostname to connect to
username
(REQUIRED) username to login with
password
(REQUIRED) password to use to login with
prompt_name
(REQUIRED) The name in the prompt on the switch. By default, use your
devices hostname.
ssh_args
Any extra args to use to connect to the switch.
key_accept
Whether or not to accept a the host key of the switch on initial login.
Defaults to False.
The functions from the proxy minion can be run from the salt commandline using
the :mod:`salt.modules.onyx<salt.modules.onyx>` execution module.
.. note:
If `multiprocessing: True` is set for the proxy minion config, each forked
worker will open up a new connection to the Cisco NX OS Switch. If you
only want one consistent connection used for everything, use
`multiprocessing: False`
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import multiprocessing
import re
# Import Salt libs
from salt.utils.vt_helper import SSHConnection
from salt.utils.vt import TerminalException
log = logging.getLogger(__file__)
__proxyenabled__ = ['onyx']
__virtualname__ = 'onyx'
DETAILS = {'grains_cache': {}}
def __virtual__():
'''
Only return if all the modules are available
'''
log.info('onyx proxy __virtual__() called...')
return __virtualname__
def _worker_name():
return multiprocessing.current_process().name
def init(opts=None):
'''
Required.
Can be used to initialize the server connection.
'''
if opts is None:
opts = __opts__
try:
DETAILS[_worker_name()] = SSHConnection(
host=opts['proxy']['host'],
username=opts['proxy']['username'],
password=opts['proxy']['password'],
key_accept=opts['proxy'].get('key_accept', False),
ssh_args=opts['proxy'].get('ssh_args', ''),
prompt='{0}.*(#|>) '.format(opts['proxy']['prompt_name']))
DETAILS[_worker_name()].sendline('no cli session paging enable')
except TerminalException as e:
log.error(e)
return False
DETAILS['initialized'] = True
def initialized():
'''
module initialization
'''
return DETAILS.get('initialized', False)
def ping():
'''
Ping the device on the other end of the connection
.. code-block: bash
salt '*' onyx.cmd ping
'''
if _worker_name() not in DETAILS:
init()
try:
return DETAILS[_worker_name()].conn.isalive()
except TerminalException as e:
log.error(e)
return False
def shutdown():
'''
Disconnect
'''
DETAILS[_worker_name()].close_connection()
def sendline(command):
'''
Run command through switch's cli
.. code-block: bash
salt '*' onyx.cmd sendline 'show run | include
"username admin password 7"'
'''
if ping() is False:
init()
out, _ = DETAILS[_worker_name()].sendline(command)
return out
def enable():
'''
Shortcut to run `enable` on switch
.. code-block:: bash
salt '*' onyx.cmd enable
'''
try:
ret = sendline('enable')
except TerminalException as e:
log.error(e)
return 'Failed to enable switch'
return ret
def configure_terminal():
'''
Shortcut to run `configure terminal` on switch
.. code-block:: bash
salt '*' onyx.cmd configure_terminal
'''
try:
ret = sendline('configure terminal ')
except TerminalException as e:
log.error(e)
return 'Failed to enable ' \
'configuration mode on switch'
return ret
def configure_terminal_exit():
'''
Shortcut to run `exit` from configuration mode on switch
.. code-block:: bash
salt '*' onyx.cmd configure_terminal_exit
'''
try:
ret = sendline('exit')
except TerminalException as e:
log.error(e)
return 'Failed to exit form configuration mode on switch'
return ret
def disable():
'''
Shortcut to run `disable` on switch
.. code-block:: bash
salt '*' onyx.cmd disable
'''
try:
ret = sendline('disable')
except TerminalException as e:
log.error(e)
return 'Failed to "configure terminal"'
return ret
def grains():
'''
Get grains for proxy minion
.. code-block: bash
salt '*' onyx.cmd grains
'''
if not DETAILS['grains_cache']:
ret = system_info()
log.debug(ret)
DETAILS['grains_cache'].update(ret)
return {'onyx': DETAILS['grains_cache']}
def grains_refresh():
'''
Refresh the grains from the proxy device.
.. code-block: bash
salt '*' onyx.cmd grains_refresh
'''
DETAILS['grains_cache'] = {}
return grains()
def get_user(username):
'''
Get username line from switch
.. code-block: bash
salt '*' onyx.cmd get_user username=admin
'''
try:
enable()
configure_terminal()
cmd_out = sendline('show running-config | include "username {0} password 7"'.format(username))
cmd_out.split('\n')
user = cmd_out[1:-1]
configure_terminal_exit()
disable()
return user
except TerminalException as e:
log.error(e)
return 'Failed to get user'
def get_roles(username):
'''
Get roles that the username is assigned from switch
.. code-block: bash
salt '*' onyx.cmd get_roles username=admin
'''
info = sendline('show user-account {0}'.format(username))
roles = re.search(r'^\s*roles:(.*)$', info, re.MULTILINE)
if roles:
roles = roles.group(1).strip().split(' ')
else:
roles = []
return roles
def check_role(username, role):
'''
Check if user is assigned a specific role on switch
.. code-block:: bash
salt '*' onyx.cmd check_role username=admin role=network-admin
'''
return role in get_roles(username)
def remove_user(username):
'''
Remove user from switch
.. code-block:: bash
salt '*' onyx.cmd remove_user username=daniel
'''
try:
sendline('config terminal')
user_line = 'no username {0}'.format(username)
ret = sendline(user_line)
sendline('end')
sendline('copy running-config startup-config')
return '\n'.join([user_line, ret])
except TerminalException as e:
log.error(e)
return 'Failed to set password'
def unset_role(username, role):
'''
Remove role from username
.. code-block:: bash
salt '*' onyx.cmd unset_role username=daniel role=vdc-admin
'''
try:
sendline('config terminal')
role_line = 'no username {0} role {1}'.format(username, role)
ret = sendline(role_line)
sendline('end')
sendline('copy running-config startup-config')
return '\n'.join([role_line, ret])
except TerminalException as e:
log.error(e)
return 'Failed to set password'
def show_run():
'''
Shortcut to run `show run` on switch
.. code-block:: bash
salt '*' onyx.cmd show_run
'''
try:
enable()
configure_terminal()
ret = sendline('show running-config')
configure_terminal_exit()
disable()
except TerminalException as e:
log.error(e)
return 'Failed to show running-config on switch'
return ret
def show_ver():
'''
Shortcut to run `show ver` on switch
.. code-block:: bash
salt '*' onyx.cmd show_ver
'''
try:
ret = sendline('show ver')
except TerminalException as e:
log.error(e)
return 'Failed to "show ver"'
return ret
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 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 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 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 _parser(block):
return re.compile('^{block}\n(?:^[ \n].*$\n?)+'.format(block=block), re.MULTILINE)
def _parse_software(data):
ret = {'software': {}}
software = _parser('Software').search(data).group(0)
matcher = re.compile('^ ([^:]+): *([^\n]+)', re.MULTILINE)
for line in matcher.finditer(software):
key, val = line.groups()
ret['software'][key] = val
return ret['software']
def _parse_hardware(data):
ret = {'hardware': {}}
hardware = _parser('Hardware').search(data).group(0)
matcher = re.compile('^ ([^:\n]+): *([^\n]+)', re.MULTILINE)
for line in matcher.finditer(hardware):
key, val = line.groups()
ret['hardware'][key] = val
return ret['hardware']
def _parse_plugins(data):
ret = {'plugins': []}
plugins = _parser('plugin').search(data).group(0)
matcher = re.compile('^ (?:([^,]+), )+([^\n]+)', re.MULTILINE)
for line in matcher.finditer(plugins):
ret['plugins'].extend(line.groups())
return ret['plugins']
def system_info():
'''
Return system information for grains of the NX OS proxy minion
.. code-block:: bash
salt '*' onyx.system_info
'''
# data = show_ver()
info = {
'software': 'Test',
'hardware': '',
'plugins': ''
}
return info
|
saltstack/salt
|
salt/proxy/onyx.py
|
show_run
|
python
|
def show_run():
'''
Shortcut to run `show run` on switch
.. code-block:: bash
salt '*' onyx.cmd show_run
'''
try:
enable()
configure_terminal()
ret = sendline('show running-config')
configure_terminal_exit()
disable()
except TerminalException as e:
log.error(e)
return 'Failed to show running-config on switch'
return ret
|
Shortcut to run `show run` on switch
.. code-block:: bash
salt '*' onyx.cmd show_run
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/onyx.py#L358-L375
|
[
"def disable():\n '''\n Shortcut to run `disable` on switch\n\n .. code-block:: bash\n\n salt '*' onyx.cmd disable\n '''\n try:\n ret = sendline('disable')\n except TerminalException as e:\n log.error(e)\n return 'Failed to \"configure terminal\"'\n return ret\n",
"def enable():\n '''\n Shortcut to run `enable` on switch\n\n .. code-block:: bash\n\n salt '*' onyx.cmd enable\n '''\n try:\n ret = sendline('enable')\n except TerminalException as e:\n log.error(e)\n return 'Failed to enable switch'\n return ret\n",
"def sendline(command):\n '''\n Run command through switch's cli\n\n .. code-block: bash\n\n salt '*' onyx.cmd sendline 'show run | include\n \"username admin password 7\"'\n '''\n if ping() is False:\n init()\n out, _ = DETAILS[_worker_name()].sendline(command)\n return out\n",
"def configure_terminal():\n '''\n Shortcut to run `configure terminal` on switch\n\n .. code-block:: bash\n\n salt '*' onyx.cmd configure_terminal\n '''\n try:\n ret = sendline('configure terminal ')\n except TerminalException as e:\n log.error(e)\n return 'Failed to enable ' \\\n 'configuration mode on switch'\n return ret\n",
"def configure_terminal_exit():\n '''\n Shortcut to run `exit` from configuration mode on switch\n\n .. code-block:: bash\n\n salt '*' onyx.cmd configure_terminal_exit\n '''\n try:\n ret = sendline('exit')\n except TerminalException as e:\n log.error(e)\n return 'Failed to exit form configuration mode on switch'\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Proxy Minion for Onyx OS Switches
.. versionadded: Neon
The Onyx OS Proxy Minion uses the built in SSHConnection module
in :mod:`salt.utils.vt_helper <salt.utils.vt_helper>`
To configure the proxy minion:
.. code-block:: yaml
proxy:
proxytype: onyx
host: 192.168.187.100
username: admin
password: admin
prompt_name: switch
ssh_args: '-o PubkeyAuthentication=no'
key_accept: True
proxytype
(REQUIRED) Use this proxy minion `onyx`
host
(REQUIRED) ip address or hostname to connect to
username
(REQUIRED) username to login with
password
(REQUIRED) password to use to login with
prompt_name
(REQUIRED) The name in the prompt on the switch. By default, use your
devices hostname.
ssh_args
Any extra args to use to connect to the switch.
key_accept
Whether or not to accept a the host key of the switch on initial login.
Defaults to False.
The functions from the proxy minion can be run from the salt commandline using
the :mod:`salt.modules.onyx<salt.modules.onyx>` execution module.
.. note:
If `multiprocessing: True` is set for the proxy minion config, each forked
worker will open up a new connection to the Cisco NX OS Switch. If you
only want one consistent connection used for everything, use
`multiprocessing: False`
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import multiprocessing
import re
# Import Salt libs
from salt.utils.vt_helper import SSHConnection
from salt.utils.vt import TerminalException
log = logging.getLogger(__file__)
__proxyenabled__ = ['onyx']
__virtualname__ = 'onyx'
DETAILS = {'grains_cache': {}}
def __virtual__():
'''
Only return if all the modules are available
'''
log.info('onyx proxy __virtual__() called...')
return __virtualname__
def _worker_name():
return multiprocessing.current_process().name
def init(opts=None):
'''
Required.
Can be used to initialize the server connection.
'''
if opts is None:
opts = __opts__
try:
DETAILS[_worker_name()] = SSHConnection(
host=opts['proxy']['host'],
username=opts['proxy']['username'],
password=opts['proxy']['password'],
key_accept=opts['proxy'].get('key_accept', False),
ssh_args=opts['proxy'].get('ssh_args', ''),
prompt='{0}.*(#|>) '.format(opts['proxy']['prompt_name']))
DETAILS[_worker_name()].sendline('no cli session paging enable')
except TerminalException as e:
log.error(e)
return False
DETAILS['initialized'] = True
def initialized():
'''
module initialization
'''
return DETAILS.get('initialized', False)
def ping():
'''
Ping the device on the other end of the connection
.. code-block: bash
salt '*' onyx.cmd ping
'''
if _worker_name() not in DETAILS:
init()
try:
return DETAILS[_worker_name()].conn.isalive()
except TerminalException as e:
log.error(e)
return False
def shutdown():
'''
Disconnect
'''
DETAILS[_worker_name()].close_connection()
def sendline(command):
'''
Run command through switch's cli
.. code-block: bash
salt '*' onyx.cmd sendline 'show run | include
"username admin password 7"'
'''
if ping() is False:
init()
out, _ = DETAILS[_worker_name()].sendline(command)
return out
def enable():
'''
Shortcut to run `enable` on switch
.. code-block:: bash
salt '*' onyx.cmd enable
'''
try:
ret = sendline('enable')
except TerminalException as e:
log.error(e)
return 'Failed to enable switch'
return ret
def configure_terminal():
'''
Shortcut to run `configure terminal` on switch
.. code-block:: bash
salt '*' onyx.cmd configure_terminal
'''
try:
ret = sendline('configure terminal ')
except TerminalException as e:
log.error(e)
return 'Failed to enable ' \
'configuration mode on switch'
return ret
def configure_terminal_exit():
'''
Shortcut to run `exit` from configuration mode on switch
.. code-block:: bash
salt '*' onyx.cmd configure_terminal_exit
'''
try:
ret = sendline('exit')
except TerminalException as e:
log.error(e)
return 'Failed to exit form configuration mode on switch'
return ret
def disable():
'''
Shortcut to run `disable` on switch
.. code-block:: bash
salt '*' onyx.cmd disable
'''
try:
ret = sendline('disable')
except TerminalException as e:
log.error(e)
return 'Failed to "configure terminal"'
return ret
def grains():
'''
Get grains for proxy minion
.. code-block: bash
salt '*' onyx.cmd grains
'''
if not DETAILS['grains_cache']:
ret = system_info()
log.debug(ret)
DETAILS['grains_cache'].update(ret)
return {'onyx': DETAILS['grains_cache']}
def grains_refresh():
'''
Refresh the grains from the proxy device.
.. code-block: bash
salt '*' onyx.cmd grains_refresh
'''
DETAILS['grains_cache'] = {}
return grains()
def get_user(username):
'''
Get username line from switch
.. code-block: bash
salt '*' onyx.cmd get_user username=admin
'''
try:
enable()
configure_terminal()
cmd_out = sendline('show running-config | include "username {0} password 7"'.format(username))
cmd_out.split('\n')
user = cmd_out[1:-1]
configure_terminal_exit()
disable()
return user
except TerminalException as e:
log.error(e)
return 'Failed to get user'
def get_roles(username):
'''
Get roles that the username is assigned from switch
.. code-block: bash
salt '*' onyx.cmd get_roles username=admin
'''
info = sendline('show user-account {0}'.format(username))
roles = re.search(r'^\s*roles:(.*)$', info, re.MULTILINE)
if roles:
roles = roles.group(1).strip().split(' ')
else:
roles = []
return roles
def check_role(username, role):
'''
Check if user is assigned a specific role on switch
.. code-block:: bash
salt '*' onyx.cmd check_role username=admin role=network-admin
'''
return role in get_roles(username)
def remove_user(username):
'''
Remove user from switch
.. code-block:: bash
salt '*' onyx.cmd remove_user username=daniel
'''
try:
sendline('config terminal')
user_line = 'no username {0}'.format(username)
ret = sendline(user_line)
sendline('end')
sendline('copy running-config startup-config')
return '\n'.join([user_line, ret])
except TerminalException as e:
log.error(e)
return 'Failed to set password'
def set_role(username, role):
'''
Assign role to username
.. code-block:: bash
salt '*' onyx.cmd set_role username=daniel role=vdc-admin
'''
try:
sendline('config terminal')
role_line = 'username {0} role {1}'.format(username, role)
ret = sendline(role_line)
sendline('end')
sendline('copy running-config startup-config')
return '\n'.join([role_line, ret])
except TerminalException as e:
log.error(e)
return 'Failed to set password'
def unset_role(username, role):
'''
Remove role from username
.. code-block:: bash
salt '*' onyx.cmd unset_role username=daniel role=vdc-admin
'''
try:
sendline('config terminal')
role_line = 'no username {0} role {1}'.format(username, role)
ret = sendline(role_line)
sendline('end')
sendline('copy running-config startup-config')
return '\n'.join([role_line, ret])
except TerminalException as e:
log.error(e)
return 'Failed to set password'
def show_ver():
'''
Shortcut to run `show ver` on switch
.. code-block:: bash
salt '*' onyx.cmd show_ver
'''
try:
ret = sendline('show ver')
except TerminalException as e:
log.error(e)
return 'Failed to "show ver"'
return ret
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 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 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 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 _parser(block):
return re.compile('^{block}\n(?:^[ \n].*$\n?)+'.format(block=block), re.MULTILINE)
def _parse_software(data):
ret = {'software': {}}
software = _parser('Software').search(data).group(0)
matcher = re.compile('^ ([^:]+): *([^\n]+)', re.MULTILINE)
for line in matcher.finditer(software):
key, val = line.groups()
ret['software'][key] = val
return ret['software']
def _parse_hardware(data):
ret = {'hardware': {}}
hardware = _parser('Hardware').search(data).group(0)
matcher = re.compile('^ ([^:\n]+): *([^\n]+)', re.MULTILINE)
for line in matcher.finditer(hardware):
key, val = line.groups()
ret['hardware'][key] = val
return ret['hardware']
def _parse_plugins(data):
ret = {'plugins': []}
plugins = _parser('plugin').search(data).group(0)
matcher = re.compile('^ (?:([^,]+), )+([^\n]+)', re.MULTILINE)
for line in matcher.finditer(plugins):
ret['plugins'].extend(line.groups())
return ret['plugins']
def system_info():
'''
Return system information for grains of the NX OS proxy minion
.. code-block:: bash
salt '*' onyx.system_info
'''
# data = show_ver()
info = {
'software': 'Test',
'hardware': '',
'plugins': ''
}
return info
|
saltstack/salt
|
salt/proxy/onyx.py
|
add_config
|
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
|
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.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/onyx.py#L394-L418
|
[
"def disable():\n '''\n Shortcut to run `disable` on switch\n\n .. code-block:: bash\n\n salt '*' onyx.cmd disable\n '''\n try:\n ret = sendline('disable')\n except TerminalException as e:\n log.error(e)\n return 'Failed to \"configure terminal\"'\n return ret\n",
"def enable():\n '''\n Shortcut to run `enable` on switch\n\n .. code-block:: bash\n\n salt '*' onyx.cmd enable\n '''\n try:\n ret = sendline('enable')\n except TerminalException as e:\n log.error(e)\n return 'Failed to enable switch'\n return ret\n",
"def sendline(command):\n '''\n Run command through switch's cli\n\n .. code-block: bash\n\n salt '*' onyx.cmd sendline 'show run | include\n \"username admin password 7\"'\n '''\n if ping() is False:\n init()\n out, _ = DETAILS[_worker_name()].sendline(command)\n return out\n",
"def configure_terminal():\n '''\n Shortcut to run `configure terminal` on switch\n\n .. code-block:: bash\n\n salt '*' onyx.cmd configure_terminal\n '''\n try:\n ret = sendline('configure terminal ')\n except TerminalException as e:\n log.error(e)\n return 'Failed to enable ' \\\n 'configuration mode on switch'\n return ret\n",
"def configure_terminal_exit():\n '''\n Shortcut to run `exit` from configuration mode on switch\n\n .. code-block:: bash\n\n salt '*' onyx.cmd configure_terminal_exit\n '''\n try:\n ret = sendline('exit')\n except TerminalException as e:\n log.error(e)\n return 'Failed to exit form configuration mode on switch'\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Proxy Minion for Onyx OS Switches
.. versionadded: Neon
The Onyx OS Proxy Minion uses the built in SSHConnection module
in :mod:`salt.utils.vt_helper <salt.utils.vt_helper>`
To configure the proxy minion:
.. code-block:: yaml
proxy:
proxytype: onyx
host: 192.168.187.100
username: admin
password: admin
prompt_name: switch
ssh_args: '-o PubkeyAuthentication=no'
key_accept: True
proxytype
(REQUIRED) Use this proxy minion `onyx`
host
(REQUIRED) ip address or hostname to connect to
username
(REQUIRED) username to login with
password
(REQUIRED) password to use to login with
prompt_name
(REQUIRED) The name in the prompt on the switch. By default, use your
devices hostname.
ssh_args
Any extra args to use to connect to the switch.
key_accept
Whether or not to accept a the host key of the switch on initial login.
Defaults to False.
The functions from the proxy minion can be run from the salt commandline using
the :mod:`salt.modules.onyx<salt.modules.onyx>` execution module.
.. note:
If `multiprocessing: True` is set for the proxy minion config, each forked
worker will open up a new connection to the Cisco NX OS Switch. If you
only want one consistent connection used for everything, use
`multiprocessing: False`
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import multiprocessing
import re
# Import Salt libs
from salt.utils.vt_helper import SSHConnection
from salt.utils.vt import TerminalException
log = logging.getLogger(__file__)
__proxyenabled__ = ['onyx']
__virtualname__ = 'onyx'
DETAILS = {'grains_cache': {}}
def __virtual__():
'''
Only return if all the modules are available
'''
log.info('onyx proxy __virtual__() called...')
return __virtualname__
def _worker_name():
return multiprocessing.current_process().name
def init(opts=None):
'''
Required.
Can be used to initialize the server connection.
'''
if opts is None:
opts = __opts__
try:
DETAILS[_worker_name()] = SSHConnection(
host=opts['proxy']['host'],
username=opts['proxy']['username'],
password=opts['proxy']['password'],
key_accept=opts['proxy'].get('key_accept', False),
ssh_args=opts['proxy'].get('ssh_args', ''),
prompt='{0}.*(#|>) '.format(opts['proxy']['prompt_name']))
DETAILS[_worker_name()].sendline('no cli session paging enable')
except TerminalException as e:
log.error(e)
return False
DETAILS['initialized'] = True
def initialized():
'''
module initialization
'''
return DETAILS.get('initialized', False)
def ping():
'''
Ping the device on the other end of the connection
.. code-block: bash
salt '*' onyx.cmd ping
'''
if _worker_name() not in DETAILS:
init()
try:
return DETAILS[_worker_name()].conn.isalive()
except TerminalException as e:
log.error(e)
return False
def shutdown():
'''
Disconnect
'''
DETAILS[_worker_name()].close_connection()
def sendline(command):
'''
Run command through switch's cli
.. code-block: bash
salt '*' onyx.cmd sendline 'show run | include
"username admin password 7"'
'''
if ping() is False:
init()
out, _ = DETAILS[_worker_name()].sendline(command)
return out
def enable():
'''
Shortcut to run `enable` on switch
.. code-block:: bash
salt '*' onyx.cmd enable
'''
try:
ret = sendline('enable')
except TerminalException as e:
log.error(e)
return 'Failed to enable switch'
return ret
def configure_terminal():
'''
Shortcut to run `configure terminal` on switch
.. code-block:: bash
salt '*' onyx.cmd configure_terminal
'''
try:
ret = sendline('configure terminal ')
except TerminalException as e:
log.error(e)
return 'Failed to enable ' \
'configuration mode on switch'
return ret
def configure_terminal_exit():
'''
Shortcut to run `exit` from configuration mode on switch
.. code-block:: bash
salt '*' onyx.cmd configure_terminal_exit
'''
try:
ret = sendline('exit')
except TerminalException as e:
log.error(e)
return 'Failed to exit form configuration mode on switch'
return ret
def disable():
'''
Shortcut to run `disable` on switch
.. code-block:: bash
salt '*' onyx.cmd disable
'''
try:
ret = sendline('disable')
except TerminalException as e:
log.error(e)
return 'Failed to "configure terminal"'
return ret
def grains():
'''
Get grains for proxy minion
.. code-block: bash
salt '*' onyx.cmd grains
'''
if not DETAILS['grains_cache']:
ret = system_info()
log.debug(ret)
DETAILS['grains_cache'].update(ret)
return {'onyx': DETAILS['grains_cache']}
def grains_refresh():
'''
Refresh the grains from the proxy device.
.. code-block: bash
salt '*' onyx.cmd grains_refresh
'''
DETAILS['grains_cache'] = {}
return grains()
def get_user(username):
'''
Get username line from switch
.. code-block: bash
salt '*' onyx.cmd get_user username=admin
'''
try:
enable()
configure_terminal()
cmd_out = sendline('show running-config | include "username {0} password 7"'.format(username))
cmd_out.split('\n')
user = cmd_out[1:-1]
configure_terminal_exit()
disable()
return user
except TerminalException as e:
log.error(e)
return 'Failed to get user'
def get_roles(username):
'''
Get roles that the username is assigned from switch
.. code-block: bash
salt '*' onyx.cmd get_roles username=admin
'''
info = sendline('show user-account {0}'.format(username))
roles = re.search(r'^\s*roles:(.*)$', info, re.MULTILINE)
if roles:
roles = roles.group(1).strip().split(' ')
else:
roles = []
return roles
def check_role(username, role):
'''
Check if user is assigned a specific role on switch
.. code-block:: bash
salt '*' onyx.cmd check_role username=admin role=network-admin
'''
return role in get_roles(username)
def remove_user(username):
'''
Remove user from switch
.. code-block:: bash
salt '*' onyx.cmd remove_user username=daniel
'''
try:
sendline('config terminal')
user_line = 'no username {0}'.format(username)
ret = sendline(user_line)
sendline('end')
sendline('copy running-config startup-config')
return '\n'.join([user_line, ret])
except TerminalException as e:
log.error(e)
return 'Failed to set password'
def set_role(username, role):
'''
Assign role to username
.. code-block:: bash
salt '*' onyx.cmd set_role username=daniel role=vdc-admin
'''
try:
sendline('config terminal')
role_line = 'username {0} role {1}'.format(username, role)
ret = sendline(role_line)
sendline('end')
sendline('copy running-config startup-config')
return '\n'.join([role_line, ret])
except TerminalException as e:
log.error(e)
return 'Failed to set password'
def unset_role(username, role):
'''
Remove role from username
.. code-block:: bash
salt '*' onyx.cmd unset_role username=daniel role=vdc-admin
'''
try:
sendline('config terminal')
role_line = 'no username {0} role {1}'.format(username, role)
ret = sendline(role_line)
sendline('end')
sendline('copy running-config startup-config')
return '\n'.join([role_line, ret])
except TerminalException as e:
log.error(e)
return 'Failed to set password'
def show_run():
'''
Shortcut to run `show run` on switch
.. code-block:: bash
salt '*' onyx.cmd show_run
'''
try:
enable()
configure_terminal()
ret = sendline('show running-config')
configure_terminal_exit()
disable()
except TerminalException as e:
log.error(e)
return 'Failed to show running-config on switch'
return ret
def show_ver():
'''
Shortcut to run `show ver` on switch
.. code-block:: bash
salt '*' onyx.cmd show_ver
'''
try:
ret = sendline('show ver')
except TerminalException as e:
log.error(e)
return 'Failed to "show ver"'
return ret
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 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 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 _parser(block):
return re.compile('^{block}\n(?:^[ \n].*$\n?)+'.format(block=block), re.MULTILINE)
def _parse_software(data):
ret = {'software': {}}
software = _parser('Software').search(data).group(0)
matcher = re.compile('^ ([^:]+): *([^\n]+)', re.MULTILINE)
for line in matcher.finditer(software):
key, val = line.groups()
ret['software'][key] = val
return ret['software']
def _parse_hardware(data):
ret = {'hardware': {}}
hardware = _parser('Hardware').search(data).group(0)
matcher = re.compile('^ ([^:\n]+): *([^\n]+)', re.MULTILINE)
for line in matcher.finditer(hardware):
key, val = line.groups()
ret['hardware'][key] = val
return ret['hardware']
def _parse_plugins(data):
ret = {'plugins': []}
plugins = _parser('plugin').search(data).group(0)
matcher = re.compile('^ (?:([^,]+), )+([^\n]+)', re.MULTILINE)
for line in matcher.finditer(plugins):
ret['plugins'].extend(line.groups())
return ret['plugins']
def system_info():
'''
Return system information for grains of the NX OS proxy minion
.. code-block:: bash
salt '*' onyx.system_info
'''
# data = show_ver()
info = {
'software': 'Test',
'hardware': '',
'plugins': ''
}
return info
|
saltstack/salt
|
salt/proxy/onyx.py
|
delete_config
|
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
|
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.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/onyx.py#L421-L444
|
[
"def sendline(command):\n '''\n Run command through switch's cli\n\n .. code-block: bash\n\n salt '*' onyx.cmd sendline 'show run | include\n \"username admin password 7\"'\n '''\n if ping() is False:\n init()\n out, _ = DETAILS[_worker_name()].sendline(command)\n return out\n"
] |
# -*- coding: utf-8 -*-
'''
Proxy Minion for Onyx OS Switches
.. versionadded: Neon
The Onyx OS Proxy Minion uses the built in SSHConnection module
in :mod:`salt.utils.vt_helper <salt.utils.vt_helper>`
To configure the proxy minion:
.. code-block:: yaml
proxy:
proxytype: onyx
host: 192.168.187.100
username: admin
password: admin
prompt_name: switch
ssh_args: '-o PubkeyAuthentication=no'
key_accept: True
proxytype
(REQUIRED) Use this proxy minion `onyx`
host
(REQUIRED) ip address or hostname to connect to
username
(REQUIRED) username to login with
password
(REQUIRED) password to use to login with
prompt_name
(REQUIRED) The name in the prompt on the switch. By default, use your
devices hostname.
ssh_args
Any extra args to use to connect to the switch.
key_accept
Whether or not to accept a the host key of the switch on initial login.
Defaults to False.
The functions from the proxy minion can be run from the salt commandline using
the :mod:`salt.modules.onyx<salt.modules.onyx>` execution module.
.. note:
If `multiprocessing: True` is set for the proxy minion config, each forked
worker will open up a new connection to the Cisco NX OS Switch. If you
only want one consistent connection used for everything, use
`multiprocessing: False`
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import multiprocessing
import re
# Import Salt libs
from salt.utils.vt_helper import SSHConnection
from salt.utils.vt import TerminalException
log = logging.getLogger(__file__)
__proxyenabled__ = ['onyx']
__virtualname__ = 'onyx'
DETAILS = {'grains_cache': {}}
def __virtual__():
'''
Only return if all the modules are available
'''
log.info('onyx proxy __virtual__() called...')
return __virtualname__
def _worker_name():
return multiprocessing.current_process().name
def init(opts=None):
'''
Required.
Can be used to initialize the server connection.
'''
if opts is None:
opts = __opts__
try:
DETAILS[_worker_name()] = SSHConnection(
host=opts['proxy']['host'],
username=opts['proxy']['username'],
password=opts['proxy']['password'],
key_accept=opts['proxy'].get('key_accept', False),
ssh_args=opts['proxy'].get('ssh_args', ''),
prompt='{0}.*(#|>) '.format(opts['proxy']['prompt_name']))
DETAILS[_worker_name()].sendline('no cli session paging enable')
except TerminalException as e:
log.error(e)
return False
DETAILS['initialized'] = True
def initialized():
'''
module initialization
'''
return DETAILS.get('initialized', False)
def ping():
'''
Ping the device on the other end of the connection
.. code-block: bash
salt '*' onyx.cmd ping
'''
if _worker_name() not in DETAILS:
init()
try:
return DETAILS[_worker_name()].conn.isalive()
except TerminalException as e:
log.error(e)
return False
def shutdown():
'''
Disconnect
'''
DETAILS[_worker_name()].close_connection()
def sendline(command):
'''
Run command through switch's cli
.. code-block: bash
salt '*' onyx.cmd sendline 'show run | include
"username admin password 7"'
'''
if ping() is False:
init()
out, _ = DETAILS[_worker_name()].sendline(command)
return out
def enable():
'''
Shortcut to run `enable` on switch
.. code-block:: bash
salt '*' onyx.cmd enable
'''
try:
ret = sendline('enable')
except TerminalException as e:
log.error(e)
return 'Failed to enable switch'
return ret
def configure_terminal():
'''
Shortcut to run `configure terminal` on switch
.. code-block:: bash
salt '*' onyx.cmd configure_terminal
'''
try:
ret = sendline('configure terminal ')
except TerminalException as e:
log.error(e)
return 'Failed to enable ' \
'configuration mode on switch'
return ret
def configure_terminal_exit():
'''
Shortcut to run `exit` from configuration mode on switch
.. code-block:: bash
salt '*' onyx.cmd configure_terminal_exit
'''
try:
ret = sendline('exit')
except TerminalException as e:
log.error(e)
return 'Failed to exit form configuration mode on switch'
return ret
def disable():
'''
Shortcut to run `disable` on switch
.. code-block:: bash
salt '*' onyx.cmd disable
'''
try:
ret = sendline('disable')
except TerminalException as e:
log.error(e)
return 'Failed to "configure terminal"'
return ret
def grains():
'''
Get grains for proxy minion
.. code-block: bash
salt '*' onyx.cmd grains
'''
if not DETAILS['grains_cache']:
ret = system_info()
log.debug(ret)
DETAILS['grains_cache'].update(ret)
return {'onyx': DETAILS['grains_cache']}
def grains_refresh():
'''
Refresh the grains from the proxy device.
.. code-block: bash
salt '*' onyx.cmd grains_refresh
'''
DETAILS['grains_cache'] = {}
return grains()
def get_user(username):
'''
Get username line from switch
.. code-block: bash
salt '*' onyx.cmd get_user username=admin
'''
try:
enable()
configure_terminal()
cmd_out = sendline('show running-config | include "username {0} password 7"'.format(username))
cmd_out.split('\n')
user = cmd_out[1:-1]
configure_terminal_exit()
disable()
return user
except TerminalException as e:
log.error(e)
return 'Failed to get user'
def get_roles(username):
'''
Get roles that the username is assigned from switch
.. code-block: bash
salt '*' onyx.cmd get_roles username=admin
'''
info = sendline('show user-account {0}'.format(username))
roles = re.search(r'^\s*roles:(.*)$', info, re.MULTILINE)
if roles:
roles = roles.group(1).strip().split(' ')
else:
roles = []
return roles
def check_role(username, role):
'''
Check if user is assigned a specific role on switch
.. code-block:: bash
salt '*' onyx.cmd check_role username=admin role=network-admin
'''
return role in get_roles(username)
def remove_user(username):
'''
Remove user from switch
.. code-block:: bash
salt '*' onyx.cmd remove_user username=daniel
'''
try:
sendline('config terminal')
user_line = 'no username {0}'.format(username)
ret = sendline(user_line)
sendline('end')
sendline('copy running-config startup-config')
return '\n'.join([user_line, ret])
except TerminalException as e:
log.error(e)
return 'Failed to set password'
def set_role(username, role):
'''
Assign role to username
.. code-block:: bash
salt '*' onyx.cmd set_role username=daniel role=vdc-admin
'''
try:
sendline('config terminal')
role_line = 'username {0} role {1}'.format(username, role)
ret = sendline(role_line)
sendline('end')
sendline('copy running-config startup-config')
return '\n'.join([role_line, ret])
except TerminalException as e:
log.error(e)
return 'Failed to set password'
def unset_role(username, role):
'''
Remove role from username
.. code-block:: bash
salt '*' onyx.cmd unset_role username=daniel role=vdc-admin
'''
try:
sendline('config terminal')
role_line = 'no username {0} role {1}'.format(username, role)
ret = sendline(role_line)
sendline('end')
sendline('copy running-config startup-config')
return '\n'.join([role_line, ret])
except TerminalException as e:
log.error(e)
return 'Failed to set password'
def show_run():
'''
Shortcut to run `show run` on switch
.. code-block:: bash
salt '*' onyx.cmd show_run
'''
try:
enable()
configure_terminal()
ret = sendline('show running-config')
configure_terminal_exit()
disable()
except TerminalException as e:
log.error(e)
return 'Failed to show running-config on switch'
return ret
def show_ver():
'''
Shortcut to run `show ver` on switch
.. code-block:: bash
salt '*' onyx.cmd show_ver
'''
try:
ret = sendline('show ver')
except TerminalException as e:
log.error(e)
return 'Failed to "show ver"'
return ret
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 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 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 _parser(block):
return re.compile('^{block}\n(?:^[ \n].*$\n?)+'.format(block=block), re.MULTILINE)
def _parse_software(data):
ret = {'software': {}}
software = _parser('Software').search(data).group(0)
matcher = re.compile('^ ([^:]+): *([^\n]+)', re.MULTILINE)
for line in matcher.finditer(software):
key, val = line.groups()
ret['software'][key] = val
return ret['software']
def _parse_hardware(data):
ret = {'hardware': {}}
hardware = _parser('Hardware').search(data).group(0)
matcher = re.compile('^ ([^:\n]+): *([^\n]+)', re.MULTILINE)
for line in matcher.finditer(hardware):
key, val = line.groups()
ret['hardware'][key] = val
return ret['hardware']
def _parse_plugins(data):
ret = {'plugins': []}
plugins = _parser('plugin').search(data).group(0)
matcher = re.compile('^ (?:([^,]+), )+([^\n]+)', re.MULTILINE)
for line in matcher.finditer(plugins):
ret['plugins'].extend(line.groups())
return ret['plugins']
def system_info():
'''
Return system information for grains of the NX OS proxy minion
.. code-block:: bash
salt '*' onyx.system_info
'''
# data = show_ver()
info = {
'software': 'Test',
'hardware': '',
'plugins': ''
}
return info
|
saltstack/salt
|
salt/proxy/onyx.py
|
find
|
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())
|
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.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/onyx.py#L447-L460
|
[
"def show_run():\n '''\n Shortcut to run `show run` on switch\n\n .. code-block:: bash\n\n salt '*' onyx.cmd show_run\n '''\n try:\n enable()\n configure_terminal()\n ret = sendline('show running-config')\n configure_terminal_exit()\n disable()\n except TerminalException as e:\n log.error(e)\n return 'Failed to show running-config on switch'\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Proxy Minion for Onyx OS Switches
.. versionadded: Neon
The Onyx OS Proxy Minion uses the built in SSHConnection module
in :mod:`salt.utils.vt_helper <salt.utils.vt_helper>`
To configure the proxy minion:
.. code-block:: yaml
proxy:
proxytype: onyx
host: 192.168.187.100
username: admin
password: admin
prompt_name: switch
ssh_args: '-o PubkeyAuthentication=no'
key_accept: True
proxytype
(REQUIRED) Use this proxy minion `onyx`
host
(REQUIRED) ip address or hostname to connect to
username
(REQUIRED) username to login with
password
(REQUIRED) password to use to login with
prompt_name
(REQUIRED) The name in the prompt on the switch. By default, use your
devices hostname.
ssh_args
Any extra args to use to connect to the switch.
key_accept
Whether or not to accept a the host key of the switch on initial login.
Defaults to False.
The functions from the proxy minion can be run from the salt commandline using
the :mod:`salt.modules.onyx<salt.modules.onyx>` execution module.
.. note:
If `multiprocessing: True` is set for the proxy minion config, each forked
worker will open up a new connection to the Cisco NX OS Switch. If you
only want one consistent connection used for everything, use
`multiprocessing: False`
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import multiprocessing
import re
# Import Salt libs
from salt.utils.vt_helper import SSHConnection
from salt.utils.vt import TerminalException
log = logging.getLogger(__file__)
__proxyenabled__ = ['onyx']
__virtualname__ = 'onyx'
DETAILS = {'grains_cache': {}}
def __virtual__():
'''
Only return if all the modules are available
'''
log.info('onyx proxy __virtual__() called...')
return __virtualname__
def _worker_name():
return multiprocessing.current_process().name
def init(opts=None):
'''
Required.
Can be used to initialize the server connection.
'''
if opts is None:
opts = __opts__
try:
DETAILS[_worker_name()] = SSHConnection(
host=opts['proxy']['host'],
username=opts['proxy']['username'],
password=opts['proxy']['password'],
key_accept=opts['proxy'].get('key_accept', False),
ssh_args=opts['proxy'].get('ssh_args', ''),
prompt='{0}.*(#|>) '.format(opts['proxy']['prompt_name']))
DETAILS[_worker_name()].sendline('no cli session paging enable')
except TerminalException as e:
log.error(e)
return False
DETAILS['initialized'] = True
def initialized():
'''
module initialization
'''
return DETAILS.get('initialized', False)
def ping():
'''
Ping the device on the other end of the connection
.. code-block: bash
salt '*' onyx.cmd ping
'''
if _worker_name() not in DETAILS:
init()
try:
return DETAILS[_worker_name()].conn.isalive()
except TerminalException as e:
log.error(e)
return False
def shutdown():
'''
Disconnect
'''
DETAILS[_worker_name()].close_connection()
def sendline(command):
'''
Run command through switch's cli
.. code-block: bash
salt '*' onyx.cmd sendline 'show run | include
"username admin password 7"'
'''
if ping() is False:
init()
out, _ = DETAILS[_worker_name()].sendline(command)
return out
def enable():
'''
Shortcut to run `enable` on switch
.. code-block:: bash
salt '*' onyx.cmd enable
'''
try:
ret = sendline('enable')
except TerminalException as e:
log.error(e)
return 'Failed to enable switch'
return ret
def configure_terminal():
'''
Shortcut to run `configure terminal` on switch
.. code-block:: bash
salt '*' onyx.cmd configure_terminal
'''
try:
ret = sendline('configure terminal ')
except TerminalException as e:
log.error(e)
return 'Failed to enable ' \
'configuration mode on switch'
return ret
def configure_terminal_exit():
'''
Shortcut to run `exit` from configuration mode on switch
.. code-block:: bash
salt '*' onyx.cmd configure_terminal_exit
'''
try:
ret = sendline('exit')
except TerminalException as e:
log.error(e)
return 'Failed to exit form configuration mode on switch'
return ret
def disable():
'''
Shortcut to run `disable` on switch
.. code-block:: bash
salt '*' onyx.cmd disable
'''
try:
ret = sendline('disable')
except TerminalException as e:
log.error(e)
return 'Failed to "configure terminal"'
return ret
def grains():
'''
Get grains for proxy minion
.. code-block: bash
salt '*' onyx.cmd grains
'''
if not DETAILS['grains_cache']:
ret = system_info()
log.debug(ret)
DETAILS['grains_cache'].update(ret)
return {'onyx': DETAILS['grains_cache']}
def grains_refresh():
'''
Refresh the grains from the proxy device.
.. code-block: bash
salt '*' onyx.cmd grains_refresh
'''
DETAILS['grains_cache'] = {}
return grains()
def get_user(username):
'''
Get username line from switch
.. code-block: bash
salt '*' onyx.cmd get_user username=admin
'''
try:
enable()
configure_terminal()
cmd_out = sendline('show running-config | include "username {0} password 7"'.format(username))
cmd_out.split('\n')
user = cmd_out[1:-1]
configure_terminal_exit()
disable()
return user
except TerminalException as e:
log.error(e)
return 'Failed to get user'
def get_roles(username):
'''
Get roles that the username is assigned from switch
.. code-block: bash
salt '*' onyx.cmd get_roles username=admin
'''
info = sendline('show user-account {0}'.format(username))
roles = re.search(r'^\s*roles:(.*)$', info, re.MULTILINE)
if roles:
roles = roles.group(1).strip().split(' ')
else:
roles = []
return roles
def check_role(username, role):
'''
Check if user is assigned a specific role on switch
.. code-block:: bash
salt '*' onyx.cmd check_role username=admin role=network-admin
'''
return role in get_roles(username)
def remove_user(username):
'''
Remove user from switch
.. code-block:: bash
salt '*' onyx.cmd remove_user username=daniel
'''
try:
sendline('config terminal')
user_line = 'no username {0}'.format(username)
ret = sendline(user_line)
sendline('end')
sendline('copy running-config startup-config')
return '\n'.join([user_line, ret])
except TerminalException as e:
log.error(e)
return 'Failed to set password'
def set_role(username, role):
'''
Assign role to username
.. code-block:: bash
salt '*' onyx.cmd set_role username=daniel role=vdc-admin
'''
try:
sendline('config terminal')
role_line = 'username {0} role {1}'.format(username, role)
ret = sendline(role_line)
sendline('end')
sendline('copy running-config startup-config')
return '\n'.join([role_line, ret])
except TerminalException as e:
log.error(e)
return 'Failed to set password'
def unset_role(username, role):
'''
Remove role from username
.. code-block:: bash
salt '*' onyx.cmd unset_role username=daniel role=vdc-admin
'''
try:
sendline('config terminal')
role_line = 'no username {0} role {1}'.format(username, role)
ret = sendline(role_line)
sendline('end')
sendline('copy running-config startup-config')
return '\n'.join([role_line, ret])
except TerminalException as e:
log.error(e)
return 'Failed to set password'
def show_run():
'''
Shortcut to run `show run` on switch
.. code-block:: bash
salt '*' onyx.cmd show_run
'''
try:
enable()
configure_terminal()
ret = sendline('show running-config')
configure_terminal_exit()
disable()
except TerminalException as e:
log.error(e)
return 'Failed to show running-config on switch'
return ret
def show_ver():
'''
Shortcut to run `show ver` on switch
.. code-block:: bash
salt '*' onyx.cmd show_ver
'''
try:
ret = sendline('show ver')
except TerminalException as e:
log.error(e)
return 'Failed to "show ver"'
return ret
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 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 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 _parser(block):
return re.compile('^{block}\n(?:^[ \n].*$\n?)+'.format(block=block), re.MULTILINE)
def _parse_software(data):
ret = {'software': {}}
software = _parser('Software').search(data).group(0)
matcher = re.compile('^ ([^:]+): *([^\n]+)', re.MULTILINE)
for line in matcher.finditer(software):
key, val = line.groups()
ret['software'][key] = val
return ret['software']
def _parse_hardware(data):
ret = {'hardware': {}}
hardware = _parser('Hardware').search(data).group(0)
matcher = re.compile('^ ([^:\n]+): *([^\n]+)', re.MULTILINE)
for line in matcher.finditer(hardware):
key, val = line.groups()
ret['hardware'][key] = val
return ret['hardware']
def _parse_plugins(data):
ret = {'plugins': []}
plugins = _parser('plugin').search(data).group(0)
matcher = re.compile('^ (?:([^,]+), )+([^\n]+)', re.MULTILINE)
for line in matcher.finditer(plugins):
ret['plugins'].extend(line.groups())
return ret['plugins']
def system_info():
'''
Return system information for grains of the NX OS proxy minion
.. code-block:: bash
salt '*' onyx.system_info
'''
# data = show_ver()
info = {
'software': 'Test',
'hardware': '',
'plugins': ''
}
return info
|
saltstack/salt
|
salt/proxy/onyx.py
|
replace
|
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
|
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'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/onyx.py#L463-L489
|
[
"def show_run():\n '''\n Shortcut to run `show run` on switch\n\n .. code-block:: bash\n\n salt '*' onyx.cmd show_run\n '''\n try:\n enable()\n configure_terminal()\n ret = sendline('show running-config')\n configure_terminal_exit()\n disable()\n except TerminalException as e:\n log.error(e)\n return 'Failed to show running-config on switch'\n return ret\n",
"def add_config(lines):\n '''\n Add one or more config lines to the switch running config\n\n .. code-block:: bash\n\n salt '*' onyx.cmd add_config 'snmp-server community TESTSTRINGHERE rw'\n\n .. note::\n For more than one config added per command, lines should be a list.\n '''\n if not isinstance(lines, list):\n lines = [lines]\n try:\n enable()\n configure_terminal()\n for line in lines:\n sendline(line)\n\n configure_terminal_exit()\n disable()\n except TerminalException as e:\n log.error(e)\n return False\n return True\n",
"def delete_config(lines):\n '''\n Delete one or more config lines to the switch running config\n\n .. code-block:: bash\n\n salt '*' onyx.cmd delete_config 'snmp-server community TESTSTRINGHERE group network-operator'\n\n .. note::\n For more than one config deleted per command, lines should be a list.\n '''\n if not isinstance(lines, list):\n lines = [lines]\n try:\n sendline('config terminal')\n for line in lines:\n sendline(' '.join(['no', line]))\n\n sendline('end')\n sendline('copy running-config startup-config')\n except TerminalException as e:\n log.error(e)\n return False\n return True\n"
] |
# -*- coding: utf-8 -*-
'''
Proxy Minion for Onyx OS Switches
.. versionadded: Neon
The Onyx OS Proxy Minion uses the built in SSHConnection module
in :mod:`salt.utils.vt_helper <salt.utils.vt_helper>`
To configure the proxy minion:
.. code-block:: yaml
proxy:
proxytype: onyx
host: 192.168.187.100
username: admin
password: admin
prompt_name: switch
ssh_args: '-o PubkeyAuthentication=no'
key_accept: True
proxytype
(REQUIRED) Use this proxy minion `onyx`
host
(REQUIRED) ip address or hostname to connect to
username
(REQUIRED) username to login with
password
(REQUIRED) password to use to login with
prompt_name
(REQUIRED) The name in the prompt on the switch. By default, use your
devices hostname.
ssh_args
Any extra args to use to connect to the switch.
key_accept
Whether or not to accept a the host key of the switch on initial login.
Defaults to False.
The functions from the proxy minion can be run from the salt commandline using
the :mod:`salt.modules.onyx<salt.modules.onyx>` execution module.
.. note:
If `multiprocessing: True` is set for the proxy minion config, each forked
worker will open up a new connection to the Cisco NX OS Switch. If you
only want one consistent connection used for everything, use
`multiprocessing: False`
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import multiprocessing
import re
# Import Salt libs
from salt.utils.vt_helper import SSHConnection
from salt.utils.vt import TerminalException
log = logging.getLogger(__file__)
__proxyenabled__ = ['onyx']
__virtualname__ = 'onyx'
DETAILS = {'grains_cache': {}}
def __virtual__():
'''
Only return if all the modules are available
'''
log.info('onyx proxy __virtual__() called...')
return __virtualname__
def _worker_name():
return multiprocessing.current_process().name
def init(opts=None):
'''
Required.
Can be used to initialize the server connection.
'''
if opts is None:
opts = __opts__
try:
DETAILS[_worker_name()] = SSHConnection(
host=opts['proxy']['host'],
username=opts['proxy']['username'],
password=opts['proxy']['password'],
key_accept=opts['proxy'].get('key_accept', False),
ssh_args=opts['proxy'].get('ssh_args', ''),
prompt='{0}.*(#|>) '.format(opts['proxy']['prompt_name']))
DETAILS[_worker_name()].sendline('no cli session paging enable')
except TerminalException as e:
log.error(e)
return False
DETAILS['initialized'] = True
def initialized():
'''
module initialization
'''
return DETAILS.get('initialized', False)
def ping():
'''
Ping the device on the other end of the connection
.. code-block: bash
salt '*' onyx.cmd ping
'''
if _worker_name() not in DETAILS:
init()
try:
return DETAILS[_worker_name()].conn.isalive()
except TerminalException as e:
log.error(e)
return False
def shutdown():
'''
Disconnect
'''
DETAILS[_worker_name()].close_connection()
def sendline(command):
'''
Run command through switch's cli
.. code-block: bash
salt '*' onyx.cmd sendline 'show run | include
"username admin password 7"'
'''
if ping() is False:
init()
out, _ = DETAILS[_worker_name()].sendline(command)
return out
def enable():
'''
Shortcut to run `enable` on switch
.. code-block:: bash
salt '*' onyx.cmd enable
'''
try:
ret = sendline('enable')
except TerminalException as e:
log.error(e)
return 'Failed to enable switch'
return ret
def configure_terminal():
'''
Shortcut to run `configure terminal` on switch
.. code-block:: bash
salt '*' onyx.cmd configure_terminal
'''
try:
ret = sendline('configure terminal ')
except TerminalException as e:
log.error(e)
return 'Failed to enable ' \
'configuration mode on switch'
return ret
def configure_terminal_exit():
'''
Shortcut to run `exit` from configuration mode on switch
.. code-block:: bash
salt '*' onyx.cmd configure_terminal_exit
'''
try:
ret = sendline('exit')
except TerminalException as e:
log.error(e)
return 'Failed to exit form configuration mode on switch'
return ret
def disable():
'''
Shortcut to run `disable` on switch
.. code-block:: bash
salt '*' onyx.cmd disable
'''
try:
ret = sendline('disable')
except TerminalException as e:
log.error(e)
return 'Failed to "configure terminal"'
return ret
def grains():
'''
Get grains for proxy minion
.. code-block: bash
salt '*' onyx.cmd grains
'''
if not DETAILS['grains_cache']:
ret = system_info()
log.debug(ret)
DETAILS['grains_cache'].update(ret)
return {'onyx': DETAILS['grains_cache']}
def grains_refresh():
'''
Refresh the grains from the proxy device.
.. code-block: bash
salt '*' onyx.cmd grains_refresh
'''
DETAILS['grains_cache'] = {}
return grains()
def get_user(username):
'''
Get username line from switch
.. code-block: bash
salt '*' onyx.cmd get_user username=admin
'''
try:
enable()
configure_terminal()
cmd_out = sendline('show running-config | include "username {0} password 7"'.format(username))
cmd_out.split('\n')
user = cmd_out[1:-1]
configure_terminal_exit()
disable()
return user
except TerminalException as e:
log.error(e)
return 'Failed to get user'
def get_roles(username):
'''
Get roles that the username is assigned from switch
.. code-block: bash
salt '*' onyx.cmd get_roles username=admin
'''
info = sendline('show user-account {0}'.format(username))
roles = re.search(r'^\s*roles:(.*)$', info, re.MULTILINE)
if roles:
roles = roles.group(1).strip().split(' ')
else:
roles = []
return roles
def check_role(username, role):
'''
Check if user is assigned a specific role on switch
.. code-block:: bash
salt '*' onyx.cmd check_role username=admin role=network-admin
'''
return role in get_roles(username)
def remove_user(username):
'''
Remove user from switch
.. code-block:: bash
salt '*' onyx.cmd remove_user username=daniel
'''
try:
sendline('config terminal')
user_line = 'no username {0}'.format(username)
ret = sendline(user_line)
sendline('end')
sendline('copy running-config startup-config')
return '\n'.join([user_line, ret])
except TerminalException as e:
log.error(e)
return 'Failed to set password'
def set_role(username, role):
'''
Assign role to username
.. code-block:: bash
salt '*' onyx.cmd set_role username=daniel role=vdc-admin
'''
try:
sendline('config terminal')
role_line = 'username {0} role {1}'.format(username, role)
ret = sendline(role_line)
sendline('end')
sendline('copy running-config startup-config')
return '\n'.join([role_line, ret])
except TerminalException as e:
log.error(e)
return 'Failed to set password'
def unset_role(username, role):
'''
Remove role from username
.. code-block:: bash
salt '*' onyx.cmd unset_role username=daniel role=vdc-admin
'''
try:
sendline('config terminal')
role_line = 'no username {0} role {1}'.format(username, role)
ret = sendline(role_line)
sendline('end')
sendline('copy running-config startup-config')
return '\n'.join([role_line, ret])
except TerminalException as e:
log.error(e)
return 'Failed to set password'
def show_run():
'''
Shortcut to run `show run` on switch
.. code-block:: bash
salt '*' onyx.cmd show_run
'''
try:
enable()
configure_terminal()
ret = sendline('show running-config')
configure_terminal_exit()
disable()
except TerminalException as e:
log.error(e)
return 'Failed to show running-config on switch'
return ret
def show_ver():
'''
Shortcut to run `show ver` on switch
.. code-block:: bash
salt '*' onyx.cmd show_ver
'''
try:
ret = sendline('show ver')
except TerminalException as e:
log.error(e)
return 'Failed to "show ver"'
return ret
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 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 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 _parser(block):
return re.compile('^{block}\n(?:^[ \n].*$\n?)+'.format(block=block), re.MULTILINE)
def _parse_software(data):
ret = {'software': {}}
software = _parser('Software').search(data).group(0)
matcher = re.compile('^ ([^:]+): *([^\n]+)', re.MULTILINE)
for line in matcher.finditer(software):
key, val = line.groups()
ret['software'][key] = val
return ret['software']
def _parse_hardware(data):
ret = {'hardware': {}}
hardware = _parser('Hardware').search(data).group(0)
matcher = re.compile('^ ([^:\n]+): *([^\n]+)', re.MULTILINE)
for line in matcher.finditer(hardware):
key, val = line.groups()
ret['hardware'][key] = val
return ret['hardware']
def _parse_plugins(data):
ret = {'plugins': []}
plugins = _parser('plugin').search(data).group(0)
matcher = re.compile('^ (?:([^,]+), )+([^\n]+)', re.MULTILINE)
for line in matcher.finditer(plugins):
ret['plugins'].extend(line.groups())
return ret['plugins']
def system_info():
'''
Return system information for grains of the NX OS proxy minion
.. code-block:: bash
salt '*' onyx.system_info
'''
# data = show_ver()
info = {
'software': 'Test',
'hardware': '',
'plugins': ''
}
return info
|
saltstack/salt
|
salt/states/postgres_group.py
|
present
|
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
|
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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/postgres_group.py#L36-L213
|
[
"def _maybe_encrypt_password(role,\n password,\n encrypted=_DEFAULT_PASSWORDS_ENCRYPTION):\n '''\n pgsql passwords are md5 hashes of the string: 'md5{password}{rolename}'\n '''\n if password is not None:\n password = six.text_type(password)\n if encrypted and password and not password.startswith('md5'):\n password = \"md5{0}\".format(\n hashlib.md5(salt.utils.stringutils.to_bytes('{0}{1}'.format(password, role))).hexdigest())\n return password\n"
] |
# -*- coding: utf-8 -*-
'''
Management of PostgreSQL groups (roles)
=======================================
The postgres_group module is used to create and manage Postgres groups.
.. code-block:: yaml
frank:
postgres_group.present
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import Python libs
# Import salt libs
import logging
# Salt imports
from salt.modules import postgres
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load if the postgres module is present
'''
if 'postgres.group_create' not in __salt__:
return (False, 'Unable to load postgres module. Make sure `postgres.bins_dir` is set.')
return True
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
|
saltstack/salt
|
salt/states/postgres_group.py
|
absent
|
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
|
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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/postgres_group.py#L216-L273
| null |
# -*- coding: utf-8 -*-
'''
Management of PostgreSQL groups (roles)
=======================================
The postgres_group module is used to create and manage Postgres groups.
.. code-block:: yaml
frank:
postgres_group.present
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import Python libs
# Import salt libs
import logging
# Salt imports
from salt.modules import postgres
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load if the postgres module is present
'''
if 'postgres.group_create' not in __salt__:
return (False, 'Unable to load postgres module. Make sure `postgres.bins_dir` is set.')
return True
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
|
saltstack/salt
|
salt/utils/docker/translate/helpers.py
|
get_port_def
|
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)
|
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.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/docker/translate/helpers.py#L26-L59
| null |
# -*- coding: utf-8 -*-
'''
Functions to translate input in the docker CLI format to the format desired by
by the API.
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
# Import Salt libs
import salt.utils.data
import salt.utils.network
from salt.exceptions import SaltInvocationError
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import range, zip # pylint: disable=import-error,redefined-builtin
NOTSET = object()
def split(item, sep=',', maxsplit=-1):
return [x.strip() for x in item.split(sep, maxsplit)]
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 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 validate_ip(val):
try:
if not salt.utils.network.is_ip(val):
raise SaltInvocationError(
'\'{0}\' is not a valid IP address'.format(val)
)
except RuntimeError:
pass
def validate_subnet(val):
try:
if not salt.utils.network.is_subnet(val):
raise SaltInvocationError(
'\'{0}\' is not a valid subnet'.format(val)
)
except RuntimeError:
pass
def translate_str(val):
return six.text_type(val) if not isinstance(val, six.string_types) else val
def translate_int(val):
if not isinstance(val, six.integer_types):
try:
val = int(val)
except (TypeError, ValueError):
raise SaltInvocationError('\'{0}\' is not an integer'.format(val))
return val
def translate_bool(val):
return bool(val) if not isinstance(val, bool) else val
def translate_dict(val):
'''
Not really translating, just raising an exception if it's not a dict
'''
if not isinstance(val, dict):
raise SaltInvocationError('\'{0}\' is not a dictionary'.format(val))
return val
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_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_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_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_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_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
|
saltstack/salt
|
salt/utils/docker/translate/helpers.py
|
get_port_range
|
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
|
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.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/docker/translate/helpers.py#L62-L93
|
[
"def split(item, sep=',', maxsplit=-1):\n return [x.strip() for x in item.split(sep, maxsplit)]\n"
] |
# -*- coding: utf-8 -*-
'''
Functions to translate input in the docker CLI format to the format desired by
by the API.
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
# Import Salt libs
import salt.utils.data
import salt.utils.network
from salt.exceptions import SaltInvocationError
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import range, zip # pylint: disable=import-error,redefined-builtin
NOTSET = object()
def split(item, sep=',', maxsplit=-1):
return [x.strip() for x in item.split(sep, maxsplit)]
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 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 validate_ip(val):
try:
if not salt.utils.network.is_ip(val):
raise SaltInvocationError(
'\'{0}\' is not a valid IP address'.format(val)
)
except RuntimeError:
pass
def validate_subnet(val):
try:
if not salt.utils.network.is_subnet(val):
raise SaltInvocationError(
'\'{0}\' is not a valid subnet'.format(val)
)
except RuntimeError:
pass
def translate_str(val):
return six.text_type(val) if not isinstance(val, six.string_types) else val
def translate_int(val):
if not isinstance(val, six.integer_types):
try:
val = int(val)
except (TypeError, ValueError):
raise SaltInvocationError('\'{0}\' is not an integer'.format(val))
return val
def translate_bool(val):
return bool(val) if not isinstance(val, bool) else val
def translate_dict(val):
'''
Not really translating, just raising an exception if it's not a dict
'''
if not isinstance(val, dict):
raise SaltInvocationError('\'{0}\' is not a dictionary'.format(val))
return val
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_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_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_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_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_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
|
saltstack/salt
|
salt/utils/docker/translate/helpers.py
|
map_vals
|
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
|
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.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/docker/translate/helpers.py#L96-L127
|
[
"def translate_stringlist(val):\n '''\n On the CLI, these are passed as multiple instances of a given CLI option.\n In Salt, we accept these as a comma-delimited list but the API expects a\n Python list. This function accepts input and returns it back as a Python\n list of strings. If the input is a string which is a comma-separated list\n of items, split that string and return it.\n '''\n if not isinstance(val, list):\n try:\n val = split(val)\n except AttributeError:\n val = split(six.text_type(val))\n for idx in range(len(val)):\n if not isinstance(val[idx], six.string_types):\n val[idx] = six.text_type(val[idx])\n return val\n"
] |
# -*- coding: utf-8 -*-
'''
Functions to translate input in the docker CLI format to the format desired by
by the API.
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
# Import Salt libs
import salt.utils.data
import salt.utils.network
from salt.exceptions import SaltInvocationError
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import range, zip # pylint: disable=import-error,redefined-builtin
NOTSET = object()
def split(item, sep=',', maxsplit=-1):
return [x.strip() for x in item.split(sep, maxsplit)]
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_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 validate_ip(val):
try:
if not salt.utils.network.is_ip(val):
raise SaltInvocationError(
'\'{0}\' is not a valid IP address'.format(val)
)
except RuntimeError:
pass
def validate_subnet(val):
try:
if not salt.utils.network.is_subnet(val):
raise SaltInvocationError(
'\'{0}\' is not a valid subnet'.format(val)
)
except RuntimeError:
pass
def translate_str(val):
return six.text_type(val) if not isinstance(val, six.string_types) else val
def translate_int(val):
if not isinstance(val, six.integer_types):
try:
val = int(val)
except (TypeError, ValueError):
raise SaltInvocationError('\'{0}\' is not an integer'.format(val))
return val
def translate_bool(val):
return bool(val) if not isinstance(val, bool) else val
def translate_dict(val):
'''
Not really translating, just raising an exception if it's not a dict
'''
if not isinstance(val, dict):
raise SaltInvocationError('\'{0}\' is not a dictionary'.format(val))
return val
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_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_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_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_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_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
|
saltstack/salt
|
salt/utils/docker/translate/helpers.py
|
translate_command
|
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
|
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").
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/docker/translate/helpers.py#L176-L190
| null |
# -*- coding: utf-8 -*-
'''
Functions to translate input in the docker CLI format to the format desired by
by the API.
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
# Import Salt libs
import salt.utils.data
import salt.utils.network
from salt.exceptions import SaltInvocationError
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import range, zip # pylint: disable=import-error,redefined-builtin
NOTSET = object()
def split(item, sep=',', maxsplit=-1):
return [x.strip() for x in item.split(sep, maxsplit)]
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_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 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 validate_ip(val):
try:
if not salt.utils.network.is_ip(val):
raise SaltInvocationError(
'\'{0}\' is not a valid IP address'.format(val)
)
except RuntimeError:
pass
def validate_subnet(val):
try:
if not salt.utils.network.is_subnet(val):
raise SaltInvocationError(
'\'{0}\' is not a valid subnet'.format(val)
)
except RuntimeError:
pass
def translate_str(val):
return six.text_type(val) if not isinstance(val, six.string_types) else val
def translate_int(val):
if not isinstance(val, six.integer_types):
try:
val = int(val)
except (TypeError, ValueError):
raise SaltInvocationError('\'{0}\' is not an integer'.format(val))
return val
def translate_bool(val):
return bool(val) if not isinstance(val, bool) else val
def translate_dict(val):
'''
Not really translating, just raising an exception if it's not a dict
'''
if not isinstance(val, dict):
raise SaltInvocationError('\'{0}\' is not a dictionary'.format(val))
return val
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_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_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_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_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
|
saltstack/salt
|
salt/utils/docker/translate/helpers.py
|
translate_bytes
|
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
|
These values can be expressed as an integer number of bytes, or a string
expression (i.e. 100mb, 1gb, etc.).
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/docker/translate/helpers.py#L193-L203
| null |
# -*- coding: utf-8 -*-
'''
Functions to translate input in the docker CLI format to the format desired by
by the API.
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
# Import Salt libs
import salt.utils.data
import salt.utils.network
from salt.exceptions import SaltInvocationError
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import range, zip # pylint: disable=import-error,redefined-builtin
NOTSET = object()
def split(item, sep=',', maxsplit=-1):
return [x.strip() for x in item.split(sep, maxsplit)]
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_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 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 validate_ip(val):
try:
if not salt.utils.network.is_ip(val):
raise SaltInvocationError(
'\'{0}\' is not a valid IP address'.format(val)
)
except RuntimeError:
pass
def validate_subnet(val):
try:
if not salt.utils.network.is_subnet(val):
raise SaltInvocationError(
'\'{0}\' is not a valid subnet'.format(val)
)
except RuntimeError:
pass
def translate_str(val):
return six.text_type(val) if not isinstance(val, six.string_types) else val
def translate_int(val):
if not isinstance(val, six.integer_types):
try:
val = int(val)
except (TypeError, ValueError):
raise SaltInvocationError('\'{0}\' is not an integer'.format(val))
return val
def translate_bool(val):
return bool(val) if not isinstance(val, bool) else val
def translate_dict(val):
'''
Not really translating, just raising an exception if it's not a dict
'''
if not isinstance(val, dict):
raise SaltInvocationError('\'{0}\' is not a dictionary'.format(val))
return val
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_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_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_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_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
|
saltstack/salt
|
salt/utils/docker/translate/helpers.py
|
translate_stringlist
|
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
|
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.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/docker/translate/helpers.py#L206-L222
|
[
"def split(item, sep=',', maxsplit=-1):\n return [x.strip() for x in item.split(sep, maxsplit)]\n"
] |
# -*- coding: utf-8 -*-
'''
Functions to translate input in the docker CLI format to the format desired by
by the API.
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
# Import Salt libs
import salt.utils.data
import salt.utils.network
from salt.exceptions import SaltInvocationError
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import range, zip # pylint: disable=import-error,redefined-builtin
NOTSET = object()
def split(item, sep=',', maxsplit=-1):
return [x.strip() for x in item.split(sep, maxsplit)]
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_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 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 validate_ip(val):
try:
if not salt.utils.network.is_ip(val):
raise SaltInvocationError(
'\'{0}\' is not a valid IP address'.format(val)
)
except RuntimeError:
pass
def validate_subnet(val):
try:
if not salt.utils.network.is_subnet(val):
raise SaltInvocationError(
'\'{0}\' is not a valid subnet'.format(val)
)
except RuntimeError:
pass
def translate_str(val):
return six.text_type(val) if not isinstance(val, six.string_types) else val
def translate_int(val):
if not isinstance(val, six.integer_types):
try:
val = int(val)
except (TypeError, ValueError):
raise SaltInvocationError('\'{0}\' is not an integer'.format(val))
return val
def translate_bool(val):
return bool(val) if not isinstance(val, bool) else val
def translate_dict(val):
'''
Not really translating, just raising an exception if it's not a dict
'''
if not isinstance(val, dict):
raise SaltInvocationError('\'{0}\' is not a dictionary'.format(val))
return val
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_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_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_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_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
|
saltstack/salt
|
salt/utils/docker/translate/helpers.py
|
translate_device_rates
|
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
|
CLI input is a list of PATH:RATE pairs, but the API expects a list of
dictionaries in the format [{'Path': path, 'Rate': rate}]
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/docker/translate/helpers.py#L225-L257
|
[
"def map_vals(val, *names, **extra_opts):\n '''\n Many arguments come in as a list of VAL1:VAL2 pairs, but map to a list\n of dicts in the format {NAME1: VAL1, NAME2: VAL2}. This function\n provides common code to handle these instances.\n '''\n fill = extra_opts.pop('fill', NOTSET)\n expected_num_elements = len(names)\n val = translate_stringlist(val)\n for idx, item in enumerate(val):\n if not isinstance(item, dict):\n elements = [x.strip() for x in item.split(':')]\n num_elements = len(elements)\n if num_elements < expected_num_elements:\n if fill is NOTSET:\n raise SaltInvocationError(\n '\\'{0}\\' contains {1} value(s) (expected {2})'.format(\n item, num_elements, expected_num_elements\n )\n )\n elements.extend([fill] * (expected_num_elements - num_elements))\n elif num_elements > expected_num_elements:\n raise SaltInvocationError(\n '\\'{0}\\' contains {1} value(s) (expected {2})'.format(\n item,\n num_elements,\n expected_num_elements if fill is NOTSET\n else 'up to {0}'.format(expected_num_elements)\n )\n )\n val[idx] = dict(zip(names, elements))\n return val\n"
] |
# -*- coding: utf-8 -*-
'''
Functions to translate input in the docker CLI format to the format desired by
by the API.
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
# Import Salt libs
import salt.utils.data
import salt.utils.network
from salt.exceptions import SaltInvocationError
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import range, zip # pylint: disable=import-error,redefined-builtin
NOTSET = object()
def split(item, sep=',', maxsplit=-1):
return [x.strip() for x in item.split(sep, maxsplit)]
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_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 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 validate_ip(val):
try:
if not salt.utils.network.is_ip(val):
raise SaltInvocationError(
'\'{0}\' is not a valid IP address'.format(val)
)
except RuntimeError:
pass
def validate_subnet(val):
try:
if not salt.utils.network.is_subnet(val):
raise SaltInvocationError(
'\'{0}\' is not a valid subnet'.format(val)
)
except RuntimeError:
pass
def translate_str(val):
return six.text_type(val) if not isinstance(val, six.string_types) else val
def translate_int(val):
if not isinstance(val, six.integer_types):
try:
val = int(val)
except (TypeError, ValueError):
raise SaltInvocationError('\'{0}\' is not an integer'.format(val))
return val
def translate_bool(val):
return bool(val) if not isinstance(val, bool) else val
def translate_dict(val):
'''
Not really translating, just raising an exception if it's not a dict
'''
if not isinstance(val, dict):
raise SaltInvocationError('\'{0}\' is not a dictionary'.format(val))
return val
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_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_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_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_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
|
saltstack/salt
|
salt/utils/docker/translate/helpers.py
|
translate_key_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
|
CLI input is a list of key/val pairs, but the API expects a dictionary in
the format {key: val}
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/docker/translate/helpers.py#L260-L277
|
[
"def split(item, sep=',', maxsplit=-1):\n return [x.strip() for x in item.split(sep, maxsplit)]\n",
"def translate_stringlist(val):\n '''\n On the CLI, these are passed as multiple instances of a given CLI option.\n In Salt, we accept these as a comma-delimited list but the API expects a\n Python list. This function accepts input and returns it back as a Python\n list of strings. If the input is a string which is a comma-separated list\n of items, split that string and return it.\n '''\n if not isinstance(val, list):\n try:\n val = split(val)\n except AttributeError:\n val = split(six.text_type(val))\n for idx in range(len(val)):\n if not isinstance(val[idx], six.string_types):\n val[idx] = six.text_type(val[idx])\n return val\n"
] |
# -*- coding: utf-8 -*-
'''
Functions to translate input in the docker CLI format to the format desired by
by the API.
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
# Import Salt libs
import salt.utils.data
import salt.utils.network
from salt.exceptions import SaltInvocationError
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import range, zip # pylint: disable=import-error,redefined-builtin
NOTSET = object()
def split(item, sep=',', maxsplit=-1):
return [x.strip() for x in item.split(sep, maxsplit)]
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_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 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 validate_ip(val):
try:
if not salt.utils.network.is_ip(val):
raise SaltInvocationError(
'\'{0}\' is not a valid IP address'.format(val)
)
except RuntimeError:
pass
def validate_subnet(val):
try:
if not salt.utils.network.is_subnet(val):
raise SaltInvocationError(
'\'{0}\' is not a valid subnet'.format(val)
)
except RuntimeError:
pass
def translate_str(val):
return six.text_type(val) if not isinstance(val, six.string_types) else val
def translate_int(val):
if not isinstance(val, six.integer_types):
try:
val = int(val)
except (TypeError, ValueError):
raise SaltInvocationError('\'{0}\' is not an integer'.format(val))
return val
def translate_bool(val):
return bool(val) if not isinstance(val, bool) else val
def translate_dict(val):
'''
Not really translating, just raising an exception if it's not a dict
'''
if not isinstance(val, dict):
raise SaltInvocationError('\'{0}\' is not a dictionary'.format(val))
return val
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_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_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_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_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
|
saltstack/salt
|
salt/utils/docker/translate/helpers.py
|
translate_labels
|
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
|
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.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/docker/translate/helpers.py#L280-L308
|
[
"def split(item, sep=',', maxsplit=-1):\n return [x.strip() for x in item.split(sep, maxsplit)]\n"
] |
# -*- coding: utf-8 -*-
'''
Functions to translate input in the docker CLI format to the format desired by
by the API.
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
# Import Salt libs
import salt.utils.data
import salt.utils.network
from salt.exceptions import SaltInvocationError
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import range, zip # pylint: disable=import-error,redefined-builtin
NOTSET = object()
def split(item, sep=',', maxsplit=-1):
return [x.strip() for x in item.split(sep, maxsplit)]
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_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 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 validate_ip(val):
try:
if not salt.utils.network.is_ip(val):
raise SaltInvocationError(
'\'{0}\' is not a valid IP address'.format(val)
)
except RuntimeError:
pass
def validate_subnet(val):
try:
if not salt.utils.network.is_subnet(val):
raise SaltInvocationError(
'\'{0}\' is not a valid subnet'.format(val)
)
except RuntimeError:
pass
def translate_str(val):
return six.text_type(val) if not isinstance(val, six.string_types) else val
def translate_int(val):
if not isinstance(val, six.integer_types):
try:
val = int(val)
except (TypeError, ValueError):
raise SaltInvocationError('\'{0}\' is not an integer'.format(val))
return val
def translate_bool(val):
return bool(val) if not isinstance(val, bool) else val
def translate_dict(val):
'''
Not really translating, just raising an exception if it's not a dict
'''
if not isinstance(val, dict):
raise SaltInvocationError('\'{0}\' is not a dictionary'.format(val))
return val
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_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_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_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_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
|
saltstack/salt
|
salt/states/firewall.py
|
check
|
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
|
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'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/firewall.py#L19-L67
| null |
# -*- coding: utf-8 -*-
'''
State to check firewall configurations
.. versionadded:: 2016.3.0
'''
from __future__ import absolute_import, print_function, unicode_literals
def __virtual__():
'''
Load only if network is loaded
'''
return 'firewall' if 'network.connect' in __salt__ else False
|
saltstack/salt
|
salt/states/selinux.py
|
_refine_mode
|
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'
|
Return a mode value that is predictable
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/selinux.py#L41-L56
| null |
# -*- coding: utf-8 -*-
'''
Management of SELinux rules
===========================
If SELinux is available for the running system, the mode can be managed and
booleans can be set.
.. code-block:: yaml
enforcing:
selinux.mode
samba_create_home_dirs:
selinux.boolean:
- value: True
- persist: True
nginx:
selinux.module:
- enabled: False
.. note::
Use of these states require that the :mod:`selinux <salt.modules.selinux>`
execution module is available.
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
# Import 3rd party libs
from salt.ext import six
def __virtual__():
'''
Only make this state available if the selinux module is available.
'''
return 'selinux' if 'selinux.getenforce' in __salt__ else False
def _refine_value(value):
'''
Return a yes/no value, or None if the input is invalid
'''
value = six.text_type(value).lower()
if value in ('1', 'on', 'yes', 'true'):
return 'on'
if value in ('0', 'off', 'no', 'false'):
return 'off'
return None
def _refine_module_state(module_state):
'''
Return a predictable value, or allow us to error out
.. versionadded:: 2016.3.0
'''
module_state = six.text_type(module_state).lower()
if module_state in ('1', 'on', 'yes', 'true', 'enabled'):
return 'enabled'
if module_state in ('0', 'off', 'no', 'false', 'disabled'):
return 'disabled'
return 'unknown'
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 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 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_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_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 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_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_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 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_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
|
saltstack/salt
|
salt/states/selinux.py
|
mode
|
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
|
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.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/selinux.py#L84-L133
|
[
"def _refine_mode(mode):\n '''\n Return a mode value that is predictable\n '''\n mode = six.text_type(mode).lower()\n if any([mode.startswith('e'),\n mode == '1',\n mode == 'on']):\n return 'Enforcing'\n if any([mode.startswith('p'),\n mode == '0',\n mode == 'off']):\n return 'Permissive'\n if any([mode.startswith('d')]):\n return 'Disabled'\n return 'unknown'\n"
] |
# -*- coding: utf-8 -*-
'''
Management of SELinux rules
===========================
If SELinux is available for the running system, the mode can be managed and
booleans can be set.
.. code-block:: yaml
enforcing:
selinux.mode
samba_create_home_dirs:
selinux.boolean:
- value: True
- persist: True
nginx:
selinux.module:
- enabled: False
.. note::
Use of these states require that the :mod:`selinux <salt.modules.selinux>`
execution module is available.
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
# Import 3rd party libs
from salt.ext import six
def __virtual__():
'''
Only make this state available if the selinux module is available.
'''
return 'selinux' if 'selinux.getenforce' in __salt__ else False
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_value(value):
'''
Return a yes/no value, or None if the input is invalid
'''
value = six.text_type(value).lower()
if value in ('1', 'on', 'yes', 'true'):
return 'on'
if value in ('0', 'off', 'no', 'false'):
return 'off'
return None
def _refine_module_state(module_state):
'''
Return a predictable value, or allow us to error out
.. versionadded:: 2016.3.0
'''
module_state = six.text_type(module_state).lower()
if module_state in ('1', 'on', 'yes', 'true', 'enabled'):
return 'enabled'
if module_state in ('0', 'off', 'no', 'false', 'disabled'):
return 'disabled'
return 'unknown'
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 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_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_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 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_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_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 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_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
|
saltstack/salt
|
salt/states/selinux.py
|
boolean
|
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
|
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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/selinux.py#L136-L191
|
[
"def _refine_value(value):\n '''\n Return a yes/no value, or None if the input is invalid\n '''\n value = six.text_type(value).lower()\n if value in ('1', 'on', 'yes', 'true'):\n return 'on'\n if value in ('0', 'off', 'no', 'false'):\n return 'off'\n return None\n"
] |
# -*- coding: utf-8 -*-
'''
Management of SELinux rules
===========================
If SELinux is available for the running system, the mode can be managed and
booleans can be set.
.. code-block:: yaml
enforcing:
selinux.mode
samba_create_home_dirs:
selinux.boolean:
- value: True
- persist: True
nginx:
selinux.module:
- enabled: False
.. note::
Use of these states require that the :mod:`selinux <salt.modules.selinux>`
execution module is available.
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
# Import 3rd party libs
from salt.ext import six
def __virtual__():
'''
Only make this state available if the selinux module is available.
'''
return 'selinux' if 'selinux.getenforce' in __salt__ else False
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_value(value):
'''
Return a yes/no value, or None if the input is invalid
'''
value = six.text_type(value).lower()
if value in ('1', 'on', 'yes', 'true'):
return 'on'
if value in ('0', 'off', 'no', 'false'):
return 'off'
return None
def _refine_module_state(module_state):
'''
Return a predictable value, or allow us to error out
.. versionadded:: 2016.3.0
'''
module_state = six.text_type(module_state).lower()
if module_state in ('1', 'on', 'yes', 'true', 'enabled'):
return 'enabled'
if module_state in ('0', 'off', 'no', 'false', 'disabled'):
return 'disabled'
return 'unknown'
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 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_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_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 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_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_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 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_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
|
saltstack/salt
|
salt/states/selinux.py
|
module
|
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
|
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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/selinux.py#L194-L268
| null |
# -*- coding: utf-8 -*-
'''
Management of SELinux rules
===========================
If SELinux is available for the running system, the mode can be managed and
booleans can be set.
.. code-block:: yaml
enforcing:
selinux.mode
samba_create_home_dirs:
selinux.boolean:
- value: True
- persist: True
nginx:
selinux.module:
- enabled: False
.. note::
Use of these states require that the :mod:`selinux <salt.modules.selinux>`
execution module is available.
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
# Import 3rd party libs
from salt.ext import six
def __virtual__():
'''
Only make this state available if the selinux module is available.
'''
return 'selinux' if 'selinux.getenforce' in __salt__ else False
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_value(value):
'''
Return a yes/no value, or None if the input is invalid
'''
value = six.text_type(value).lower()
if value in ('1', 'on', 'yes', 'true'):
return 'on'
if value in ('0', 'off', 'no', 'false'):
return 'off'
return None
def _refine_module_state(module_state):
'''
Return a predictable value, or allow us to error out
.. versionadded:: 2016.3.0
'''
module_state = six.text_type(module_state).lower()
if module_state in ('1', 'on', 'yes', 'true', 'enabled'):
return 'enabled'
if module_state in ('0', 'off', 'no', 'false', 'disabled'):
return 'disabled'
return 'unknown'
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 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 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_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 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_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_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 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_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
|
saltstack/salt
|
salt/states/selinux.py
|
module_install
|
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
|
Installs custom SELinux module from given file
name
Path to file with module to install
.. versionadded:: 2016.11.6
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/selinux.py#L271-L289
| null |
# -*- coding: utf-8 -*-
'''
Management of SELinux rules
===========================
If SELinux is available for the running system, the mode can be managed and
booleans can be set.
.. code-block:: yaml
enforcing:
selinux.mode
samba_create_home_dirs:
selinux.boolean:
- value: True
- persist: True
nginx:
selinux.module:
- enabled: False
.. note::
Use of these states require that the :mod:`selinux <salt.modules.selinux>`
execution module is available.
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
# Import 3rd party libs
from salt.ext import six
def __virtual__():
'''
Only make this state available if the selinux module is available.
'''
return 'selinux' if 'selinux.getenforce' in __salt__ else False
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_value(value):
'''
Return a yes/no value, or None if the input is invalid
'''
value = six.text_type(value).lower()
if value in ('1', 'on', 'yes', 'true'):
return 'on'
if value in ('0', 'off', 'no', 'false'):
return 'off'
return None
def _refine_module_state(module_state):
'''
Return a predictable value, or allow us to error out
.. versionadded:: 2016.3.0
'''
module_state = six.text_type(module_state).lower()
if module_state in ('1', 'on', 'yes', 'true', 'enabled'):
return 'enabled'
if module_state in ('0', 'off', 'no', 'false', 'disabled'):
return 'disabled'
return 'unknown'
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 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 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_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 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_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_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 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_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
|
saltstack/salt
|
salt/states/selinux.py
|
module_remove
|
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
|
Removes SELinux module
name
The name of the module to remove
.. versionadded:: 2016.11.6
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/selinux.py#L292-L315
| null |
# -*- coding: utf-8 -*-
'''
Management of SELinux rules
===========================
If SELinux is available for the running system, the mode can be managed and
booleans can be set.
.. code-block:: yaml
enforcing:
selinux.mode
samba_create_home_dirs:
selinux.boolean:
- value: True
- persist: True
nginx:
selinux.module:
- enabled: False
.. note::
Use of these states require that the :mod:`selinux <salt.modules.selinux>`
execution module is available.
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
# Import 3rd party libs
from salt.ext import six
def __virtual__():
'''
Only make this state available if the selinux module is available.
'''
return 'selinux' if 'selinux.getenforce' in __salt__ else False
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_value(value):
'''
Return a yes/no value, or None if the input is invalid
'''
value = six.text_type(value).lower()
if value in ('1', 'on', 'yes', 'true'):
return 'on'
if value in ('0', 'off', 'no', 'false'):
return 'off'
return None
def _refine_module_state(module_state):
'''
Return a predictable value, or allow us to error out
.. versionadded:: 2016.3.0
'''
module_state = six.text_type(module_state).lower()
if module_state in ('1', 'on', 'yes', 'true', 'enabled'):
return 'enabled'
if module_state in ('0', 'off', 'no', 'false', 'disabled'):
return 'disabled'
return 'unknown'
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 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 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_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 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_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_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 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_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
|
saltstack/salt
|
salt/states/selinux.py
|
fcontext_policy_present
|
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
|
.. 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.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/selinux.py#L318-L396
| null |
# -*- coding: utf-8 -*-
'''
Management of SELinux rules
===========================
If SELinux is available for the running system, the mode can be managed and
booleans can be set.
.. code-block:: yaml
enforcing:
selinux.mode
samba_create_home_dirs:
selinux.boolean:
- value: True
- persist: True
nginx:
selinux.module:
- enabled: False
.. note::
Use of these states require that the :mod:`selinux <salt.modules.selinux>`
execution module is available.
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
# Import 3rd party libs
from salt.ext import six
def __virtual__():
'''
Only make this state available if the selinux module is available.
'''
return 'selinux' if 'selinux.getenforce' in __salt__ else False
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_value(value):
'''
Return a yes/no value, or None if the input is invalid
'''
value = six.text_type(value).lower()
if value in ('1', 'on', 'yes', 'true'):
return 'on'
if value in ('0', 'off', 'no', 'false'):
return 'off'
return None
def _refine_module_state(module_state):
'''
Return a predictable value, or allow us to error out
.. versionadded:: 2016.3.0
'''
module_state = six.text_type(module_state).lower()
if module_state in ('1', 'on', 'yes', 'true', 'enabled'):
return 'enabled'
if module_state in ('0', 'off', 'no', 'false', 'disabled'):
return 'disabled'
return 'unknown'
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 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 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_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_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 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_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 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_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
|
saltstack/salt
|
salt/states/selinux.py
|
fcontext_policy_absent
|
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
|
.. 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.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/selinux.py#L399-L455
| null |
# -*- coding: utf-8 -*-
'''
Management of SELinux rules
===========================
If SELinux is available for the running system, the mode can be managed and
booleans can be set.
.. code-block:: yaml
enforcing:
selinux.mode
samba_create_home_dirs:
selinux.boolean:
- value: True
- persist: True
nginx:
selinux.module:
- enabled: False
.. note::
Use of these states require that the :mod:`selinux <salt.modules.selinux>`
execution module is available.
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
# Import 3rd party libs
from salt.ext import six
def __virtual__():
'''
Only make this state available if the selinux module is available.
'''
return 'selinux' if 'selinux.getenforce' in __salt__ else False
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_value(value):
'''
Return a yes/no value, or None if the input is invalid
'''
value = six.text_type(value).lower()
if value in ('1', 'on', 'yes', 'true'):
return 'on'
if value in ('0', 'off', 'no', 'false'):
return 'off'
return None
def _refine_module_state(module_state):
'''
Return a predictable value, or allow us to error out
.. versionadded:: 2016.3.0
'''
module_state = six.text_type(module_state).lower()
if module_state in ('1', 'on', 'yes', 'true', 'enabled'):
return 'enabled'
if module_state in ('0', 'off', 'no', 'false', 'disabled'):
return 'disabled'
return 'unknown'
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 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 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_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_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 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_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 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_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
|
saltstack/salt
|
salt/states/selinux.py
|
fcontext_policy_applied
|
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
|
.. versionadded:: 2017.7.0
Checks and makes sure the SELinux policies for a given filespec are
applied.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/selinux.py#L458-L481
| null |
# -*- coding: utf-8 -*-
'''
Management of SELinux rules
===========================
If SELinux is available for the running system, the mode can be managed and
booleans can be set.
.. code-block:: yaml
enforcing:
selinux.mode
samba_create_home_dirs:
selinux.boolean:
- value: True
- persist: True
nginx:
selinux.module:
- enabled: False
.. note::
Use of these states require that the :mod:`selinux <salt.modules.selinux>`
execution module is available.
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
# Import 3rd party libs
from salt.ext import six
def __virtual__():
'''
Only make this state available if the selinux module is available.
'''
return 'selinux' if 'selinux.getenforce' in __salt__ else False
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_value(value):
'''
Return a yes/no value, or None if the input is invalid
'''
value = six.text_type(value).lower()
if value in ('1', 'on', 'yes', 'true'):
return 'on'
if value in ('0', 'off', 'no', 'false'):
return 'off'
return None
def _refine_module_state(module_state):
'''
Return a predictable value, or allow us to error out
.. versionadded:: 2016.3.0
'''
module_state = six.text_type(module_state).lower()
if module_state in ('1', 'on', 'yes', 'true', 'enabled'):
return 'enabled'
if module_state in ('0', 'off', 'no', 'false', 'disabled'):
return 'disabled'
return 'unknown'
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 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 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_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_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 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_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 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_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
|
saltstack/salt
|
salt/states/selinux.py
|
port_policy_present
|
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
|
.. 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.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/selinux.py#L484-L536
| null |
# -*- coding: utf-8 -*-
'''
Management of SELinux rules
===========================
If SELinux is available for the running system, the mode can be managed and
booleans can be set.
.. code-block:: yaml
enforcing:
selinux.mode
samba_create_home_dirs:
selinux.boolean:
- value: True
- persist: True
nginx:
selinux.module:
- enabled: False
.. note::
Use of these states require that the :mod:`selinux <salt.modules.selinux>`
execution module is available.
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
# Import 3rd party libs
from salt.ext import six
def __virtual__():
'''
Only make this state available if the selinux module is available.
'''
return 'selinux' if 'selinux.getenforce' in __salt__ else False
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_value(value):
'''
Return a yes/no value, or None if the input is invalid
'''
value = six.text_type(value).lower()
if value in ('1', 'on', 'yes', 'true'):
return 'on'
if value in ('0', 'off', 'no', 'false'):
return 'off'
return None
def _refine_module_state(module_state):
'''
Return a predictable value, or allow us to error out
.. versionadded:: 2016.3.0
'''
module_state = six.text_type(module_state).lower()
if module_state in ('1', 'on', 'yes', 'true', 'enabled'):
return 'enabled'
if module_state in ('0', 'off', 'no', 'false', 'disabled'):
return 'disabled'
return 'unknown'
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 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 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_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_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 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_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_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 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
|
saltstack/salt
|
salt/states/selinux.py
|
port_policy_absent
|
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
|
.. 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.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/selinux.py#L539-L587
| null |
# -*- coding: utf-8 -*-
'''
Management of SELinux rules
===========================
If SELinux is available for the running system, the mode can be managed and
booleans can be set.
.. code-block:: yaml
enforcing:
selinux.mode
samba_create_home_dirs:
selinux.boolean:
- value: True
- persist: True
nginx:
selinux.module:
- enabled: False
.. note::
Use of these states require that the :mod:`selinux <salt.modules.selinux>`
execution module is available.
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
# Import 3rd party libs
from salt.ext import six
def __virtual__():
'''
Only make this state available if the selinux module is available.
'''
return 'selinux' if 'selinux.getenforce' in __salt__ else False
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_value(value):
'''
Return a yes/no value, or None if the input is invalid
'''
value = six.text_type(value).lower()
if value in ('1', 'on', 'yes', 'true'):
return 'on'
if value in ('0', 'off', 'no', 'false'):
return 'off'
return None
def _refine_module_state(module_state):
'''
Return a predictable value, or allow us to error out
.. versionadded:: 2016.3.0
'''
module_state = six.text_type(module_state).lower()
if module_state in ('1', 'on', 'yes', 'true', 'enabled'):
return 'enabled'
if module_state in ('0', 'off', 'no', 'false', 'disabled'):
return 'disabled'
return 'unknown'
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 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 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_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_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 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_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_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 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
|
saltstack/salt
|
salt/states/openstack_config.py
|
present
|
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
|
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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/openstack_config.py#L33-L90
| null |
# -*- coding: utf-8 -*-
'''
Manage OpenStack configuration file settings.
:maintainer: Jeffrey C. Ollie <jeff@ocjtech.us>
:maturity: new
:depends:
:platform: linux
'''
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
# Import Salt Libs
from salt.ext import six
from salt.exceptions import CommandExecutionError
def __virtual__():
'''
Only load if the openstack_config module is in __salt__
'''
if 'openstack_config.get' not in __salt__:
return False
if 'openstack_config.set' not in __salt__:
return False
if 'openstack_config.delete' not in __salt__:
return False
return True
def absent(name, filename, section, parameter=None):
'''
Ensure a value is not 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.
'''
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)
except CommandExecutionError as err:
if six.text_type(err).lower().startswith('parameter not found:'):
ret['result'] = True
ret['comment'] = 'The value is already absent'
return ret
raise
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Value \'{0}\' is set to be deleted.'.format(
old_value
)
return ret
__salt__['openstack_config.delete'](filename=filename,
section=section,
parameter=parameter)
ret['changes'] = {'Value': 'Deleted'}
ret['result'] = True
ret['comment'] = 'The value has been deleted'
return ret
|
saltstack/salt
|
salt/states/azurearm_compute.py
|
availability_set_present
|
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
|
.. 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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/azurearm_compute.py#L104-L263
| null |
# -*- coding: utf-8 -*-
'''
Azure (ARM) Compute State Module
.. versionadded:: 2019.2.0
:maintainer: <devops@decisionlab.io>
:maturity: new
:depends:
* `azure <https://pypi.python.org/pypi/azure>`_ >= 2.0.0
* `azure-common <https://pypi.python.org/pypi/azure-common>`_ >= 1.1.8
* `azure-mgmt <https://pypi.python.org/pypi/azure-mgmt>`_ >= 1.0.0
* `azure-mgmt-compute <https://pypi.python.org/pypi/azure-mgmt-compute>`_ >= 1.0.0
* `azure-mgmt-network <https://pypi.python.org/pypi/azure-mgmt-network>`_ >= 1.7.1
* `azure-mgmt-resource <https://pypi.python.org/pypi/azure-mgmt-resource>`_ >= 1.1.0
* `azure-mgmt-storage <https://pypi.python.org/pypi/azure-mgmt-storage>`_ >= 1.0.0
* `azure-mgmt-web <https://pypi.python.org/pypi/azure-mgmt-web>`_ >= 0.32.0
* `azure-storage <https://pypi.python.org/pypi/azure-storage>`_ >= 0.34.3
* `msrestazure <https://pypi.python.org/pypi/msrestazure>`_ >= 0.4.21
:platform: linux
:configuration: This module requires Azure Resource Manager credentials to be passed as a dictionary of
keyword arguments to the ``connection_auth`` parameter in order to work properly. Since the authentication
parameters are sensitive, it's recommended to pass them to the states via pillar.
Required provider parameters:
if using username and password:
* ``subscription_id``
* ``username``
* ``password``
if using a service principal:
* ``subscription_id``
* ``tenant``
* ``client_id``
* ``secret``
Optional provider parameters:
**cloud_environment**: Used to point the cloud driver to different API endpoints, such as Azure GovCloud. Possible values:
* ``AZURE_PUBLIC_CLOUD`` (default)
* ``AZURE_CHINA_CLOUD``
* ``AZURE_US_GOV_CLOUD``
* ``AZURE_GERMAN_CLOUD``
Example Pillar for Azure Resource Manager authentication:
.. code-block:: yaml
azurearm:
user_pass_auth:
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
username: fletch
password: 123pass
mysubscription:
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
tenant: ABCDEFAB-1234-ABCD-1234-ABCDEFABCDEF
client_id: ABCDEFAB-1234-ABCD-1234-ABCDEFABCDEF
secret: XXXXXXXXXXXXXXXXXXXXXXXX
cloud_environment: AZURE_PUBLIC_CLOUD
Example states using Azure Resource Manager authentication:
.. code-block:: jinja
{% set profile = salt['pillar.get']('azurearm:mysubscription') %}
Ensure availability set exists:
azurearm_compute.availability_set_present:
- name: my_avail_set
- resource_group: my_rg
- virtual_machines:
- my_vm1
- my_vm2
- tags:
how_awesome: very
contact_name: Elmer Fudd Gantry
- connection_auth: {{ profile }}
Ensure availability set is absent:
azurearm_compute.availability_set_absent:
- name: other_avail_set
- resource_group: my_rg
- connection_auth: {{ profile }}
'''
# Python libs
from __future__ import absolute_import
import logging
__virtualname__ = 'azurearm_compute'
log = logging.getLogger(__name__)
def __virtual__():
'''
Only make this state available if the azurearm_compute module is available.
'''
return __virtualname__ if 'azurearm_compute.availability_set_create_or_update' in __salt__ else False
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
|
saltstack/salt
|
salt/states/azurearm_compute.py
|
availability_set_absent
|
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
|
.. 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.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/azurearm_compute.py#L266-L326
| null |
# -*- coding: utf-8 -*-
'''
Azure (ARM) Compute State Module
.. versionadded:: 2019.2.0
:maintainer: <devops@decisionlab.io>
:maturity: new
:depends:
* `azure <https://pypi.python.org/pypi/azure>`_ >= 2.0.0
* `azure-common <https://pypi.python.org/pypi/azure-common>`_ >= 1.1.8
* `azure-mgmt <https://pypi.python.org/pypi/azure-mgmt>`_ >= 1.0.0
* `azure-mgmt-compute <https://pypi.python.org/pypi/azure-mgmt-compute>`_ >= 1.0.0
* `azure-mgmt-network <https://pypi.python.org/pypi/azure-mgmt-network>`_ >= 1.7.1
* `azure-mgmt-resource <https://pypi.python.org/pypi/azure-mgmt-resource>`_ >= 1.1.0
* `azure-mgmt-storage <https://pypi.python.org/pypi/azure-mgmt-storage>`_ >= 1.0.0
* `azure-mgmt-web <https://pypi.python.org/pypi/azure-mgmt-web>`_ >= 0.32.0
* `azure-storage <https://pypi.python.org/pypi/azure-storage>`_ >= 0.34.3
* `msrestazure <https://pypi.python.org/pypi/msrestazure>`_ >= 0.4.21
:platform: linux
:configuration: This module requires Azure Resource Manager credentials to be passed as a dictionary of
keyword arguments to the ``connection_auth`` parameter in order to work properly. Since the authentication
parameters are sensitive, it's recommended to pass them to the states via pillar.
Required provider parameters:
if using username and password:
* ``subscription_id``
* ``username``
* ``password``
if using a service principal:
* ``subscription_id``
* ``tenant``
* ``client_id``
* ``secret``
Optional provider parameters:
**cloud_environment**: Used to point the cloud driver to different API endpoints, such as Azure GovCloud. Possible values:
* ``AZURE_PUBLIC_CLOUD`` (default)
* ``AZURE_CHINA_CLOUD``
* ``AZURE_US_GOV_CLOUD``
* ``AZURE_GERMAN_CLOUD``
Example Pillar for Azure Resource Manager authentication:
.. code-block:: yaml
azurearm:
user_pass_auth:
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
username: fletch
password: 123pass
mysubscription:
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
tenant: ABCDEFAB-1234-ABCD-1234-ABCDEFABCDEF
client_id: ABCDEFAB-1234-ABCD-1234-ABCDEFABCDEF
secret: XXXXXXXXXXXXXXXXXXXXXXXX
cloud_environment: AZURE_PUBLIC_CLOUD
Example states using Azure Resource Manager authentication:
.. code-block:: jinja
{% set profile = salt['pillar.get']('azurearm:mysubscription') %}
Ensure availability set exists:
azurearm_compute.availability_set_present:
- name: my_avail_set
- resource_group: my_rg
- virtual_machines:
- my_vm1
- my_vm2
- tags:
how_awesome: very
contact_name: Elmer Fudd Gantry
- connection_auth: {{ profile }}
Ensure availability set is absent:
azurearm_compute.availability_set_absent:
- name: other_avail_set
- resource_group: my_rg
- connection_auth: {{ profile }}
'''
# Python libs
from __future__ import absolute_import
import logging
__virtualname__ = 'azurearm_compute'
log = logging.getLogger(__name__)
def __virtual__():
'''
Only make this state available if the azurearm_compute module is available.
'''
return __virtualname__ if 'azurearm_compute.availability_set_create_or_update' in __salt__ else False
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
|
saltstack/salt
|
salt/grains/fibre_channel.py
|
_linux_wwns
|
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
|
Return Fibre Channel port WWNs from a Linux host.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/grains/fibre_channel.py#L38-L48
|
[
"def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n"
] |
# -*- coding: utf-8 -*-
'''
Grains for Fibre Channel WWN's. On Windows this runs a PowerShell command that
queries WMI to get the Fibre Channel WWN's available.
.. versionadded:: 2018.3.0
To enable these grains set ``fibre_channel_grains: True``.
.. code-block:: yaml
fibre_channel_grains: True
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import glob
import logging
# Import Salt libs
import salt.modules.cmdmod
import salt.utils.platform
import salt.utils.files
__virtualname__ = 'fibre_channel'
# Get logging started
log = logging.getLogger(__name__)
def __virtual__():
if __opts__.get('fibre_channel_grains', False) is False:
return False
else:
return __virtualname__
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 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
|
saltstack/salt
|
salt/grains/fibre_channel.py
|
_windows_wwns
|
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
|
Return Fibre Channel port WWNs from a Windows host.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/grains/fibre_channel.py#L51-L64
|
[
"def powershell(cmd,\n cwd=None,\n stdin=None,\n runas=None,\n shell=DEFAULT_SHELL,\n env=None,\n clean_env=False,\n template=None,\n rstrip=True,\n umask=None,\n output_encoding=None,\n output_loglevel='debug',\n hide_output=False,\n timeout=None,\n reset_system_locale=True,\n ignore_retcode=False,\n saltenv='base',\n use_vt=False,\n password=None,\n depth=None,\n encode_cmd=False,\n success_retcodes=None,\n success_stdout=None,\n success_stderr=None,\n **kwargs):\n '''\n Execute the passed PowerShell command and return the output as a dictionary.\n\n Other ``cmd.*`` functions (besides ``cmd.powershell_all``)\n return the raw text output of the command. This\n function appends ``| ConvertTo-JSON`` to the command and then parses the\n JSON into a Python dictionary. If you want the raw textual result of your\n PowerShell command you should use ``cmd.run`` with the ``shell=powershell``\n option.\n\n For example:\n\n .. code-block:: bash\n\n salt '*' cmd.run '$PSVersionTable.CLRVersion' shell=powershell\n salt '*' cmd.run 'Get-NetTCPConnection' shell=powershell\n\n .. versionadded:: 2016.3.0\n\n .. warning::\n\n This passes the cmd argument directly to PowerShell\n without any further processing! Be absolutely sure that you\n have properly sanitized the command passed to this function\n and do not use untrusted inputs.\n\n In addition to the normal ``cmd.run`` parameters, this command offers the\n ``depth`` parameter to change the Windows default depth for the\n ``ConvertTo-JSON`` powershell command. The Windows default is 2. If you need\n more depth, set that here.\n\n .. note::\n For some commands, setting the depth to a value greater than 4 greatly\n increases the time it takes for the command to return and in many cases\n returns useless data.\n\n :param str cmd: The powershell command to run.\n\n :param str cwd: The directory from which to execute the command. Defaults\n to the home directory of the user specified by ``runas`` (or the user\n under which Salt is running if ``runas`` is not specified).\n\n :param str stdin: A string of standard input can be specified for the\n command to be run using the ``stdin`` parameter. This can be useful in cases\n where sensitive information must be read from standard input.\n\n :param str runas: Specify an alternate user to run the command. The default\n behavior is to run as the user under which Salt is running. If running\n on a Windows minion you must also use the ``password`` argument, and\n the target user account must be in the Administrators group.\n\n :param str password: Windows only. Required when specifying ``runas``. This\n parameter will be ignored on non-Windows platforms.\n\n .. versionadded:: 2016.3.0\n\n :param str shell: Specify an alternate shell. Defaults to the system's\n default shell.\n\n :param bool python_shell: If False, let python handle the positional\n arguments. Set to True to use shell features, such as pipes or\n redirection.\n\n :param dict env: Environment variables to be set prior to execution.\n\n .. note::\n When passing environment variables on the CLI, they should be\n passed as the string representation of a dictionary.\n\n .. code-block:: bash\n\n salt myminion cmd.powershell 'some command' env='{\"FOO\": \"bar\"}'\n\n :param bool clean_env: Attempt to clean out all other shell environment\n variables and set only those provided in the 'env' argument to this\n function.\n\n :param str template: If this setting is applied then the named templating\n engine will be used to render the downloaded file. Currently jinja,\n mako, and wempy are supported.\n\n :param bool rstrip: Strip all whitespace off the end of output before it is\n returned.\n\n :param str umask: The umask (in octal) to use when running the command.\n\n :param str output_encoding: Control the encoding used to decode the\n command's output.\n\n .. note::\n This should not need to be used in most cases. By default, Salt\n will try to use the encoding detected from the system locale, and\n will fall back to UTF-8 if this fails. This should only need to be\n used in cases where the output of the command is encoded in\n something other than the system locale or UTF-8.\n\n To see the encoding Salt has detected from the system locale, check\n the `locale` line in the output of :py:func:`test.versions_report\n <salt.modules.test.versions_report>`.\n\n .. versionadded:: 2018.3.0\n\n :param str output_loglevel: Control the loglevel at which the output from\n the command is logged to the minion log.\n\n .. note::\n The command being run will still be logged at the ``debug``\n loglevel regardless, unless ``quiet`` is used for this value.\n\n :param bool ignore_retcode: If the exit code of the command is nonzero,\n this is treated as an error condition, and the output from the command\n will be logged to the minion log. However, there are some cases where\n programs use the return code for signaling and a nonzero exit code\n doesn't necessarily mean failure. Pass this argument as ``True`` to\n skip logging the output if the command has a nonzero exit code.\n\n :param bool hide_output: If ``True``, suppress stdout and stderr in the\n return data.\n\n .. note::\n This is separate from ``output_loglevel``, which only handles how\n Salt logs to the minion log.\n\n .. versionadded:: 2018.3.0\n\n :param int timeout: A timeout in seconds for the executed process to return.\n\n :param bool use_vt: Use VT utils (saltstack) to stream the command output\n more interactively to the console and the logs. This is experimental.\n\n :param bool reset_system_locale: Resets the system locale\n\n :param str saltenv: The salt environment to use. Default is 'base'\n\n :param int depth: The number of levels of contained objects to be included.\n Default is 2. Values greater than 4 seem to greatly increase the time\n it takes for the command to complete for some commands. eg: ``dir``\n\n .. versionadded:: 2016.3.4\n\n :param bool encode_cmd: Encode the command before executing. Use in cases\n where characters may be dropped or incorrectly converted when executed.\n Default is False.\n\n :param list success_retcodes: This parameter will be allow a list of\n non-zero return codes that should be considered a success. If the\n return code returned from the run matches any in the provided list,\n the return code will be overridden with zero.\n\n .. versionadded:: 2019.2.0\n\n :param list success_stdout: This parameter will be allow a list of\n strings that when found in standard out should be considered a success.\n If stdout returned from the run matches any in the provided list,\n the return code will be overridden with zero.\n\n .. versionadded:: Neon\n\n :param list success_stderr: This parameter will be allow a list of\n strings that when found in standard error should be considered a success.\n If stderr returned from the run matches any in the provided list,\n the return code will be overridden with zero.\n\n .. versionadded:: Neon\n\n :param bool stdin_raw_newlines: False\n If ``True``, Salt will not automatically convert the characters ``\\\\n``\n present in the ``stdin`` value to newlines.\n\n .. versionadded:: 2019.2.0\n\n :returns:\n :dict: A dictionary of data returned by the powershell command.\n\n CLI Example:\n\n .. code-block:: powershell\n\n salt '*' cmd.powershell \"$PSVersionTable.CLRVersion\"\n '''\n if 'python_shell' in kwargs:\n python_shell = kwargs.pop('python_shell')\n else:\n python_shell = True\n\n # Append PowerShell Object formatting\n # ConvertTo-JSON is only available on PowerShell 3.0 and later\n psversion = shell_info('powershell')['psversion']\n if salt.utils.versions.version_cmp(psversion, '2.0') == 1:\n cmd += ' | ConvertTo-JSON'\n if depth is not None:\n cmd += ' -Depth {0}'.format(depth)\n\n if encode_cmd:\n # Convert the cmd to UTF-16LE without a BOM and base64 encode.\n # Just base64 encoding UTF-8 or including a BOM is not valid.\n log.debug('Encoding PowerShell command \\'%s\\'', cmd)\n cmd_utf16 = cmd.decode('utf-8').encode('utf-16le')\n cmd = base64.standard_b64encode(cmd_utf16)\n encoded_cmd = True\n else:\n encoded_cmd = False\n\n # Put the whole command inside a try / catch block\n # Some errors in PowerShell are not \"Terminating Errors\" and will not be\n # caught in a try/catch block. For example, the `Get-WmiObject` command will\n # often return a \"Non Terminating Error\". To fix this, make sure\n # `-ErrorAction Stop` is set in the powershell command\n cmd = 'try {' + cmd + '} catch { \"{}\" }'\n\n # Retrieve the response, while overriding shell with 'powershell'\n response = run(cmd,\n cwd=cwd,\n stdin=stdin,\n runas=runas,\n shell='powershell',\n env=env,\n clean_env=clean_env,\n template=template,\n rstrip=rstrip,\n umask=umask,\n output_encoding=output_encoding,\n output_loglevel=output_loglevel,\n hide_output=hide_output,\n timeout=timeout,\n reset_system_locale=reset_system_locale,\n ignore_retcode=ignore_retcode,\n saltenv=saltenv,\n use_vt=use_vt,\n python_shell=python_shell,\n password=password,\n encoded_cmd=encoded_cmd,\n success_retcodes=success_retcodes,\n success_stdout=success_stdout,\n success_stderr=success_stderr,\n **kwargs)\n\n try:\n return salt.utils.json.loads(response)\n except Exception:\n log.error(\"Error converting PowerShell JSON return\", exc_info=True)\n return {}\n"
] |
# -*- coding: utf-8 -*-
'''
Grains for Fibre Channel WWN's. On Windows this runs a PowerShell command that
queries WMI to get the Fibre Channel WWN's available.
.. versionadded:: 2018.3.0
To enable these grains set ``fibre_channel_grains: True``.
.. code-block:: yaml
fibre_channel_grains: True
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import glob
import logging
# Import Salt libs
import salt.modules.cmdmod
import salt.utils.platform
import salt.utils.files
__virtualname__ = 'fibre_channel'
# Get logging started
log = logging.getLogger(__name__)
def __virtual__():
if __opts__.get('fibre_channel_grains', False) is False:
return False
else:
return __virtualname__
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 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
|
saltstack/salt
|
salt/grains/fibre_channel.py
|
fibre_channel_wwns
|
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
|
Return list of fiber channel HBA WWNs
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/grains/fibre_channel.py#L67-L76
|
[
"def _linux_wwns():\n '''\n Return Fibre Channel port WWNs from a Linux host.\n '''\n ret = []\n for fc_file in glob.glob('/sys/class/fc_host/*/port_name'):\n with salt.utils.files.fopen(fc_file, 'r') as _wwn:\n content = _wwn.read()\n for line in content.splitlines():\n ret.append(line.rstrip()[2:])\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Grains for Fibre Channel WWN's. On Windows this runs a PowerShell command that
queries WMI to get the Fibre Channel WWN's available.
.. versionadded:: 2018.3.0
To enable these grains set ``fibre_channel_grains: True``.
.. code-block:: yaml
fibre_channel_grains: True
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import glob
import logging
# Import Salt libs
import salt.modules.cmdmod
import salt.utils.platform
import salt.utils.files
__virtualname__ = 'fibre_channel'
# Get logging started
log = logging.getLogger(__name__)
def __virtual__():
if __opts__.get('fibre_channel_grains', False) is False:
return False
else:
return __virtualname__
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 _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
|
saltstack/salt
|
salt/utils/vsan.py
|
vsan_supported
|
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
|
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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/vsan.py#L85-L107
| null |
# -*- coding: utf-8 -*-
'''
Connection library for VMware vSAN endpoint
This library used the vSAN extension of the VMware SDK
used to manage vSAN related objects
:codeauthor: Alexandru Bleotu <alexandru.bleotu@morganstaley.com>
Dependencies
~~~~~~~~~~~~
- pyVmomi Python Module
pyVmomi
-------
PyVmomi can be installed via pip:
.. code-block:: bash
pip install pyVmomi
.. note::
versions of Python. If using version 6.0 of pyVmomi, Python 2.6,
Python 2.7.9, or newer must be present. This is due to an upstream dependency
in pyVmomi 6.0 that is not supported in Python versions 2.7 to 2.7.8. If the
version of Python is not in the supported range, you will need to install an
earlier version of pyVmomi. See `Issue #29537`_ for more information.
.. _Issue #29537: https://github.com/saltstack/salt/issues/29537
Based on the note above, to install an earlier version of pyVmomi than the
version currently listed in PyPi, run the following:
.. code-block:: bash
pip install pyVmomi==5.5.0.2014.1.1
The 5.5.0.2014.1.1 is a known stable version that this original VMware utils file
was developed against.
'''
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
import sys
import logging
import ssl
# Import Salt Libs
from salt.ext import six
from salt.exceptions import VMwareApiError, VMwareRuntimeError, \
VMwareObjectRetrievalError
import salt.utils.vmware
try:
from pyVmomi import vim, vmodl
HAS_PYVMOMI = True
except ImportError:
HAS_PYVMOMI = False
try:
from salt.ext.vsan import vsanapiutils
HAS_PYVSAN = True
except ImportError:
HAS_PYVSAN = False
# Get Logging Started
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load if PyVmomi is installed.
'''
if HAS_PYVSAN and HAS_PYVMOMI:
return True
else:
return False, 'Missing dependency: The salt.utils.vsan module ' \
'requires pyvmomi and the pyvsan extension library'
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_disk_management_system(service_instance):
'''
Returns a vim.VimClusterVsanVcDiskManagementSystem 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-disk-management-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']
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 add_capacity_to_diskgroup(service_instance, vsan_disk_mgmt_system,
host_ref, diskgroup, new_capacity_disks):
'''
Adds capacity disk(s) to 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
diskgroup
The vsan.HostDiskMapping object representing the host's diskgroup where
the additional capacity needs to be added
new_capacity_disks
List of vim.HostScsiDisk objects representing the disks to be added as
capacity disks. Can be either ssd or non-ssd. There must be a minimum
of 1 new capacity disk in the list.
'''
hostname = salt.utils.vmware.get_managed_object_name(host_ref)
cache_disk = diskgroup.ssd
cache_disk_id = cache_disk.canonicalName
log.debug(
'Adding capacity to disk group with cache disk \'%s\' on host \'%s\'',
cache_disk_id, hostname
)
log.trace(
'new_capacity_disk_ids = %s',
[c.canonicalName for c in new_capacity_disks]
)
spec = vim.VimVsanHostDiskMappingCreationSpec()
spec.cacheDisks = [cache_disk]
spec.capacityDisks = new_capacity_disks
# All new capacity disks must be either ssd or non-ssd (mixed disks are not
# supported); also they need to match the type of the existing capacity
# disks; we assume disks are already validated
spec.creationType = 'allFlash' if getattr(new_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:
raise VMwareRuntimeError(exc.msg)
_wait_for_tasks([task], service_instance)
return True
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_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 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 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 _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]))
|
saltstack/salt
|
salt/utils/vsan.py
|
get_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']
|
Returns a vim.cluster.VsanVcClusterConfigSystem object
service_instance
Service instance to the host or vCenter
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/vsan.py#L110-L131
|
[
"def GetVsanVcMos(vcStub, context=None):\n vsanStub = GetVsanVcStub(vcStub, context)\n vcMos = {\n 'vsan-disk-management-system' : vim.cluster.VsanVcDiskManagementSystem(\n 'vsan-disk-management-system',\n vsanStub\n ),\n 'vsan-stretched-cluster-system' : vim.cluster.VsanVcStretchedClusterSystem(\n 'vsan-stretched-cluster-system',\n vsanStub\n ),\n 'vsan-cluster-config-system' : vim.cluster.VsanVcClusterConfigSystem(\n 'vsan-cluster-config-system',\n vsanStub\n ),\n 'vsan-performance-manager' : vim.cluster.VsanPerformanceManager(\n 'vsan-performance-manager',\n vsanStub\n ),\n 'vsan-cluster-health-system' : vim.cluster.VsanVcClusterHealthSystem(\n 'vsan-cluster-health-system',\n vsanStub\n ),\n 'vsan-upgrade-systemex' : vim.VsanUpgradeSystemEx(\n 'vsan-upgrade-systemex',\n vsanStub\n ),\n 'vsan-cluster-space-report-system' : vim.cluster.VsanSpaceReportSystem(\n 'vsan-cluster-space-report-system',\n vsanStub\n ),\n\n 'vsan-cluster-object-system' : vim.cluster.VsanObjectSystem(\n 'vsan-cluster-object-system',\n vsanStub\n ),\n }\n\n return vcMos\n"
] |
# -*- coding: utf-8 -*-
'''
Connection library for VMware vSAN endpoint
This library used the vSAN extension of the VMware SDK
used to manage vSAN related objects
:codeauthor: Alexandru Bleotu <alexandru.bleotu@morganstaley.com>
Dependencies
~~~~~~~~~~~~
- pyVmomi Python Module
pyVmomi
-------
PyVmomi can be installed via pip:
.. code-block:: bash
pip install pyVmomi
.. note::
versions of Python. If using version 6.0 of pyVmomi, Python 2.6,
Python 2.7.9, or newer must be present. This is due to an upstream dependency
in pyVmomi 6.0 that is not supported in Python versions 2.7 to 2.7.8. If the
version of Python is not in the supported range, you will need to install an
earlier version of pyVmomi. See `Issue #29537`_ for more information.
.. _Issue #29537: https://github.com/saltstack/salt/issues/29537
Based on the note above, to install an earlier version of pyVmomi than the
version currently listed in PyPi, run the following:
.. code-block:: bash
pip install pyVmomi==5.5.0.2014.1.1
The 5.5.0.2014.1.1 is a known stable version that this original VMware utils file
was developed against.
'''
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
import sys
import logging
import ssl
# Import Salt Libs
from salt.ext import six
from salt.exceptions import VMwareApiError, VMwareRuntimeError, \
VMwareObjectRetrievalError
import salt.utils.vmware
try:
from pyVmomi import vim, vmodl
HAS_PYVMOMI = True
except ImportError:
HAS_PYVMOMI = False
try:
from salt.ext.vsan import vsanapiutils
HAS_PYVSAN = True
except ImportError:
HAS_PYVSAN = False
# Get Logging Started
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load if PyVmomi is installed.
'''
if HAS_PYVSAN and HAS_PYVMOMI:
return True
else:
return False, 'Missing dependency: The salt.utils.vsan module ' \
'requires pyvmomi and the pyvsan extension library'
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 get_vsan_disk_management_system(service_instance):
'''
Returns a vim.VimClusterVsanVcDiskManagementSystem 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-disk-management-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']
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 add_capacity_to_diskgroup(service_instance, vsan_disk_mgmt_system,
host_ref, diskgroup, new_capacity_disks):
'''
Adds capacity disk(s) to 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
diskgroup
The vsan.HostDiskMapping object representing the host's diskgroup where
the additional capacity needs to be added
new_capacity_disks
List of vim.HostScsiDisk objects representing the disks to be added as
capacity disks. Can be either ssd or non-ssd. There must be a minimum
of 1 new capacity disk in the list.
'''
hostname = salt.utils.vmware.get_managed_object_name(host_ref)
cache_disk = diskgroup.ssd
cache_disk_id = cache_disk.canonicalName
log.debug(
'Adding capacity to disk group with cache disk \'%s\' on host \'%s\'',
cache_disk_id, hostname
)
log.trace(
'new_capacity_disk_ids = %s',
[c.canonicalName for c in new_capacity_disks]
)
spec = vim.VimVsanHostDiskMappingCreationSpec()
spec.cacheDisks = [cache_disk]
spec.capacityDisks = new_capacity_disks
# All new capacity disks must be either ssd or non-ssd (mixed disks are not
# supported); also they need to match the type of the existing capacity
# disks; we assume disks are already validated
spec.creationType = 'allFlash' if getattr(new_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:
raise VMwareRuntimeError(exc.msg)
_wait_for_tasks([task], service_instance)
return True
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_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 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 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 _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]))
|
saltstack/salt
|
salt/utils/vsan.py
|
get_host_vsan_system
|
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']
|
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.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/vsan.py#L158-L184
|
[
"def get_mors_with_properties(service_instance, object_type, property_list=None,\n container_ref=None, traversal_spec=None,\n local_properties=False):\n '''\n Returns a list containing properties and managed object references for the managed object.\n\n service_instance\n The Service Instance from which to obtain managed object references.\n\n object_type\n The type of content for which to obtain managed object references.\n\n property_list\n An optional list of object properties used to return even more filtered managed object reference results.\n\n container_ref\n An optional reference to the managed object to search under. Can either be an object of type Folder, Datacenter,\n ComputeResource, Resource Pool or HostSystem. If not specified, default behaviour is to search under the inventory\n rootFolder.\n\n traversal_spec\n An optional TraversalSpec to be used instead of the standard\n ``Traverse All`` spec\n\n local_properties\n Flag specigying whether the properties to be retrieved are local to the\n container. If that is the case, the traversal spec needs to be None.\n '''\n # Get all the content\n content_args = [service_instance, object_type]\n content_kwargs = {'property_list': property_list,\n 'container_ref': container_ref,\n 'traversal_spec': traversal_spec,\n 'local_properties': local_properties}\n try:\n content = get_content(*content_args, **content_kwargs)\n except BadStatusLine:\n content = get_content(*content_args, **content_kwargs)\n except IOError as exc:\n if exc.errno != errno.EPIPE:\n raise exc\n content = get_content(*content_args, **content_kwargs)\n\n object_list = []\n for obj in content:\n properties = {}\n for prop in obj.propSet:\n properties[prop.name] = prop.val\n properties['object'] = obj.obj\n object_list.append(properties)\n log.trace('Retrieved %s objects', len(object_list))\n return object_list\n",
"def get_managed_object_name(mo_ref):\n '''\n Returns the name of a managed object.\n If the name wasn't found, it returns None.\n\n mo_ref\n The managed object reference.\n '''\n props = get_properties_of_managed_object(mo_ref, ['name'])\n return props.get('name')\n"
] |
# -*- coding: utf-8 -*-
'''
Connection library for VMware vSAN endpoint
This library used the vSAN extension of the VMware SDK
used to manage vSAN related objects
:codeauthor: Alexandru Bleotu <alexandru.bleotu@morganstaley.com>
Dependencies
~~~~~~~~~~~~
- pyVmomi Python Module
pyVmomi
-------
PyVmomi can be installed via pip:
.. code-block:: bash
pip install pyVmomi
.. note::
versions of Python. If using version 6.0 of pyVmomi, Python 2.6,
Python 2.7.9, or newer must be present. This is due to an upstream dependency
in pyVmomi 6.0 that is not supported in Python versions 2.7 to 2.7.8. If the
version of Python is not in the supported range, you will need to install an
earlier version of pyVmomi. See `Issue #29537`_ for more information.
.. _Issue #29537: https://github.com/saltstack/salt/issues/29537
Based on the note above, to install an earlier version of pyVmomi than the
version currently listed in PyPi, run the following:
.. code-block:: bash
pip install pyVmomi==5.5.0.2014.1.1
The 5.5.0.2014.1.1 is a known stable version that this original VMware utils file
was developed against.
'''
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
import sys
import logging
import ssl
# Import Salt Libs
from salt.ext import six
from salt.exceptions import VMwareApiError, VMwareRuntimeError, \
VMwareObjectRetrievalError
import salt.utils.vmware
try:
from pyVmomi import vim, vmodl
HAS_PYVMOMI = True
except ImportError:
HAS_PYVMOMI = False
try:
from salt.ext.vsan import vsanapiutils
HAS_PYVSAN = True
except ImportError:
HAS_PYVSAN = False
# Get Logging Started
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load if PyVmomi is installed.
'''
if HAS_PYVSAN and HAS_PYVMOMI:
return True
else:
return False, 'Missing dependency: The salt.utils.vsan module ' \
'requires pyvmomi and the pyvsan extension library'
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 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_disk_management_system(service_instance):
'''
Returns a vim.VimClusterVsanVcDiskManagementSystem 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-disk-management-system']
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 add_capacity_to_diskgroup(service_instance, vsan_disk_mgmt_system,
host_ref, diskgroup, new_capacity_disks):
'''
Adds capacity disk(s) to 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
diskgroup
The vsan.HostDiskMapping object representing the host's diskgroup where
the additional capacity needs to be added
new_capacity_disks
List of vim.HostScsiDisk objects representing the disks to be added as
capacity disks. Can be either ssd or non-ssd. There must be a minimum
of 1 new capacity disk in the list.
'''
hostname = salt.utils.vmware.get_managed_object_name(host_ref)
cache_disk = diskgroup.ssd
cache_disk_id = cache_disk.canonicalName
log.debug(
'Adding capacity to disk group with cache disk \'%s\' on host \'%s\'',
cache_disk_id, hostname
)
log.trace(
'new_capacity_disk_ids = %s',
[c.canonicalName for c in new_capacity_disks]
)
spec = vim.VimVsanHostDiskMappingCreationSpec()
spec.cacheDisks = [cache_disk]
spec.capacityDisks = new_capacity_disks
# All new capacity disks must be either ssd or non-ssd (mixed disks are not
# supported); also they need to match the type of the existing capacity
# disks; we assume disks are already validated
spec.creationType = 'allFlash' if getattr(new_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:
raise VMwareRuntimeError(exc.msg)
_wait_for_tasks([task], service_instance)
return True
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_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 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 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 _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]))
|
saltstack/salt
|
salt/utils/vsan.py
|
create_diskgroup
|
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
|
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.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/vsan.py#L187-L242
|
[
"def get_managed_object_name(mo_ref):\n '''\n Returns the name of a managed object.\n If the name wasn't found, it returns None.\n\n mo_ref\n The managed object reference.\n '''\n props = get_properties_of_managed_object(mo_ref, ['name'])\n return props.get('name')\n",
"def _wait_for_tasks(tasks, service_instance):\n '''\n Wait for tasks created via the VSAN API\n '''\n log.trace('Waiting for vsan tasks: {0}',\n ', '.join([six.text_type(t) for t in tasks]))\n try:\n vsanapiutils.WaitForTasks(tasks, service_instance)\n except vim.fault.NoPermission as exc:\n log.exception(exc)\n raise VMwareApiError('Not enough permissions. Required privilege: '\n '{0}'.format(exc.privilegeId))\n except vim.fault.VimFault as exc:\n log.exception(exc)\n raise VMwareApiError(exc.msg)\n except vmodl.RuntimeFault as exc:\n log.exception(exc)\n raise VMwareRuntimeError(exc.msg)\n log.trace('Tasks %s finished successfully',\n ', '.join([six.text_type(t) for t in tasks]))\n"
] |
# -*- coding: utf-8 -*-
'''
Connection library for VMware vSAN endpoint
This library used the vSAN extension of the VMware SDK
used to manage vSAN related objects
:codeauthor: Alexandru Bleotu <alexandru.bleotu@morganstaley.com>
Dependencies
~~~~~~~~~~~~
- pyVmomi Python Module
pyVmomi
-------
PyVmomi can be installed via pip:
.. code-block:: bash
pip install pyVmomi
.. note::
versions of Python. If using version 6.0 of pyVmomi, Python 2.6,
Python 2.7.9, or newer must be present. This is due to an upstream dependency
in pyVmomi 6.0 that is not supported in Python versions 2.7 to 2.7.8. If the
version of Python is not in the supported range, you will need to install an
earlier version of pyVmomi. See `Issue #29537`_ for more information.
.. _Issue #29537: https://github.com/saltstack/salt/issues/29537
Based on the note above, to install an earlier version of pyVmomi than the
version currently listed in PyPi, run the following:
.. code-block:: bash
pip install pyVmomi==5.5.0.2014.1.1
The 5.5.0.2014.1.1 is a known stable version that this original VMware utils file
was developed against.
'''
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
import sys
import logging
import ssl
# Import Salt Libs
from salt.ext import six
from salt.exceptions import VMwareApiError, VMwareRuntimeError, \
VMwareObjectRetrievalError
import salt.utils.vmware
try:
from pyVmomi import vim, vmodl
HAS_PYVMOMI = True
except ImportError:
HAS_PYVMOMI = False
try:
from salt.ext.vsan import vsanapiutils
HAS_PYVSAN = True
except ImportError:
HAS_PYVSAN = False
# Get Logging Started
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load if PyVmomi is installed.
'''
if HAS_PYVSAN and HAS_PYVMOMI:
return True
else:
return False, 'Missing dependency: The salt.utils.vsan module ' \
'requires pyvmomi and the pyvsan extension library'
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 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_disk_management_system(service_instance):
'''
Returns a vim.VimClusterVsanVcDiskManagementSystem 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-disk-management-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']
def add_capacity_to_diskgroup(service_instance, vsan_disk_mgmt_system,
host_ref, diskgroup, new_capacity_disks):
'''
Adds capacity disk(s) to 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
diskgroup
The vsan.HostDiskMapping object representing the host's diskgroup where
the additional capacity needs to be added
new_capacity_disks
List of vim.HostScsiDisk objects representing the disks to be added as
capacity disks. Can be either ssd or non-ssd. There must be a minimum
of 1 new capacity disk in the list.
'''
hostname = salt.utils.vmware.get_managed_object_name(host_ref)
cache_disk = diskgroup.ssd
cache_disk_id = cache_disk.canonicalName
log.debug(
'Adding capacity to disk group with cache disk \'%s\' on host \'%s\'',
cache_disk_id, hostname
)
log.trace(
'new_capacity_disk_ids = %s',
[c.canonicalName for c in new_capacity_disks]
)
spec = vim.VimVsanHostDiskMappingCreationSpec()
spec.cacheDisks = [cache_disk]
spec.capacityDisks = new_capacity_disks
# All new capacity disks must be either ssd or non-ssd (mixed disks are not
# supported); also they need to match the type of the existing capacity
# disks; we assume disks are already validated
spec.creationType = 'allFlash' if getattr(new_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:
raise VMwareRuntimeError(exc.msg)
_wait_for_tasks([task], service_instance)
return True
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_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 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 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 _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]))
|
saltstack/salt
|
salt/utils/vsan.py
|
remove_capacity_from_diskgroup
|
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
|
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.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/vsan.py#L308-L379
|
[
"def wait_for_task(task, instance_name, task_type, sleep_seconds=1, log_level='debug'):\n '''\n Waits for a task to be completed.\n\n task\n The task to wait for.\n\n instance_name\n The name of the ESXi host, vCenter Server, or Virtual Machine that\n the task is being run on.\n\n task_type\n The type of task being performed. Useful information for debugging purposes.\n\n sleep_seconds\n The number of seconds to wait before querying the task again.\n Defaults to ``1`` second.\n\n log_level\n The level at which to log task information. Default is ``debug``,\n but ``info`` is also supported.\n '''\n time_counter = 0\n start_time = time.time()\n log.trace('task = %s, task_type = %s', task, task.__class__.__name__)\n try:\n task_info = task.info\n except vim.fault.NoPermission as exc:\n log.exception(exc)\n raise salt.exceptions.VMwareApiError(\n 'Not enough permissions. Required privilege: '\n '{}'.format(exc.privilegeId))\n except vim.fault.FileNotFound as exc:\n log.exception(exc)\n raise salt.exceptions.VMwareFileNotFoundError(exc.msg)\n except vim.fault.VimFault as exc:\n log.exception(exc)\n raise salt.exceptions.VMwareApiError(exc.msg)\n except vmodl.RuntimeFault as exc:\n log.exception(exc)\n raise salt.exceptions.VMwareRuntimeError(exc.msg)\n while task_info.state == 'running' or task_info.state == 'queued':\n if time_counter % sleep_seconds == 0:\n msg = '[ {0} ] Waiting for {1} task to finish [{2} s]'.format(\n instance_name, task_type, time_counter)\n if log_level == 'info':\n log.info(msg)\n else:\n log.debug(msg)\n time.sleep(1.0 - ((time.time() - start_time) % 1.0))\n time_counter += 1\n try:\n task_info = task.info\n except vim.fault.NoPermission as exc:\n log.exception(exc)\n raise salt.exceptions.VMwareApiError(\n 'Not enough permissions. Required privilege: '\n '{}'.format(exc.privilegeId))\n except vim.fault.FileNotFound as exc:\n log.exception(exc)\n raise salt.exceptions.VMwareFileNotFoundError(exc.msg)\n except vim.fault.VimFault as exc:\n log.exception(exc)\n raise salt.exceptions.VMwareApiError(exc.msg)\n except vmodl.RuntimeFault as exc:\n log.exception(exc)\n raise salt.exceptions.VMwareRuntimeError(exc.msg)\n if task_info.state == 'success':\n msg = '[ {0} ] Successfully completed {1} task in {2} seconds'.format(\n instance_name, task_type, time_counter)\n if log_level == 'info':\n log.info(msg)\n else:\n log.debug(msg)\n # task is in a successful state\n return task_info.result\n else:\n # task is in an error state\n try:\n raise task_info.error\n except vim.fault.NoPermission as exc:\n log.exception(exc)\n raise salt.exceptions.VMwareApiError(\n 'Not enough permissions. Required privilege: '\n '{}'.format(exc.privilegeId))\n except vim.fault.FileNotFound as exc:\n log.exception(exc)\n raise salt.exceptions.VMwareFileNotFoundError(exc.msg)\n except vim.fault.VimFault as exc:\n log.exception(exc)\n raise salt.exceptions.VMwareApiError(exc.msg)\n except vmodl.fault.SystemError as exc:\n log.exception(exc)\n raise salt.exceptions.VMwareSystemError(exc.msg)\n except vmodl.fault.InvalidArgument as exc:\n log.exception(exc)\n exc_message = exc.msg\n if exc.faultMessage:\n exc_message = '{0} ({1})'.format(exc_message,\n exc.faultMessage[0].message)\n raise salt.exceptions.VMwareApiError(exc_message)\n",
"def get_managed_object_name(mo_ref):\n '''\n Returns the name of a managed object.\n If the name wasn't found, it returns None.\n\n mo_ref\n The managed object reference.\n '''\n props = get_properties_of_managed_object(mo_ref, ['name'])\n return props.get('name')\n",
"def get_host_vsan_system(service_instance, host_ref, hostname=None):\n '''\n Returns a host's vsan system\n\n service_instance\n Service instance to the host or vCenter\n\n host_ref\n Refernce to ESXi host\n\n hostname\n Name of ESXi host. Default value is None.\n '''\n if not hostname:\n hostname = salt.utils.vmware.get_managed_object_name(host_ref)\n traversal_spec = vmodl.query.PropertyCollector.TraversalSpec(\n path='configManager.vsanSystem',\n type=vim.HostSystem,\n skip=False)\n objs = salt.utils.vmware.get_mors_with_properties(\n service_instance, vim.HostVsanSystem, property_list=['config.enabled'],\n container_ref=host_ref, traversal_spec=traversal_spec)\n if not objs:\n raise VMwareObjectRetrievalError('Host\\'s \\'{0}\\' VSAN system was '\n 'not retrieved'.format(hostname))\n log.trace('[%s] Retrieved VSAN system', hostname)\n return objs[0]['object']\n"
] |
# -*- coding: utf-8 -*-
'''
Connection library for VMware vSAN endpoint
This library used the vSAN extension of the VMware SDK
used to manage vSAN related objects
:codeauthor: Alexandru Bleotu <alexandru.bleotu@morganstaley.com>
Dependencies
~~~~~~~~~~~~
- pyVmomi Python Module
pyVmomi
-------
PyVmomi can be installed via pip:
.. code-block:: bash
pip install pyVmomi
.. note::
versions of Python. If using version 6.0 of pyVmomi, Python 2.6,
Python 2.7.9, or newer must be present. This is due to an upstream dependency
in pyVmomi 6.0 that is not supported in Python versions 2.7 to 2.7.8. If the
version of Python is not in the supported range, you will need to install an
earlier version of pyVmomi. See `Issue #29537`_ for more information.
.. _Issue #29537: https://github.com/saltstack/salt/issues/29537
Based on the note above, to install an earlier version of pyVmomi than the
version currently listed in PyPi, run the following:
.. code-block:: bash
pip install pyVmomi==5.5.0.2014.1.1
The 5.5.0.2014.1.1 is a known stable version that this original VMware utils file
was developed against.
'''
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
import sys
import logging
import ssl
# Import Salt Libs
from salt.ext import six
from salt.exceptions import VMwareApiError, VMwareRuntimeError, \
VMwareObjectRetrievalError
import salt.utils.vmware
try:
from pyVmomi import vim, vmodl
HAS_PYVMOMI = True
except ImportError:
HAS_PYVMOMI = False
try:
from salt.ext.vsan import vsanapiutils
HAS_PYVSAN = True
except ImportError:
HAS_PYVSAN = False
# Get Logging Started
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load if PyVmomi is installed.
'''
if HAS_PYVSAN and HAS_PYVMOMI:
return True
else:
return False, 'Missing dependency: The salt.utils.vsan module ' \
'requires pyvmomi and the pyvsan extension library'
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 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_disk_management_system(service_instance):
'''
Returns a vim.VimClusterVsanVcDiskManagementSystem 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-disk-management-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']
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 add_capacity_to_diskgroup(service_instance, vsan_disk_mgmt_system,
host_ref, diskgroup, new_capacity_disks):
'''
Adds capacity disk(s) to 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
diskgroup
The vsan.HostDiskMapping object representing the host's diskgroup where
the additional capacity needs to be added
new_capacity_disks
List of vim.HostScsiDisk objects representing the disks to be added as
capacity disks. Can be either ssd or non-ssd. There must be a minimum
of 1 new capacity disk in the list.
'''
hostname = salt.utils.vmware.get_managed_object_name(host_ref)
cache_disk = diskgroup.ssd
cache_disk_id = cache_disk.canonicalName
log.debug(
'Adding capacity to disk group with cache disk \'%s\' on host \'%s\'',
cache_disk_id, hostname
)
log.trace(
'new_capacity_disk_ids = %s',
[c.canonicalName for c in new_capacity_disks]
)
spec = vim.VimVsanHostDiskMappingCreationSpec()
spec.cacheDisks = [cache_disk]
spec.capacityDisks = new_capacity_disks
# All new capacity disks must be either ssd or non-ssd (mixed disks are not
# supported); also they need to match the type of the existing capacity
# disks; we assume disks are already validated
spec.creationType = 'allFlash' if getattr(new_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:
raise VMwareRuntimeError(exc.msg)
_wait_for_tasks([task], service_instance)
return True
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 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 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 _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]))
|
saltstack/salt
|
salt/utils/vsan.py
|
remove_diskgroup
|
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
|
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.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/vsan.py#L382-L440
|
[
"def wait_for_task(task, instance_name, task_type, sleep_seconds=1, log_level='debug'):\n '''\n Waits for a task to be completed.\n\n task\n The task to wait for.\n\n instance_name\n The name of the ESXi host, vCenter Server, or Virtual Machine that\n the task is being run on.\n\n task_type\n The type of task being performed. Useful information for debugging purposes.\n\n sleep_seconds\n The number of seconds to wait before querying the task again.\n Defaults to ``1`` second.\n\n log_level\n The level at which to log task information. Default is ``debug``,\n but ``info`` is also supported.\n '''\n time_counter = 0\n start_time = time.time()\n log.trace('task = %s, task_type = %s', task, task.__class__.__name__)\n try:\n task_info = task.info\n except vim.fault.NoPermission as exc:\n log.exception(exc)\n raise salt.exceptions.VMwareApiError(\n 'Not enough permissions. Required privilege: '\n '{}'.format(exc.privilegeId))\n except vim.fault.FileNotFound as exc:\n log.exception(exc)\n raise salt.exceptions.VMwareFileNotFoundError(exc.msg)\n except vim.fault.VimFault as exc:\n log.exception(exc)\n raise salt.exceptions.VMwareApiError(exc.msg)\n except vmodl.RuntimeFault as exc:\n log.exception(exc)\n raise salt.exceptions.VMwareRuntimeError(exc.msg)\n while task_info.state == 'running' or task_info.state == 'queued':\n if time_counter % sleep_seconds == 0:\n msg = '[ {0} ] Waiting for {1} task to finish [{2} s]'.format(\n instance_name, task_type, time_counter)\n if log_level == 'info':\n log.info(msg)\n else:\n log.debug(msg)\n time.sleep(1.0 - ((time.time() - start_time) % 1.0))\n time_counter += 1\n try:\n task_info = task.info\n except vim.fault.NoPermission as exc:\n log.exception(exc)\n raise salt.exceptions.VMwareApiError(\n 'Not enough permissions. Required privilege: '\n '{}'.format(exc.privilegeId))\n except vim.fault.FileNotFound as exc:\n log.exception(exc)\n raise salt.exceptions.VMwareFileNotFoundError(exc.msg)\n except vim.fault.VimFault as exc:\n log.exception(exc)\n raise salt.exceptions.VMwareApiError(exc.msg)\n except vmodl.RuntimeFault as exc:\n log.exception(exc)\n raise salt.exceptions.VMwareRuntimeError(exc.msg)\n if task_info.state == 'success':\n msg = '[ {0} ] Successfully completed {1} task in {2} seconds'.format(\n instance_name, task_type, time_counter)\n if log_level == 'info':\n log.info(msg)\n else:\n log.debug(msg)\n # task is in a successful state\n return task_info.result\n else:\n # task is in an error state\n try:\n raise task_info.error\n except vim.fault.NoPermission as exc:\n log.exception(exc)\n raise salt.exceptions.VMwareApiError(\n 'Not enough permissions. Required privilege: '\n '{}'.format(exc.privilegeId))\n except vim.fault.FileNotFound as exc:\n log.exception(exc)\n raise salt.exceptions.VMwareFileNotFoundError(exc.msg)\n except vim.fault.VimFault as exc:\n log.exception(exc)\n raise salt.exceptions.VMwareApiError(exc.msg)\n except vmodl.fault.SystemError as exc:\n log.exception(exc)\n raise salt.exceptions.VMwareSystemError(exc.msg)\n except vmodl.fault.InvalidArgument as exc:\n log.exception(exc)\n exc_message = exc.msg\n if exc.faultMessage:\n exc_message = '{0} ({1})'.format(exc_message,\n exc.faultMessage[0].message)\n raise salt.exceptions.VMwareApiError(exc_message)\n",
"def get_managed_object_name(mo_ref):\n '''\n Returns the name of a managed object.\n If the name wasn't found, it returns None.\n\n mo_ref\n The managed object reference.\n '''\n props = get_properties_of_managed_object(mo_ref, ['name'])\n return props.get('name')\n",
"def get_host_vsan_system(service_instance, host_ref, hostname=None):\n '''\n Returns a host's vsan system\n\n service_instance\n Service instance to the host or vCenter\n\n host_ref\n Refernce to ESXi host\n\n hostname\n Name of ESXi host. Default value is None.\n '''\n if not hostname:\n hostname = salt.utils.vmware.get_managed_object_name(host_ref)\n traversal_spec = vmodl.query.PropertyCollector.TraversalSpec(\n path='configManager.vsanSystem',\n type=vim.HostSystem,\n skip=False)\n objs = salt.utils.vmware.get_mors_with_properties(\n service_instance, vim.HostVsanSystem, property_list=['config.enabled'],\n container_ref=host_ref, traversal_spec=traversal_spec)\n if not objs:\n raise VMwareObjectRetrievalError('Host\\'s \\'{0}\\' VSAN system was '\n 'not retrieved'.format(hostname))\n log.trace('[%s] Retrieved VSAN system', hostname)\n return objs[0]['object']\n"
] |
# -*- coding: utf-8 -*-
'''
Connection library for VMware vSAN endpoint
This library used the vSAN extension of the VMware SDK
used to manage vSAN related objects
:codeauthor: Alexandru Bleotu <alexandru.bleotu@morganstaley.com>
Dependencies
~~~~~~~~~~~~
- pyVmomi Python Module
pyVmomi
-------
PyVmomi can be installed via pip:
.. code-block:: bash
pip install pyVmomi
.. note::
versions of Python. If using version 6.0 of pyVmomi, Python 2.6,
Python 2.7.9, or newer must be present. This is due to an upstream dependency
in pyVmomi 6.0 that is not supported in Python versions 2.7 to 2.7.8. If the
version of Python is not in the supported range, you will need to install an
earlier version of pyVmomi. See `Issue #29537`_ for more information.
.. _Issue #29537: https://github.com/saltstack/salt/issues/29537
Based on the note above, to install an earlier version of pyVmomi than the
version currently listed in PyPi, run the following:
.. code-block:: bash
pip install pyVmomi==5.5.0.2014.1.1
The 5.5.0.2014.1.1 is a known stable version that this original VMware utils file
was developed against.
'''
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
import sys
import logging
import ssl
# Import Salt Libs
from salt.ext import six
from salt.exceptions import VMwareApiError, VMwareRuntimeError, \
VMwareObjectRetrievalError
import salt.utils.vmware
try:
from pyVmomi import vim, vmodl
HAS_PYVMOMI = True
except ImportError:
HAS_PYVMOMI = False
try:
from salt.ext.vsan import vsanapiutils
HAS_PYVSAN = True
except ImportError:
HAS_PYVSAN = False
# Get Logging Started
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load if PyVmomi is installed.
'''
if HAS_PYVSAN and HAS_PYVMOMI:
return True
else:
return False, 'Missing dependency: The salt.utils.vsan module ' \
'requires pyvmomi and the pyvsan extension library'
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 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_disk_management_system(service_instance):
'''
Returns a vim.VimClusterVsanVcDiskManagementSystem 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-disk-management-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']
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 add_capacity_to_diskgroup(service_instance, vsan_disk_mgmt_system,
host_ref, diskgroup, new_capacity_disks):
'''
Adds capacity disk(s) to 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
diskgroup
The vsan.HostDiskMapping object representing the host's diskgroup where
the additional capacity needs to be added
new_capacity_disks
List of vim.HostScsiDisk objects representing the disks to be added as
capacity disks. Can be either ssd or non-ssd. There must be a minimum
of 1 new capacity disk in the list.
'''
hostname = salt.utils.vmware.get_managed_object_name(host_ref)
cache_disk = diskgroup.ssd
cache_disk_id = cache_disk.canonicalName
log.debug(
'Adding capacity to disk group with cache disk \'%s\' on host \'%s\'',
cache_disk_id, hostname
)
log.trace(
'new_capacity_disk_ids = %s',
[c.canonicalName for c in new_capacity_disks]
)
spec = vim.VimVsanHostDiskMappingCreationSpec()
spec.cacheDisks = [cache_disk]
spec.capacityDisks = new_capacity_disks
# All new capacity disks must be either ssd or non-ssd (mixed disks are not
# supported); also they need to match the type of the existing capacity
# disks; we assume disks are already validated
spec.creationType = 'allFlash' if getattr(new_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:
raise VMwareRuntimeError(exc.msg)
_wait_for_tasks([task], service_instance)
return True
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 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 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 _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]))
|
saltstack/salt
|
salt/utils/vsan.py
|
get_cluster_vsan_info
|
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)
|
Returns the extended cluster vsan configuration object
(vim.VsanConfigInfoEx).
cluster_ref
Reference to the cluster
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/vsan.py#L443-L468
|
[
"def get_managed_object_name(mo_ref):\n '''\n Returns the name of a managed object.\n If the name wasn't found, it returns None.\n\n mo_ref\n The managed object reference.\n '''\n props = get_properties_of_managed_object(mo_ref, ['name'])\n return props.get('name')\n",
"def get_service_instance_from_managed_object(mo_ref, name='<unnamed>'):\n '''\n Retrieves the service instance from a managed object.\n\n me_ref\n Reference to a managed object (of type vim.ManagedEntity).\n\n name\n Name of managed object. This field is optional.\n '''\n if not name:\n name = mo_ref.name\n log.trace('[%s] Retrieving service instance from managed object', name)\n si = vim.ServiceInstance('ServiceInstance')\n si._stub = mo_ref._stub\n return si\n",
"def get_vsan_cluster_config_system(service_instance):\n '''\n Returns a vim.cluster.VsanVcClusterConfigSystem object\n\n service_instance\n Service instance to the host or vCenter\n '''\n\n #TODO Replace when better connection mechanism is available\n\n #For python 2.7.9 and later, the defaul SSL conext has more strict\n #connection handshaking rule. We may need turn of the hostname checking\n #and client side cert verification\n context = None\n if sys.version_info[:3] > (2, 7, 8):\n context = ssl.create_default_context()\n context.check_hostname = False\n context.verify_mode = ssl.CERT_NONE\n\n stub = service_instance._stub\n vc_mos = vsanapiutils.GetVsanVcMos(stub, context=context)\n return vc_mos['vsan-cluster-config-system']\n"
] |
# -*- coding: utf-8 -*-
'''
Connection library for VMware vSAN endpoint
This library used the vSAN extension of the VMware SDK
used to manage vSAN related objects
:codeauthor: Alexandru Bleotu <alexandru.bleotu@morganstaley.com>
Dependencies
~~~~~~~~~~~~
- pyVmomi Python Module
pyVmomi
-------
PyVmomi can be installed via pip:
.. code-block:: bash
pip install pyVmomi
.. note::
versions of Python. If using version 6.0 of pyVmomi, Python 2.6,
Python 2.7.9, or newer must be present. This is due to an upstream dependency
in pyVmomi 6.0 that is not supported in Python versions 2.7 to 2.7.8. If the
version of Python is not in the supported range, you will need to install an
earlier version of pyVmomi. See `Issue #29537`_ for more information.
.. _Issue #29537: https://github.com/saltstack/salt/issues/29537
Based on the note above, to install an earlier version of pyVmomi than the
version currently listed in PyPi, run the following:
.. code-block:: bash
pip install pyVmomi==5.5.0.2014.1.1
The 5.5.0.2014.1.1 is a known stable version that this original VMware utils file
was developed against.
'''
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
import sys
import logging
import ssl
# Import Salt Libs
from salt.ext import six
from salt.exceptions import VMwareApiError, VMwareRuntimeError, \
VMwareObjectRetrievalError
import salt.utils.vmware
try:
from pyVmomi import vim, vmodl
HAS_PYVMOMI = True
except ImportError:
HAS_PYVMOMI = False
try:
from salt.ext.vsan import vsanapiutils
HAS_PYVSAN = True
except ImportError:
HAS_PYVSAN = False
# Get Logging Started
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load if PyVmomi is installed.
'''
if HAS_PYVSAN and HAS_PYVMOMI:
return True
else:
return False, 'Missing dependency: The salt.utils.vsan module ' \
'requires pyvmomi and the pyvsan extension library'
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 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_disk_management_system(service_instance):
'''
Returns a vim.VimClusterVsanVcDiskManagementSystem 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-disk-management-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']
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 add_capacity_to_diskgroup(service_instance, vsan_disk_mgmt_system,
host_ref, diskgroup, new_capacity_disks):
'''
Adds capacity disk(s) to 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
diskgroup
The vsan.HostDiskMapping object representing the host's diskgroup where
the additional capacity needs to be added
new_capacity_disks
List of vim.HostScsiDisk objects representing the disks to be added as
capacity disks. Can be either ssd or non-ssd. There must be a minimum
of 1 new capacity disk in the list.
'''
hostname = salt.utils.vmware.get_managed_object_name(host_ref)
cache_disk = diskgroup.ssd
cache_disk_id = cache_disk.canonicalName
log.debug(
'Adding capacity to disk group with cache disk \'%s\' on host \'%s\'',
cache_disk_id, hostname
)
log.trace(
'new_capacity_disk_ids = %s',
[c.canonicalName for c in new_capacity_disks]
)
spec = vim.VimVsanHostDiskMappingCreationSpec()
spec.cacheDisks = [cache_disk]
spec.capacityDisks = new_capacity_disks
# All new capacity disks must be either ssd or non-ssd (mixed disks are not
# supported); also they need to match the type of the existing capacity
# disks; we assume disks are already validated
spec.creationType = 'allFlash' if getattr(new_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:
raise VMwareRuntimeError(exc.msg)
_wait_for_tasks([task], service_instance)
return True
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_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 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 _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]))
|
saltstack/salt
|
salt/utils/vsan.py
|
reconfigure_cluster_vsan
|
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)
|
Reconfigures the VSAN system of a cluster.
cluster_ref
Reference to the cluster
cluster_vsan_spec
Cluster VSAN reconfigure spec (vim.vsan.ReconfigSpec).
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/vsan.py#L471-L500
|
[
"def get_managed_object_name(mo_ref):\n '''\n Returns the name of a managed object.\n If the name wasn't found, it returns None.\n\n mo_ref\n The managed object reference.\n '''\n props = get_properties_of_managed_object(mo_ref, ['name'])\n return props.get('name')\n",
"def get_service_instance_from_managed_object(mo_ref, name='<unnamed>'):\n '''\n Retrieves the service instance from a managed object.\n\n me_ref\n Reference to a managed object (of type vim.ManagedEntity).\n\n name\n Name of managed object. This field is optional.\n '''\n if not name:\n name = mo_ref.name\n log.trace('[%s] Retrieving service instance from managed object', name)\n si = vim.ServiceInstance('ServiceInstance')\n si._stub = mo_ref._stub\n return si\n",
"def get_vsan_cluster_config_system(service_instance):\n '''\n Returns a vim.cluster.VsanVcClusterConfigSystem object\n\n service_instance\n Service instance to the host or vCenter\n '''\n\n #TODO Replace when better connection mechanism is available\n\n #For python 2.7.9 and later, the defaul SSL conext has more strict\n #connection handshaking rule. We may need turn of the hostname checking\n #and client side cert verification\n context = None\n if sys.version_info[:3] > (2, 7, 8):\n context = ssl.create_default_context()\n context.check_hostname = False\n context.verify_mode = ssl.CERT_NONE\n\n stub = service_instance._stub\n vc_mos = vsanapiutils.GetVsanVcMos(stub, context=context)\n return vc_mos['vsan-cluster-config-system']\n",
"def _wait_for_tasks(tasks, service_instance):\n '''\n Wait for tasks created via the VSAN API\n '''\n log.trace('Waiting for vsan tasks: {0}',\n ', '.join([six.text_type(t) for t in tasks]))\n try:\n vsanapiutils.WaitForTasks(tasks, service_instance)\n except vim.fault.NoPermission as exc:\n log.exception(exc)\n raise VMwareApiError('Not enough permissions. Required privilege: '\n '{0}'.format(exc.privilegeId))\n except vim.fault.VimFault as exc:\n log.exception(exc)\n raise VMwareApiError(exc.msg)\n except vmodl.RuntimeFault as exc:\n log.exception(exc)\n raise VMwareRuntimeError(exc.msg)\n log.trace('Tasks %s finished successfully',\n ', '.join([six.text_type(t) for t in tasks]))\n"
] |
# -*- coding: utf-8 -*-
'''
Connection library for VMware vSAN endpoint
This library used the vSAN extension of the VMware SDK
used to manage vSAN related objects
:codeauthor: Alexandru Bleotu <alexandru.bleotu@morganstaley.com>
Dependencies
~~~~~~~~~~~~
- pyVmomi Python Module
pyVmomi
-------
PyVmomi can be installed via pip:
.. code-block:: bash
pip install pyVmomi
.. note::
versions of Python. If using version 6.0 of pyVmomi, Python 2.6,
Python 2.7.9, or newer must be present. This is due to an upstream dependency
in pyVmomi 6.0 that is not supported in Python versions 2.7 to 2.7.8. If the
version of Python is not in the supported range, you will need to install an
earlier version of pyVmomi. See `Issue #29537`_ for more information.
.. _Issue #29537: https://github.com/saltstack/salt/issues/29537
Based on the note above, to install an earlier version of pyVmomi than the
version currently listed in PyPi, run the following:
.. code-block:: bash
pip install pyVmomi==5.5.0.2014.1.1
The 5.5.0.2014.1.1 is a known stable version that this original VMware utils file
was developed against.
'''
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
import sys
import logging
import ssl
# Import Salt Libs
from salt.ext import six
from salt.exceptions import VMwareApiError, VMwareRuntimeError, \
VMwareObjectRetrievalError
import salt.utils.vmware
try:
from pyVmomi import vim, vmodl
HAS_PYVMOMI = True
except ImportError:
HAS_PYVMOMI = False
try:
from salt.ext.vsan import vsanapiutils
HAS_PYVSAN = True
except ImportError:
HAS_PYVSAN = False
# Get Logging Started
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load if PyVmomi is installed.
'''
if HAS_PYVSAN and HAS_PYVMOMI:
return True
else:
return False, 'Missing dependency: The salt.utils.vsan module ' \
'requires pyvmomi and the pyvsan extension library'
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 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_disk_management_system(service_instance):
'''
Returns a vim.VimClusterVsanVcDiskManagementSystem 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-disk-management-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']
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 add_capacity_to_diskgroup(service_instance, vsan_disk_mgmt_system,
host_ref, diskgroup, new_capacity_disks):
'''
Adds capacity disk(s) to 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
diskgroup
The vsan.HostDiskMapping object representing the host's diskgroup where
the additional capacity needs to be added
new_capacity_disks
List of vim.HostScsiDisk objects representing the disks to be added as
capacity disks. Can be either ssd or non-ssd. There must be a minimum
of 1 new capacity disk in the list.
'''
hostname = salt.utils.vmware.get_managed_object_name(host_ref)
cache_disk = diskgroup.ssd
cache_disk_id = cache_disk.canonicalName
log.debug(
'Adding capacity to disk group with cache disk \'%s\' on host \'%s\'',
cache_disk_id, hostname
)
log.trace(
'new_capacity_disk_ids = %s',
[c.canonicalName for c in new_capacity_disks]
)
spec = vim.VimVsanHostDiskMappingCreationSpec()
spec.cacheDisks = [cache_disk]
spec.capacityDisks = new_capacity_disks
# All new capacity disks must be either ssd or non-ssd (mixed disks are not
# supported); also they need to match the type of the existing capacity
# disks; we assume disks are already validated
spec.creationType = 'allFlash' if getattr(new_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:
raise VMwareRuntimeError(exc.msg)
_wait_for_tasks([task], service_instance)
return True
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_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 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 _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]))
|
saltstack/salt
|
salt/utils/vsan.py
|
_wait_for_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]))
|
Wait for tasks created via the VSAN API
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/vsan.py#L503-L522
|
[
"def WaitForTasks(tasks, si):\n \"\"\"\n Given the service instance si and tasks, it returns after all the\n tasks are complete\n \"\"\"\n\n pc = si.content.propertyCollector\n\n taskList = [str(task) for task in tasks]\n\n # Create filter\n objSpecs = [vmodl.query.PropertyCollector.ObjectSpec(obj=task)\n for task in tasks]\n propSpec = vmodl.query.PropertyCollector.PropertySpec(type=vim.Task,\n pathSet=[], all=True)\n filterSpec = vmodl.query.PropertyCollector.FilterSpec()\n filterSpec.objectSet = objSpecs\n filterSpec.propSet = [propSpec]\n filter = pc.CreateFilter(filterSpec, True)\n\n try:\n version, state = None, None\n\n # Loop looking for updates till the state moves to a completed state.\n while len(taskList):\n update = pc.WaitForUpdates(version)\n for filterSet in update.filterSet:\n for objSet in filterSet.objectSet:\n task = objSet.obj\n for change in objSet.changeSet:\n if change.name == 'info':\n state = change.val.state\n elif change.name == 'info.state':\n state = change.val\n else:\n continue\n\n if not str(task) in taskList:\n continue\n\n if state == vim.TaskInfo.State.success:\n # Remove task from taskList\n taskList.remove(str(task))\n elif state == vim.TaskInfo.State.error:\n raise task.info.error\n # Move to next version\n version = update.version\n finally:\n if filter:\n filter.Destroy()\n"
] |
# -*- coding: utf-8 -*-
'''
Connection library for VMware vSAN endpoint
This library used the vSAN extension of the VMware SDK
used to manage vSAN related objects
:codeauthor: Alexandru Bleotu <alexandru.bleotu@morganstaley.com>
Dependencies
~~~~~~~~~~~~
- pyVmomi Python Module
pyVmomi
-------
PyVmomi can be installed via pip:
.. code-block:: bash
pip install pyVmomi
.. note::
versions of Python. If using version 6.0 of pyVmomi, Python 2.6,
Python 2.7.9, or newer must be present. This is due to an upstream dependency
in pyVmomi 6.0 that is not supported in Python versions 2.7 to 2.7.8. If the
version of Python is not in the supported range, you will need to install an
earlier version of pyVmomi. See `Issue #29537`_ for more information.
.. _Issue #29537: https://github.com/saltstack/salt/issues/29537
Based on the note above, to install an earlier version of pyVmomi than the
version currently listed in PyPi, run the following:
.. code-block:: bash
pip install pyVmomi==5.5.0.2014.1.1
The 5.5.0.2014.1.1 is a known stable version that this original VMware utils file
was developed against.
'''
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
import sys
import logging
import ssl
# Import Salt Libs
from salt.ext import six
from salt.exceptions import VMwareApiError, VMwareRuntimeError, \
VMwareObjectRetrievalError
import salt.utils.vmware
try:
from pyVmomi import vim, vmodl
HAS_PYVMOMI = True
except ImportError:
HAS_PYVMOMI = False
try:
from salt.ext.vsan import vsanapiutils
HAS_PYVSAN = True
except ImportError:
HAS_PYVSAN = False
# Get Logging Started
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load if PyVmomi is installed.
'''
if HAS_PYVSAN and HAS_PYVMOMI:
return True
else:
return False, 'Missing dependency: The salt.utils.vsan module ' \
'requires pyvmomi and the pyvsan extension library'
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 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_disk_management_system(service_instance):
'''
Returns a vim.VimClusterVsanVcDiskManagementSystem 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-disk-management-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']
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 add_capacity_to_diskgroup(service_instance, vsan_disk_mgmt_system,
host_ref, diskgroup, new_capacity_disks):
'''
Adds capacity disk(s) to 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
diskgroup
The vsan.HostDiskMapping object representing the host's diskgroup where
the additional capacity needs to be added
new_capacity_disks
List of vim.HostScsiDisk objects representing the disks to be added as
capacity disks. Can be either ssd or non-ssd. There must be a minimum
of 1 new capacity disk in the list.
'''
hostname = salt.utils.vmware.get_managed_object_name(host_ref)
cache_disk = diskgroup.ssd
cache_disk_id = cache_disk.canonicalName
log.debug(
'Adding capacity to disk group with cache disk \'%s\' on host \'%s\'',
cache_disk_id, hostname
)
log.trace(
'new_capacity_disk_ids = %s',
[c.canonicalName for c in new_capacity_disks]
)
spec = vim.VimVsanHostDiskMappingCreationSpec()
spec.cacheDisks = [cache_disk]
spec.capacityDisks = new_capacity_disks
# All new capacity disks must be either ssd or non-ssd (mixed disks are not
# supported); also they need to match the type of the existing capacity
# disks; we assume disks are already validated
spec.creationType = 'allFlash' if getattr(new_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:
raise VMwareRuntimeError(exc.msg)
_wait_for_tasks([task], service_instance)
return True
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_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 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 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)
|
saltstack/salt
|
salt/utils/crypt.py
|
decrypt
|
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)
|
.. 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.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/crypt.py#L27-L100
| null |
# -*- coding: utf-8 -*-
'''
Functions dealing with encryption
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import hashlib
import logging
import os
log = logging.getLogger(__name__)
# Import Salt libs
import salt.loader
import salt.utils.files
from salt.exceptions import SaltInvocationError
try:
import Crypto.Random
HAS_CRYPTO = True
except ImportError:
HAS_CRYPTO = False
def reinit_crypto():
'''
When a fork arises, pycrypto needs to reinit
From its doc::
Caveat: For the random number generator to work correctly,
you must call Random.atfork() in both the parent and
child processes after using os.fork()
'''
if HAS_CRYPTO:
Crypto.Random.atfork()
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(':')
|
saltstack/salt
|
salt/utils/crypt.py
|
pem_finger
|
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(':')
|
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.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/crypt.py#L117-L140
|
[
"def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n"
] |
# -*- coding: utf-8 -*-
'''
Functions dealing with encryption
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import hashlib
import logging
import os
log = logging.getLogger(__name__)
# Import Salt libs
import salt.loader
import salt.utils.files
from salt.exceptions import SaltInvocationError
try:
import Crypto.Random
HAS_CRYPTO = True
except ImportError:
HAS_CRYPTO = False
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 reinit_crypto():
'''
When a fork arises, pycrypto needs to reinit
From its doc::
Caveat: For the random number generator to work correctly,
you must call Random.atfork() in both the parent and
child processes after using os.fork()
'''
if HAS_CRYPTO:
Crypto.Random.atfork()
|
saltstack/salt
|
salt/utils/schema.py
|
SchemaItem._get_argname_value
|
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
|
Return the argname value looking up on all possible attributes
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/schema.py#L731-L748
| null |
class SchemaItem(six.with_metaclass(BaseSchemaItemMeta, object)):
'''
Base configuration items class.
All configurations must subclass it
'''
# Define some class level attributes to make PyLint happier
__type__ = None
__format__ = None
_attributes = None
__flatten__ = False
__serialize_attr_aliases__ = None
required = False
def __init__(self, required=None, **extra):
'''
:param required: If the configuration item is required. Defaults to ``False``.
'''
if required is not None:
self.required = required
self.extra = extra
def __validate_attributes__(self):
'''
Run any validation check you need the instance attributes.
ATTENTION:
Don't call the parent class when overriding this
method because it will just duplicate the executions. This class'es
metaclass will take care of that.
'''
if self.required not in (True, False):
raise RuntimeError(
'\'required\' can only be True/False'
)
def serialize(self):
'''
Return a serializable form of the config instance
'''
raise NotImplementedError
|
saltstack/salt
|
salt/utils/schema.py
|
BaseSchemaItem.serialize
|
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
|
Return a serializable form of the config instance
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/schema.py#L827-L845
|
[
"def _get_argname_value(self, argname):\n '''\n Return the argname value looking up on all possible attributes\n '''\n # Let's see if there's a private function to get the value\n argvalue = getattr(self, '__get_{0}__'.format(argname), None)\n if argvalue is not None and callable(argvalue):\n argvalue = argvalue()\n if argvalue is None:\n # Let's see if the value is defined as a public class variable\n argvalue = getattr(self, argname, None)\n if argvalue is None:\n # Let's see if it's defined as a private class variable\n argvalue = getattr(self, '__{0}__'.format(argname), None)\n if argvalue is None:\n # Let's look for it in the extra dictionary\n argvalue = self.extra.get(argname, None)\n return argvalue\n"
] |
class BaseSchemaItem(SchemaItem):
'''
Base configuration items class.
All configurations must subclass it
'''
# Let's define description as a class attribute, this will allow a custom configuration
# item to do something like:
# class MyCustomConfig(StringItem):
# '''
# This is my custom config, blah, blah, blah
# '''
# description = __doc__
#
description = None
# The same for all other base arguments
title = None
default = None
enum = None
enumNames = None
def __init__(self, title=None, description=None, default=None, enum=None, enumNames=None, **kwargs):
'''
:param required:
If the configuration item is required. Defaults to ``False``.
:param title:
A short explanation about the purpose of the data described by this item.
:param description:
A detailed explanation about the purpose of the data described by this item.
:param default:
The default value for this configuration item. May be :data:`.Null` (a special value
to set the default value to null).
:param enum:
A list(list, tuple, set) of valid choices.
'''
if title is not None:
self.title = title
if description is not None:
self.description = description
if default is not None:
self.default = default
if enum is not None:
self.enum = enum
if enumNames is not None:
self.enumNames = enumNames
super(BaseSchemaItem, self).__init__(**kwargs)
def __validate_attributes__(self):
if self.enum is not None:
if not isinstance(self.enum, (list, tuple, set)):
raise RuntimeError(
'Only the \'list\', \'tuple\' and \'set\' python types can be used '
'to define \'enum\''
)
if not isinstance(self.enum, list):
self.enum = list(self.enum)
if self.enumNames is not None:
if not isinstance(self.enumNames, (list, tuple, set)):
raise RuntimeError(
'Only the \'list\', \'tuple\' and \'set\' python types can be used '
'to define \'enumNames\''
)
if len(self.enum) != len(self.enumNames):
raise RuntimeError(
'The size of \'enumNames\' must match the size of \'enum\''
)
if not isinstance(self.enumNames, list):
self.enumNames = list(self.enumNames)
def __get_description__(self):
if self.description is not None:
if self.description == self.__doc__:
return textwrap.dedent(self.description).strip()
return self.description
|
saltstack/salt
|
salt/utils/schema.py
|
ComplexSchemaItem._add_missing_schema_attributes
|
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)
|
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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/schema.py#L1481-L1493
| null |
class ComplexSchemaItem(BaseSchemaItem):
'''
.. versionadded:: 2016.11.0
Complex Schema Item
'''
# This attribute is populated by the metaclass, but pylint fails to see it
# and assumes it's not an iterable
_attributes = []
_definition_name = None
def __init__(self, definition_name=None, required=None):
super(ComplexSchemaItem, self).__init__(required=required)
self.__type__ = 'object'
self._definition_name = definition_name if definition_name else \
self.__class__.__name__
# Schema attributes might have been added as class attributes so we
# and they must be added to the _attributes attr
self._add_missing_schema_attributes()
@property
def definition_name(self):
return self._definition_name
def serialize(self):
'''
The serialization of the complex item is a pointer to the item
definition
'''
return {'$ref': '#/definitions/{0}'.format(self.definition_name)}
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_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)]
|
saltstack/salt
|
salt/utils/schema.py
|
ComplexSchemaItem.get_definition
|
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
|
Returns the definition of the complex item
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/schema.py#L1506-L1533
|
[
"def serialize(self):\n '''\n Return a serializable form of the config instance\n '''\n serialized = {'type': self.__type__}\n for argname in self._attributes:\n if argname == 'required':\n # This is handled elsewhere\n continue\n argvalue = self._get_argname_value(argname)\n if argvalue is not None:\n if argvalue is Null:\n argvalue = None\n # None values are not meant to be included in the\n # serialization, since this is not None...\n if self.__serialize_attr_aliases__ and argname in self.__serialize_attr_aliases__:\n argname = self.__serialize_attr_aliases__[argname]\n serialized[argname] = argvalue\n return serialized\n"
] |
class ComplexSchemaItem(BaseSchemaItem):
'''
.. versionadded:: 2016.11.0
Complex Schema Item
'''
# This attribute is populated by the metaclass, but pylint fails to see it
# and assumes it's not an iterable
_attributes = []
_definition_name = None
def __init__(self, definition_name=None, required=None):
super(ComplexSchemaItem, self).__init__(required=required)
self.__type__ = 'object'
self._definition_name = definition_name if definition_name else \
self.__class__.__name__
# Schema attributes might have been added as class attributes so we
# and they must be added to the _attributes attr
self._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)
@property
def definition_name(self):
return self._definition_name
def serialize(self):
'''
The serialization of the complex item is a pointer to the item
definition
'''
return {'$ref': '#/definitions/{0}'.format(self.definition_name)}
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)]
|
saltstack/salt
|
salt/utils/schema.py
|
ComplexSchemaItem.get_complex_attrs
|
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)]
|
Returns a dictionary of the complex attributes
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/schema.py#L1535-L1538
| null |
class ComplexSchemaItem(BaseSchemaItem):
'''
.. versionadded:: 2016.11.0
Complex Schema Item
'''
# This attribute is populated by the metaclass, but pylint fails to see it
# and assumes it's not an iterable
_attributes = []
_definition_name = None
def __init__(self, definition_name=None, required=None):
super(ComplexSchemaItem, self).__init__(required=required)
self.__type__ = 'object'
self._definition_name = definition_name if definition_name else \
self.__class__.__name__
# Schema attributes might have been added as class attributes so we
# and they must be added to the _attributes attr
self._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)
@property
def definition_name(self):
return self._definition_name
def serialize(self):
'''
The serialization of the complex item is a pointer to the item
definition
'''
return {'$ref': '#/definitions/{0}'.format(self.definition_name)}
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
|
saltstack/salt
|
salt/modules/boto_rds.py
|
exists
|
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)}
|
Check to see if an RDS exists.
CLI example::
salt myminion boto_rds.exists myrds region=us-east-1
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_rds.py#L141-L155
| null |
# -*- coding: utf-8 -*-
'''
Connection module for Amazon RDS
.. versionadded:: 2015.8.0
:configuration: This module accepts explicit rds credentials but can also
utilize IAM roles assigned to the instance through Instance Profiles.
Dynamic credentials are then automatically obtained from AWS API and no
further configuration is necessary. More Information available at:
.. code-block:: text
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
If IAM roles are not used you need to specify them either in a pillar or
in the minion's config file:
.. code-block:: yaml
rds.keyid: GKTADJGHEIQSXMKKRBJ08H
rds.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
rds.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
:depends: boto3
'''
# keep lint from choking on _get_conn and _cache_id
#pylint: disable=E0602
# pylint whinging perfectly valid code
#pylint: disable=W0106
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import time
# Import Salt libs
import salt.utils.compat
import salt.utils.odict as odict
import salt.utils.versions
from salt.exceptions import SaltInvocationError
log = logging.getLogger(__name__)
# Import third party libs
from salt.ext import six
# pylint: disable=import-error
try:
#pylint: disable=unused-import
import boto
import boto3
#pylint: enable=unused-import
from botocore.exceptions import ClientError
logging.getLogger('boto').setLevel(logging.CRITICAL)
logging.getLogger('boto3').setLevel(logging.CRITICAL)
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
# pylint: enable=import-error
boto3_param_map = {
'allocated_storage': ('AllocatedStorage', int),
'allow_major_version_upgrade': ('AllowMajorVersionUpgrade', bool),
'apply_immediately': ('ApplyImmediately', bool),
'auto_minor_version_upgrade': ('AutoMinorVersionUpgrade', bool),
'availability_zone': ('AvailabilityZone', str),
'backup_retention_period': ('BackupRetentionPeriod', int),
'ca_certificate_identifier': ('CACertificateIdentifier', str),
'character_set_name': ('CharacterSetName', str),
'copy_tags_to_snapshot': ('CopyTagsToSnapshot', bool),
'db_cluster_identifier': ('DBClusterIdentifier', str),
'db_instance_class': ('DBInstanceClass', str),
'db_name': ('DBName', str),
'db_parameter_group_name': ('DBParameterGroupName', str),
'db_port_number': ('DBPortNumber', int),
'db_security_groups': ('DBSecurityGroups', list),
'db_subnet_group_name': ('DBSubnetGroupName', str),
'domain': ('Domain', str),
'domain_iam_role_name': ('DomainIAMRoleName', str),
'engine': ('Engine', str),
'engine_version': ('EngineVersion', str),
'iops': ('Iops', int),
'kms_key_id': ('KmsKeyId', str),
'license_model': ('LicenseModel', str),
'master_user_password': ('MasterUserPassword', str),
'master_username': ('MasterUsername', str),
'monitoring_interval': ('MonitoringInterval', int),
'monitoring_role_arn': ('MonitoringRoleArn', str),
'multi_az': ('MultiAZ', bool),
'name': ('DBInstanceIdentifier', str),
'new_db_instance_identifier': ('NewDBInstanceIdentifier', str),
'option_group_name': ('OptionGroupName', str),
'port': ('Port', int),
'preferred_backup_window': ('PreferredBackupWindow', str),
'preferred_maintenance_window': ('PreferredMaintenanceWindow', str),
'promotion_tier': ('PromotionTier', int),
'publicly_accessible': ('PubliclyAccessible', bool),
'storage_encrypted': ('StorageEncrypted', bool),
'storage_type': ('StorageType', str),
'tags': ('Tags', list),
'tde_credential_arn': ('TdeCredentialArn', str),
'tde_credential_password': ('TdeCredentialPassword', str),
'vpc_security_group_ids': ('VpcSecurityGroupIds', list),
}
def __virtual__():
'''
Only load if boto libraries exist and if boto libraries are greater than
a given version.
'''
return salt.utils.versions.check_boto_reqs(
boto3_ver='1.3.1'
)
def __init__(opts):
salt.utils.compat.pack_dunder(__name__)
if HAS_BOTO:
__utils__['boto3.assign_funcs'](__name__, 'rds')
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 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 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 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_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_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_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_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 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 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_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_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 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 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_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_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_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 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_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 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 _tag_doc(tags):
taglist = []
if tags is not None:
for k, v in six.iteritems(tags):
if six.text_type(k).startswith('__'):
continue
taglist.append({'Key': six.text_type(k), 'Value': six.text_type(v)})
return taglist
|
saltstack/salt
|
salt/modules/boto_rds.py
|
option_group_exists
|
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)}
|
Check to see if an RDS option group exists.
CLI example::
salt myminion boto_rds.option_group_exists myoptiongr region=us-east-1
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_rds.py#L158-L173
| null |
# -*- coding: utf-8 -*-
'''
Connection module for Amazon RDS
.. versionadded:: 2015.8.0
:configuration: This module accepts explicit rds credentials but can also
utilize IAM roles assigned to the instance through Instance Profiles.
Dynamic credentials are then automatically obtained from AWS API and no
further configuration is necessary. More Information available at:
.. code-block:: text
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
If IAM roles are not used you need to specify them either in a pillar or
in the minion's config file:
.. code-block:: yaml
rds.keyid: GKTADJGHEIQSXMKKRBJ08H
rds.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
rds.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
:depends: boto3
'''
# keep lint from choking on _get_conn and _cache_id
#pylint: disable=E0602
# pylint whinging perfectly valid code
#pylint: disable=W0106
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import time
# Import Salt libs
import salt.utils.compat
import salt.utils.odict as odict
import salt.utils.versions
from salt.exceptions import SaltInvocationError
log = logging.getLogger(__name__)
# Import third party libs
from salt.ext import six
# pylint: disable=import-error
try:
#pylint: disable=unused-import
import boto
import boto3
#pylint: enable=unused-import
from botocore.exceptions import ClientError
logging.getLogger('boto').setLevel(logging.CRITICAL)
logging.getLogger('boto3').setLevel(logging.CRITICAL)
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
# pylint: enable=import-error
boto3_param_map = {
'allocated_storage': ('AllocatedStorage', int),
'allow_major_version_upgrade': ('AllowMajorVersionUpgrade', bool),
'apply_immediately': ('ApplyImmediately', bool),
'auto_minor_version_upgrade': ('AutoMinorVersionUpgrade', bool),
'availability_zone': ('AvailabilityZone', str),
'backup_retention_period': ('BackupRetentionPeriod', int),
'ca_certificate_identifier': ('CACertificateIdentifier', str),
'character_set_name': ('CharacterSetName', str),
'copy_tags_to_snapshot': ('CopyTagsToSnapshot', bool),
'db_cluster_identifier': ('DBClusterIdentifier', str),
'db_instance_class': ('DBInstanceClass', str),
'db_name': ('DBName', str),
'db_parameter_group_name': ('DBParameterGroupName', str),
'db_port_number': ('DBPortNumber', int),
'db_security_groups': ('DBSecurityGroups', list),
'db_subnet_group_name': ('DBSubnetGroupName', str),
'domain': ('Domain', str),
'domain_iam_role_name': ('DomainIAMRoleName', str),
'engine': ('Engine', str),
'engine_version': ('EngineVersion', str),
'iops': ('Iops', int),
'kms_key_id': ('KmsKeyId', str),
'license_model': ('LicenseModel', str),
'master_user_password': ('MasterUserPassword', str),
'master_username': ('MasterUsername', str),
'monitoring_interval': ('MonitoringInterval', int),
'monitoring_role_arn': ('MonitoringRoleArn', str),
'multi_az': ('MultiAZ', bool),
'name': ('DBInstanceIdentifier', str),
'new_db_instance_identifier': ('NewDBInstanceIdentifier', str),
'option_group_name': ('OptionGroupName', str),
'port': ('Port', int),
'preferred_backup_window': ('PreferredBackupWindow', str),
'preferred_maintenance_window': ('PreferredMaintenanceWindow', str),
'promotion_tier': ('PromotionTier', int),
'publicly_accessible': ('PubliclyAccessible', bool),
'storage_encrypted': ('StorageEncrypted', bool),
'storage_type': ('StorageType', str),
'tags': ('Tags', list),
'tde_credential_arn': ('TdeCredentialArn', str),
'tde_credential_password': ('TdeCredentialPassword', str),
'vpc_security_group_ids': ('VpcSecurityGroupIds', list),
}
def __virtual__():
'''
Only load if boto libraries exist and if boto libraries are greater than
a given version.
'''
return salt.utils.versions.check_boto_reqs(
boto3_ver='1.3.1'
)
def __init__(opts):
salt.utils.compat.pack_dunder(__name__)
if HAS_BOTO:
__utils__['boto3.assign_funcs'](__name__, 'rds')
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 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 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 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_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_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_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_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 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 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_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_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 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 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_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_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_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 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_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 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 _tag_doc(tags):
taglist = []
if tags is not None:
for k, v in six.iteritems(tags):
if six.text_type(k).startswith('__'):
continue
taglist.append({'Key': six.text_type(k), 'Value': six.text_type(v)})
return taglist
|
saltstack/salt
|
salt/modules/boto_rds.py
|
parameter_group_exists
|
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
|
Check to see if an RDS parameter group exists.
CLI example::
salt myminion boto_rds.parameter_group_exists myparametergroup \
region=us-east-1
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_rds.py#L176-L196
| null |
# -*- coding: utf-8 -*-
'''
Connection module for Amazon RDS
.. versionadded:: 2015.8.0
:configuration: This module accepts explicit rds credentials but can also
utilize IAM roles assigned to the instance through Instance Profiles.
Dynamic credentials are then automatically obtained from AWS API and no
further configuration is necessary. More Information available at:
.. code-block:: text
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
If IAM roles are not used you need to specify them either in a pillar or
in the minion's config file:
.. code-block:: yaml
rds.keyid: GKTADJGHEIQSXMKKRBJ08H
rds.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
rds.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
:depends: boto3
'''
# keep lint from choking on _get_conn and _cache_id
#pylint: disable=E0602
# pylint whinging perfectly valid code
#pylint: disable=W0106
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import time
# Import Salt libs
import salt.utils.compat
import salt.utils.odict as odict
import salt.utils.versions
from salt.exceptions import SaltInvocationError
log = logging.getLogger(__name__)
# Import third party libs
from salt.ext import six
# pylint: disable=import-error
try:
#pylint: disable=unused-import
import boto
import boto3
#pylint: enable=unused-import
from botocore.exceptions import ClientError
logging.getLogger('boto').setLevel(logging.CRITICAL)
logging.getLogger('boto3').setLevel(logging.CRITICAL)
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
# pylint: enable=import-error
boto3_param_map = {
'allocated_storage': ('AllocatedStorage', int),
'allow_major_version_upgrade': ('AllowMajorVersionUpgrade', bool),
'apply_immediately': ('ApplyImmediately', bool),
'auto_minor_version_upgrade': ('AutoMinorVersionUpgrade', bool),
'availability_zone': ('AvailabilityZone', str),
'backup_retention_period': ('BackupRetentionPeriod', int),
'ca_certificate_identifier': ('CACertificateIdentifier', str),
'character_set_name': ('CharacterSetName', str),
'copy_tags_to_snapshot': ('CopyTagsToSnapshot', bool),
'db_cluster_identifier': ('DBClusterIdentifier', str),
'db_instance_class': ('DBInstanceClass', str),
'db_name': ('DBName', str),
'db_parameter_group_name': ('DBParameterGroupName', str),
'db_port_number': ('DBPortNumber', int),
'db_security_groups': ('DBSecurityGroups', list),
'db_subnet_group_name': ('DBSubnetGroupName', str),
'domain': ('Domain', str),
'domain_iam_role_name': ('DomainIAMRoleName', str),
'engine': ('Engine', str),
'engine_version': ('EngineVersion', str),
'iops': ('Iops', int),
'kms_key_id': ('KmsKeyId', str),
'license_model': ('LicenseModel', str),
'master_user_password': ('MasterUserPassword', str),
'master_username': ('MasterUsername', str),
'monitoring_interval': ('MonitoringInterval', int),
'monitoring_role_arn': ('MonitoringRoleArn', str),
'multi_az': ('MultiAZ', bool),
'name': ('DBInstanceIdentifier', str),
'new_db_instance_identifier': ('NewDBInstanceIdentifier', str),
'option_group_name': ('OptionGroupName', str),
'port': ('Port', int),
'preferred_backup_window': ('PreferredBackupWindow', str),
'preferred_maintenance_window': ('PreferredMaintenanceWindow', str),
'promotion_tier': ('PromotionTier', int),
'publicly_accessible': ('PubliclyAccessible', bool),
'storage_encrypted': ('StorageEncrypted', bool),
'storage_type': ('StorageType', str),
'tags': ('Tags', list),
'tde_credential_arn': ('TdeCredentialArn', str),
'tde_credential_password': ('TdeCredentialPassword', str),
'vpc_security_group_ids': ('VpcSecurityGroupIds', list),
}
def __virtual__():
'''
Only load if boto libraries exist and if boto libraries are greater than
a given version.
'''
return salt.utils.versions.check_boto_reqs(
boto3_ver='1.3.1'
)
def __init__(opts):
salt.utils.compat.pack_dunder(__name__)
if HAS_BOTO:
__utils__['boto3.assign_funcs'](__name__, 'rds')
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 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 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 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_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_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_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_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 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 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_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_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 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 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_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_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_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 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_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 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 _tag_doc(tags):
taglist = []
if tags is not None:
for k, v in six.iteritems(tags):
if six.text_type(k).startswith('__'):
continue
taglist.append({'Key': six.text_type(k), 'Value': six.text_type(v)})
return taglist
|
saltstack/salt
|
salt/modules/boto_rds.py
|
subnet_group_exists
|
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)}
|
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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_rds.py#L199-L220
| null |
# -*- coding: utf-8 -*-
'''
Connection module for Amazon RDS
.. versionadded:: 2015.8.0
:configuration: This module accepts explicit rds credentials but can also
utilize IAM roles assigned to the instance through Instance Profiles.
Dynamic credentials are then automatically obtained from AWS API and no
further configuration is necessary. More Information available at:
.. code-block:: text
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
If IAM roles are not used you need to specify them either in a pillar or
in the minion's config file:
.. code-block:: yaml
rds.keyid: GKTADJGHEIQSXMKKRBJ08H
rds.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
rds.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
:depends: boto3
'''
# keep lint from choking on _get_conn and _cache_id
#pylint: disable=E0602
# pylint whinging perfectly valid code
#pylint: disable=W0106
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import time
# Import Salt libs
import salt.utils.compat
import salt.utils.odict as odict
import salt.utils.versions
from salt.exceptions import SaltInvocationError
log = logging.getLogger(__name__)
# Import third party libs
from salt.ext import six
# pylint: disable=import-error
try:
#pylint: disable=unused-import
import boto
import boto3
#pylint: enable=unused-import
from botocore.exceptions import ClientError
logging.getLogger('boto').setLevel(logging.CRITICAL)
logging.getLogger('boto3').setLevel(logging.CRITICAL)
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
# pylint: enable=import-error
boto3_param_map = {
'allocated_storage': ('AllocatedStorage', int),
'allow_major_version_upgrade': ('AllowMajorVersionUpgrade', bool),
'apply_immediately': ('ApplyImmediately', bool),
'auto_minor_version_upgrade': ('AutoMinorVersionUpgrade', bool),
'availability_zone': ('AvailabilityZone', str),
'backup_retention_period': ('BackupRetentionPeriod', int),
'ca_certificate_identifier': ('CACertificateIdentifier', str),
'character_set_name': ('CharacterSetName', str),
'copy_tags_to_snapshot': ('CopyTagsToSnapshot', bool),
'db_cluster_identifier': ('DBClusterIdentifier', str),
'db_instance_class': ('DBInstanceClass', str),
'db_name': ('DBName', str),
'db_parameter_group_name': ('DBParameterGroupName', str),
'db_port_number': ('DBPortNumber', int),
'db_security_groups': ('DBSecurityGroups', list),
'db_subnet_group_name': ('DBSubnetGroupName', str),
'domain': ('Domain', str),
'domain_iam_role_name': ('DomainIAMRoleName', str),
'engine': ('Engine', str),
'engine_version': ('EngineVersion', str),
'iops': ('Iops', int),
'kms_key_id': ('KmsKeyId', str),
'license_model': ('LicenseModel', str),
'master_user_password': ('MasterUserPassword', str),
'master_username': ('MasterUsername', str),
'monitoring_interval': ('MonitoringInterval', int),
'monitoring_role_arn': ('MonitoringRoleArn', str),
'multi_az': ('MultiAZ', bool),
'name': ('DBInstanceIdentifier', str),
'new_db_instance_identifier': ('NewDBInstanceIdentifier', str),
'option_group_name': ('OptionGroupName', str),
'port': ('Port', int),
'preferred_backup_window': ('PreferredBackupWindow', str),
'preferred_maintenance_window': ('PreferredMaintenanceWindow', str),
'promotion_tier': ('PromotionTier', int),
'publicly_accessible': ('PubliclyAccessible', bool),
'storage_encrypted': ('StorageEncrypted', bool),
'storage_type': ('StorageType', str),
'tags': ('Tags', list),
'tde_credential_arn': ('TdeCredentialArn', str),
'tde_credential_password': ('TdeCredentialPassword', str),
'vpc_security_group_ids': ('VpcSecurityGroupIds', list),
}
def __virtual__():
'''
Only load if boto libraries exist and if boto libraries are greater than
a given version.
'''
return salt.utils.versions.check_boto_reqs(
boto3_ver='1.3.1'
)
def __init__(opts):
salt.utils.compat.pack_dunder(__name__)
if HAS_BOTO:
__utils__['boto3.assign_funcs'](__name__, 'rds')
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 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 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 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_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_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_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_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 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 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_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_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 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 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_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_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_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 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_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 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 _tag_doc(tags):
taglist = []
if tags is not None:
for k, v in six.iteritems(tags):
if six.text_type(k).startswith('__'):
continue
taglist.append({'Key': six.text_type(k), 'Value': six.text_type(v)})
return taglist
|
saltstack/salt
|
salt/modules/boto_rds.py
|
create
|
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)}
|
Create an RDS Instance
CLI example to create an RDS Instance::
salt myminion boto_rds.create myrds 10 db.t2.micro MySQL sqlusr sqlpassw
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_rds.py#L223-L319
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n",
"def describe_db_instances(name=None, filters=None, jmespath='DBInstances',\n region=None, key=None, keyid=None, profile=None):\n '''\n Return a detailed listing of some, or all, DB Instances visible in the\n current scope. Arbitrary subelements or subsections of the returned dataset\n can be selected by passing in a valid JMSEPath filter as well.\n\n CLI example::\n\n salt myminion boto_rds.describe_db_instances jmespath='DBInstances[*].DBInstanceIdentifier'\n\n '''\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n pag = conn.get_paginator('describe_db_instances')\n args = {}\n args.update({'DBInstanceIdentifier': name}) if name else None\n args.update({'Filters': filters}) if filters else None\n pit = pag.paginate(**args)\n pit = pit.search(jmespath) if jmespath else pit\n try:\n return [p for p in pit]\n except ClientError as e:\n code = getattr(e, 'response', {}).get('Error', {}).get('Code')\n if code != 'DBInstanceNotFound':\n log.error(__utils__['boto3.get_error'](e))\n return []\n",
"def _tag_doc(tags):\n taglist = []\n if tags is not None:\n for k, v in six.iteritems(tags):\n if six.text_type(k).startswith('__'):\n continue\n taglist.append({'Key': six.text_type(k), 'Value': six.text_type(v)})\n return taglist\n"
] |
# -*- coding: utf-8 -*-
'''
Connection module for Amazon RDS
.. versionadded:: 2015.8.0
:configuration: This module accepts explicit rds credentials but can also
utilize IAM roles assigned to the instance through Instance Profiles.
Dynamic credentials are then automatically obtained from AWS API and no
further configuration is necessary. More Information available at:
.. code-block:: text
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
If IAM roles are not used you need to specify them either in a pillar or
in the minion's config file:
.. code-block:: yaml
rds.keyid: GKTADJGHEIQSXMKKRBJ08H
rds.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
rds.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
:depends: boto3
'''
# keep lint from choking on _get_conn and _cache_id
#pylint: disable=E0602
# pylint whinging perfectly valid code
#pylint: disable=W0106
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import time
# Import Salt libs
import salt.utils.compat
import salt.utils.odict as odict
import salt.utils.versions
from salt.exceptions import SaltInvocationError
log = logging.getLogger(__name__)
# Import third party libs
from salt.ext import six
# pylint: disable=import-error
try:
#pylint: disable=unused-import
import boto
import boto3
#pylint: enable=unused-import
from botocore.exceptions import ClientError
logging.getLogger('boto').setLevel(logging.CRITICAL)
logging.getLogger('boto3').setLevel(logging.CRITICAL)
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
# pylint: enable=import-error
boto3_param_map = {
'allocated_storage': ('AllocatedStorage', int),
'allow_major_version_upgrade': ('AllowMajorVersionUpgrade', bool),
'apply_immediately': ('ApplyImmediately', bool),
'auto_minor_version_upgrade': ('AutoMinorVersionUpgrade', bool),
'availability_zone': ('AvailabilityZone', str),
'backup_retention_period': ('BackupRetentionPeriod', int),
'ca_certificate_identifier': ('CACertificateIdentifier', str),
'character_set_name': ('CharacterSetName', str),
'copy_tags_to_snapshot': ('CopyTagsToSnapshot', bool),
'db_cluster_identifier': ('DBClusterIdentifier', str),
'db_instance_class': ('DBInstanceClass', str),
'db_name': ('DBName', str),
'db_parameter_group_name': ('DBParameterGroupName', str),
'db_port_number': ('DBPortNumber', int),
'db_security_groups': ('DBSecurityGroups', list),
'db_subnet_group_name': ('DBSubnetGroupName', str),
'domain': ('Domain', str),
'domain_iam_role_name': ('DomainIAMRoleName', str),
'engine': ('Engine', str),
'engine_version': ('EngineVersion', str),
'iops': ('Iops', int),
'kms_key_id': ('KmsKeyId', str),
'license_model': ('LicenseModel', str),
'master_user_password': ('MasterUserPassword', str),
'master_username': ('MasterUsername', str),
'monitoring_interval': ('MonitoringInterval', int),
'monitoring_role_arn': ('MonitoringRoleArn', str),
'multi_az': ('MultiAZ', bool),
'name': ('DBInstanceIdentifier', str),
'new_db_instance_identifier': ('NewDBInstanceIdentifier', str),
'option_group_name': ('OptionGroupName', str),
'port': ('Port', int),
'preferred_backup_window': ('PreferredBackupWindow', str),
'preferred_maintenance_window': ('PreferredMaintenanceWindow', str),
'promotion_tier': ('PromotionTier', int),
'publicly_accessible': ('PubliclyAccessible', bool),
'storage_encrypted': ('StorageEncrypted', bool),
'storage_type': ('StorageType', str),
'tags': ('Tags', list),
'tde_credential_arn': ('TdeCredentialArn', str),
'tde_credential_password': ('TdeCredentialPassword', str),
'vpc_security_group_ids': ('VpcSecurityGroupIds', list),
}
def __virtual__():
'''
Only load if boto libraries exist and if boto libraries are greater than
a given version.
'''
return salt.utils.versions.check_boto_reqs(
boto3_ver='1.3.1'
)
def __init__(opts):
salt.utils.compat.pack_dunder(__name__)
if HAS_BOTO:
__utils__['boto3.assign_funcs'](__name__, 'rds')
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 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 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 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 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_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_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_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 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 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_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_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 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 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_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_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_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 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_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 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 _tag_doc(tags):
taglist = []
if tags is not None:
for k, v in six.iteritems(tags):
if six.text_type(k).startswith('__'):
continue
taglist.append({'Key': six.text_type(k), 'Value': six.text_type(v)})
return taglist
|
saltstack/salt
|
salt/modules/boto_rds.py
|
create_read_replica
|
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)}
|
Create an RDS read replica
CLI example to create an RDS read replica::
salt myminion boto_rds.create_read_replica replicaname source_name
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_rds.py#L322-L377
|
[
"def _tag_doc(tags):\n taglist = []\n if tags is not None:\n for k, v in six.iteritems(tags):\n if six.text_type(k).startswith('__'):\n continue\n taglist.append({'Key': six.text_type(k), 'Value': six.text_type(v)})\n return taglist\n"
] |
# -*- coding: utf-8 -*-
'''
Connection module for Amazon RDS
.. versionadded:: 2015.8.0
:configuration: This module accepts explicit rds credentials but can also
utilize IAM roles assigned to the instance through Instance Profiles.
Dynamic credentials are then automatically obtained from AWS API and no
further configuration is necessary. More Information available at:
.. code-block:: text
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
If IAM roles are not used you need to specify them either in a pillar or
in the minion's config file:
.. code-block:: yaml
rds.keyid: GKTADJGHEIQSXMKKRBJ08H
rds.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
rds.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
:depends: boto3
'''
# keep lint from choking on _get_conn and _cache_id
#pylint: disable=E0602
# pylint whinging perfectly valid code
#pylint: disable=W0106
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import time
# Import Salt libs
import salt.utils.compat
import salt.utils.odict as odict
import salt.utils.versions
from salt.exceptions import SaltInvocationError
log = logging.getLogger(__name__)
# Import third party libs
from salt.ext import six
# pylint: disable=import-error
try:
#pylint: disable=unused-import
import boto
import boto3
#pylint: enable=unused-import
from botocore.exceptions import ClientError
logging.getLogger('boto').setLevel(logging.CRITICAL)
logging.getLogger('boto3').setLevel(logging.CRITICAL)
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
# pylint: enable=import-error
boto3_param_map = {
'allocated_storage': ('AllocatedStorage', int),
'allow_major_version_upgrade': ('AllowMajorVersionUpgrade', bool),
'apply_immediately': ('ApplyImmediately', bool),
'auto_minor_version_upgrade': ('AutoMinorVersionUpgrade', bool),
'availability_zone': ('AvailabilityZone', str),
'backup_retention_period': ('BackupRetentionPeriod', int),
'ca_certificate_identifier': ('CACertificateIdentifier', str),
'character_set_name': ('CharacterSetName', str),
'copy_tags_to_snapshot': ('CopyTagsToSnapshot', bool),
'db_cluster_identifier': ('DBClusterIdentifier', str),
'db_instance_class': ('DBInstanceClass', str),
'db_name': ('DBName', str),
'db_parameter_group_name': ('DBParameterGroupName', str),
'db_port_number': ('DBPortNumber', int),
'db_security_groups': ('DBSecurityGroups', list),
'db_subnet_group_name': ('DBSubnetGroupName', str),
'domain': ('Domain', str),
'domain_iam_role_name': ('DomainIAMRoleName', str),
'engine': ('Engine', str),
'engine_version': ('EngineVersion', str),
'iops': ('Iops', int),
'kms_key_id': ('KmsKeyId', str),
'license_model': ('LicenseModel', str),
'master_user_password': ('MasterUserPassword', str),
'master_username': ('MasterUsername', str),
'monitoring_interval': ('MonitoringInterval', int),
'monitoring_role_arn': ('MonitoringRoleArn', str),
'multi_az': ('MultiAZ', bool),
'name': ('DBInstanceIdentifier', str),
'new_db_instance_identifier': ('NewDBInstanceIdentifier', str),
'option_group_name': ('OptionGroupName', str),
'port': ('Port', int),
'preferred_backup_window': ('PreferredBackupWindow', str),
'preferred_maintenance_window': ('PreferredMaintenanceWindow', str),
'promotion_tier': ('PromotionTier', int),
'publicly_accessible': ('PubliclyAccessible', bool),
'storage_encrypted': ('StorageEncrypted', bool),
'storage_type': ('StorageType', str),
'tags': ('Tags', list),
'tde_credential_arn': ('TdeCredentialArn', str),
'tde_credential_password': ('TdeCredentialPassword', str),
'vpc_security_group_ids': ('VpcSecurityGroupIds', list),
}
def __virtual__():
'''
Only load if boto libraries exist and if boto libraries are greater than
a given version.
'''
return salt.utils.versions.check_boto_reqs(
boto3_ver='1.3.1'
)
def __init__(opts):
salt.utils.compat.pack_dunder(__name__)
if HAS_BOTO:
__utils__['boto3.assign_funcs'](__name__, 'rds')
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 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 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 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 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_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_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_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 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 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_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_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 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 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_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_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_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 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_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 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 _tag_doc(tags):
taglist = []
if tags is not None:
for k, v in six.iteritems(tags):
if six.text_type(k).startswith('__'):
continue
taglist.append({'Key': six.text_type(k), 'Value': six.text_type(v)})
return taglist
|
saltstack/salt
|
salt/modules/boto_rds.py
|
create_option_group
|
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)}
|
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"
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_rds.py#L380-L410
|
[
"def _tag_doc(tags):\n taglist = []\n if tags is not None:\n for k, v in six.iteritems(tags):\n if six.text_type(k).startswith('__'):\n continue\n taglist.append({'Key': six.text_type(k), 'Value': six.text_type(v)})\n return taglist\n"
] |
# -*- coding: utf-8 -*-
'''
Connection module for Amazon RDS
.. versionadded:: 2015.8.0
:configuration: This module accepts explicit rds credentials but can also
utilize IAM roles assigned to the instance through Instance Profiles.
Dynamic credentials are then automatically obtained from AWS API and no
further configuration is necessary. More Information available at:
.. code-block:: text
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
If IAM roles are not used you need to specify them either in a pillar or
in the minion's config file:
.. code-block:: yaml
rds.keyid: GKTADJGHEIQSXMKKRBJ08H
rds.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
rds.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
:depends: boto3
'''
# keep lint from choking on _get_conn and _cache_id
#pylint: disable=E0602
# pylint whinging perfectly valid code
#pylint: disable=W0106
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import time
# Import Salt libs
import salt.utils.compat
import salt.utils.odict as odict
import salt.utils.versions
from salt.exceptions import SaltInvocationError
log = logging.getLogger(__name__)
# Import third party libs
from salt.ext import six
# pylint: disable=import-error
try:
#pylint: disable=unused-import
import boto
import boto3
#pylint: enable=unused-import
from botocore.exceptions import ClientError
logging.getLogger('boto').setLevel(logging.CRITICAL)
logging.getLogger('boto3').setLevel(logging.CRITICAL)
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
# pylint: enable=import-error
boto3_param_map = {
'allocated_storage': ('AllocatedStorage', int),
'allow_major_version_upgrade': ('AllowMajorVersionUpgrade', bool),
'apply_immediately': ('ApplyImmediately', bool),
'auto_minor_version_upgrade': ('AutoMinorVersionUpgrade', bool),
'availability_zone': ('AvailabilityZone', str),
'backup_retention_period': ('BackupRetentionPeriod', int),
'ca_certificate_identifier': ('CACertificateIdentifier', str),
'character_set_name': ('CharacterSetName', str),
'copy_tags_to_snapshot': ('CopyTagsToSnapshot', bool),
'db_cluster_identifier': ('DBClusterIdentifier', str),
'db_instance_class': ('DBInstanceClass', str),
'db_name': ('DBName', str),
'db_parameter_group_name': ('DBParameterGroupName', str),
'db_port_number': ('DBPortNumber', int),
'db_security_groups': ('DBSecurityGroups', list),
'db_subnet_group_name': ('DBSubnetGroupName', str),
'domain': ('Domain', str),
'domain_iam_role_name': ('DomainIAMRoleName', str),
'engine': ('Engine', str),
'engine_version': ('EngineVersion', str),
'iops': ('Iops', int),
'kms_key_id': ('KmsKeyId', str),
'license_model': ('LicenseModel', str),
'master_user_password': ('MasterUserPassword', str),
'master_username': ('MasterUsername', str),
'monitoring_interval': ('MonitoringInterval', int),
'monitoring_role_arn': ('MonitoringRoleArn', str),
'multi_az': ('MultiAZ', bool),
'name': ('DBInstanceIdentifier', str),
'new_db_instance_identifier': ('NewDBInstanceIdentifier', str),
'option_group_name': ('OptionGroupName', str),
'port': ('Port', int),
'preferred_backup_window': ('PreferredBackupWindow', str),
'preferred_maintenance_window': ('PreferredMaintenanceWindow', str),
'promotion_tier': ('PromotionTier', int),
'publicly_accessible': ('PubliclyAccessible', bool),
'storage_encrypted': ('StorageEncrypted', bool),
'storage_type': ('StorageType', str),
'tags': ('Tags', list),
'tde_credential_arn': ('TdeCredentialArn', str),
'tde_credential_password': ('TdeCredentialPassword', str),
'vpc_security_group_ids': ('VpcSecurityGroupIds', list),
}
def __virtual__():
'''
Only load if boto libraries exist and if boto libraries are greater than
a given version.
'''
return salt.utils.versions.check_boto_reqs(
boto3_ver='1.3.1'
)
def __init__(opts):
salt.utils.compat.pack_dunder(__name__)
if HAS_BOTO:
__utils__['boto3.assign_funcs'](__name__, 'rds')
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 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 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 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 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_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_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_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 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 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_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_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 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 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_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_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_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 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_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 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 _tag_doc(tags):
taglist = []
if tags is not None:
for k, v in six.iteritems(tags):
if six.text_type(k).startswith('__'):
continue
taglist.append({'Key': six.text_type(k), 'Value': six.text_type(v)})
return taglist
|
saltstack/salt
|
salt/modules/boto_rds.py
|
create_parameter_group
|
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)}
|
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"
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_rds.py#L413-L446
|
[
"def _tag_doc(tags):\n taglist = []\n if tags is not None:\n for k, v in six.iteritems(tags):\n if six.text_type(k).startswith('__'):\n continue\n taglist.append({'Key': six.text_type(k), 'Value': six.text_type(v)})\n return taglist\n"
] |
# -*- coding: utf-8 -*-
'''
Connection module for Amazon RDS
.. versionadded:: 2015.8.0
:configuration: This module accepts explicit rds credentials but can also
utilize IAM roles assigned to the instance through Instance Profiles.
Dynamic credentials are then automatically obtained from AWS API and no
further configuration is necessary. More Information available at:
.. code-block:: text
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
If IAM roles are not used you need to specify them either in a pillar or
in the minion's config file:
.. code-block:: yaml
rds.keyid: GKTADJGHEIQSXMKKRBJ08H
rds.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
rds.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
:depends: boto3
'''
# keep lint from choking on _get_conn and _cache_id
#pylint: disable=E0602
# pylint whinging perfectly valid code
#pylint: disable=W0106
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import time
# Import Salt libs
import salt.utils.compat
import salt.utils.odict as odict
import salt.utils.versions
from salt.exceptions import SaltInvocationError
log = logging.getLogger(__name__)
# Import third party libs
from salt.ext import six
# pylint: disable=import-error
try:
#pylint: disable=unused-import
import boto
import boto3
#pylint: enable=unused-import
from botocore.exceptions import ClientError
logging.getLogger('boto').setLevel(logging.CRITICAL)
logging.getLogger('boto3').setLevel(logging.CRITICAL)
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
# pylint: enable=import-error
boto3_param_map = {
'allocated_storage': ('AllocatedStorage', int),
'allow_major_version_upgrade': ('AllowMajorVersionUpgrade', bool),
'apply_immediately': ('ApplyImmediately', bool),
'auto_minor_version_upgrade': ('AutoMinorVersionUpgrade', bool),
'availability_zone': ('AvailabilityZone', str),
'backup_retention_period': ('BackupRetentionPeriod', int),
'ca_certificate_identifier': ('CACertificateIdentifier', str),
'character_set_name': ('CharacterSetName', str),
'copy_tags_to_snapshot': ('CopyTagsToSnapshot', bool),
'db_cluster_identifier': ('DBClusterIdentifier', str),
'db_instance_class': ('DBInstanceClass', str),
'db_name': ('DBName', str),
'db_parameter_group_name': ('DBParameterGroupName', str),
'db_port_number': ('DBPortNumber', int),
'db_security_groups': ('DBSecurityGroups', list),
'db_subnet_group_name': ('DBSubnetGroupName', str),
'domain': ('Domain', str),
'domain_iam_role_name': ('DomainIAMRoleName', str),
'engine': ('Engine', str),
'engine_version': ('EngineVersion', str),
'iops': ('Iops', int),
'kms_key_id': ('KmsKeyId', str),
'license_model': ('LicenseModel', str),
'master_user_password': ('MasterUserPassword', str),
'master_username': ('MasterUsername', str),
'monitoring_interval': ('MonitoringInterval', int),
'monitoring_role_arn': ('MonitoringRoleArn', str),
'multi_az': ('MultiAZ', bool),
'name': ('DBInstanceIdentifier', str),
'new_db_instance_identifier': ('NewDBInstanceIdentifier', str),
'option_group_name': ('OptionGroupName', str),
'port': ('Port', int),
'preferred_backup_window': ('PreferredBackupWindow', str),
'preferred_maintenance_window': ('PreferredMaintenanceWindow', str),
'promotion_tier': ('PromotionTier', int),
'publicly_accessible': ('PubliclyAccessible', bool),
'storage_encrypted': ('StorageEncrypted', bool),
'storage_type': ('StorageType', str),
'tags': ('Tags', list),
'tde_credential_arn': ('TdeCredentialArn', str),
'tde_credential_password': ('TdeCredentialPassword', str),
'vpc_security_group_ids': ('VpcSecurityGroupIds', list),
}
def __virtual__():
'''
Only load if boto libraries exist and if boto libraries are greater than
a given version.
'''
return salt.utils.versions.check_boto_reqs(
boto3_ver='1.3.1'
)
def __init__(opts):
salt.utils.compat.pack_dunder(__name__)
if HAS_BOTO:
__utils__['boto3.assign_funcs'](__name__, 'rds')
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 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 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 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 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_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_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_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 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 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_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_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 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 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_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_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_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 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_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 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 _tag_doc(tags):
taglist = []
if tags is not None:
for k, v in six.iteritems(tags):
if six.text_type(k).startswith('__'):
continue
taglist.append({'Key': six.text_type(k), 'Value': six.text_type(v)})
return taglist
|
saltstack/salt
|
salt/modules/boto_rds.py
|
create_subnet_group
|
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)}
|
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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_rds.py#L449-L477
|
[
"def _tag_doc(tags):\n taglist = []\n if tags is not None:\n for k, v in six.iteritems(tags):\n if six.text_type(k).startswith('__'):\n continue\n taglist.append({'Key': six.text_type(k), 'Value': six.text_type(v)})\n return taglist\n"
] |
# -*- coding: utf-8 -*-
'''
Connection module for Amazon RDS
.. versionadded:: 2015.8.0
:configuration: This module accepts explicit rds credentials but can also
utilize IAM roles assigned to the instance through Instance Profiles.
Dynamic credentials are then automatically obtained from AWS API and no
further configuration is necessary. More Information available at:
.. code-block:: text
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
If IAM roles are not used you need to specify them either in a pillar or
in the minion's config file:
.. code-block:: yaml
rds.keyid: GKTADJGHEIQSXMKKRBJ08H
rds.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
rds.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
:depends: boto3
'''
# keep lint from choking on _get_conn and _cache_id
#pylint: disable=E0602
# pylint whinging perfectly valid code
#pylint: disable=W0106
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import time
# Import Salt libs
import salt.utils.compat
import salt.utils.odict as odict
import salt.utils.versions
from salt.exceptions import SaltInvocationError
log = logging.getLogger(__name__)
# Import third party libs
from salt.ext import six
# pylint: disable=import-error
try:
#pylint: disable=unused-import
import boto
import boto3
#pylint: enable=unused-import
from botocore.exceptions import ClientError
logging.getLogger('boto').setLevel(logging.CRITICAL)
logging.getLogger('boto3').setLevel(logging.CRITICAL)
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
# pylint: enable=import-error
boto3_param_map = {
'allocated_storage': ('AllocatedStorage', int),
'allow_major_version_upgrade': ('AllowMajorVersionUpgrade', bool),
'apply_immediately': ('ApplyImmediately', bool),
'auto_minor_version_upgrade': ('AutoMinorVersionUpgrade', bool),
'availability_zone': ('AvailabilityZone', str),
'backup_retention_period': ('BackupRetentionPeriod', int),
'ca_certificate_identifier': ('CACertificateIdentifier', str),
'character_set_name': ('CharacterSetName', str),
'copy_tags_to_snapshot': ('CopyTagsToSnapshot', bool),
'db_cluster_identifier': ('DBClusterIdentifier', str),
'db_instance_class': ('DBInstanceClass', str),
'db_name': ('DBName', str),
'db_parameter_group_name': ('DBParameterGroupName', str),
'db_port_number': ('DBPortNumber', int),
'db_security_groups': ('DBSecurityGroups', list),
'db_subnet_group_name': ('DBSubnetGroupName', str),
'domain': ('Domain', str),
'domain_iam_role_name': ('DomainIAMRoleName', str),
'engine': ('Engine', str),
'engine_version': ('EngineVersion', str),
'iops': ('Iops', int),
'kms_key_id': ('KmsKeyId', str),
'license_model': ('LicenseModel', str),
'master_user_password': ('MasterUserPassword', str),
'master_username': ('MasterUsername', str),
'monitoring_interval': ('MonitoringInterval', int),
'monitoring_role_arn': ('MonitoringRoleArn', str),
'multi_az': ('MultiAZ', bool),
'name': ('DBInstanceIdentifier', str),
'new_db_instance_identifier': ('NewDBInstanceIdentifier', str),
'option_group_name': ('OptionGroupName', str),
'port': ('Port', int),
'preferred_backup_window': ('PreferredBackupWindow', str),
'preferred_maintenance_window': ('PreferredMaintenanceWindow', str),
'promotion_tier': ('PromotionTier', int),
'publicly_accessible': ('PubliclyAccessible', bool),
'storage_encrypted': ('StorageEncrypted', bool),
'storage_type': ('StorageType', str),
'tags': ('Tags', list),
'tde_credential_arn': ('TdeCredentialArn', str),
'tde_credential_password': ('TdeCredentialPassword', str),
'vpc_security_group_ids': ('VpcSecurityGroupIds', list),
}
def __virtual__():
'''
Only load if boto libraries exist and if boto libraries are greater than
a given version.
'''
return salt.utils.versions.check_boto_reqs(
boto3_ver='1.3.1'
)
def __init__(opts):
salt.utils.compat.pack_dunder(__name__)
if HAS_BOTO:
__utils__['boto3.assign_funcs'](__name__, 'rds')
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 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 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 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 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_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_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_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 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 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_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_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 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 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_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_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_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 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_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 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 _tag_doc(tags):
taglist = []
if tags is not None:
for k, v in six.iteritems(tags):
if six.text_type(k).startswith('__'):
continue
taglist.append({'Key': six.text_type(k), 'Value': six.text_type(v)})
return taglist
|
saltstack/salt
|
salt/modules/boto_rds.py
|
update_parameter_group
|
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)}
|
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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_rds.py#L480-L522
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n",
"def update(*args, **kwds): # pylint: disable=E0211\n '''od.update(E, **F) -> None. Update od from dict/iterable E and F.\n\n If E is a dict instance, does: for k in E: od[k] = E[k]\n If E has a .keys() method, does: for k in E.keys(): od[k] = E[k]\n Or if E is an iterable of items, does: for k, v in E: od[k] = v\n In either case, this is followed by: for k, v in F.items(): od[k] = v\n\n '''\n if len(args) > 2:\n raise TypeError(\n 'update() takes at most 2 positional '\n 'arguments ({0} given)'.format(len(args))\n )\n elif not args:\n raise TypeError('update() takes at least 1 argument (0 given)')\n self = args[0]\n # Make progressively weaker assumptions about \"other\"\n other = ()\n if len(args) == 2:\n other = args[1]\n if isinstance(other, dict):\n for key in other:\n self[key] = other[key]\n elif hasattr(other, 'keys'):\n for key in other:\n self[key] = other[key]\n else:\n for key, value in other:\n self[key] = value\n for key, value in six.iteritems(kwds):\n self[key] = value\n"
] |
# -*- coding: utf-8 -*-
'''
Connection module for Amazon RDS
.. versionadded:: 2015.8.0
:configuration: This module accepts explicit rds credentials but can also
utilize IAM roles assigned to the instance through Instance Profiles.
Dynamic credentials are then automatically obtained from AWS API and no
further configuration is necessary. More Information available at:
.. code-block:: text
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
If IAM roles are not used you need to specify them either in a pillar or
in the minion's config file:
.. code-block:: yaml
rds.keyid: GKTADJGHEIQSXMKKRBJ08H
rds.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
rds.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
:depends: boto3
'''
# keep lint from choking on _get_conn and _cache_id
#pylint: disable=E0602
# pylint whinging perfectly valid code
#pylint: disable=W0106
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import time
# Import Salt libs
import salt.utils.compat
import salt.utils.odict as odict
import salt.utils.versions
from salt.exceptions import SaltInvocationError
log = logging.getLogger(__name__)
# Import third party libs
from salt.ext import six
# pylint: disable=import-error
try:
#pylint: disable=unused-import
import boto
import boto3
#pylint: enable=unused-import
from botocore.exceptions import ClientError
logging.getLogger('boto').setLevel(logging.CRITICAL)
logging.getLogger('boto3').setLevel(logging.CRITICAL)
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
# pylint: enable=import-error
boto3_param_map = {
'allocated_storage': ('AllocatedStorage', int),
'allow_major_version_upgrade': ('AllowMajorVersionUpgrade', bool),
'apply_immediately': ('ApplyImmediately', bool),
'auto_minor_version_upgrade': ('AutoMinorVersionUpgrade', bool),
'availability_zone': ('AvailabilityZone', str),
'backup_retention_period': ('BackupRetentionPeriod', int),
'ca_certificate_identifier': ('CACertificateIdentifier', str),
'character_set_name': ('CharacterSetName', str),
'copy_tags_to_snapshot': ('CopyTagsToSnapshot', bool),
'db_cluster_identifier': ('DBClusterIdentifier', str),
'db_instance_class': ('DBInstanceClass', str),
'db_name': ('DBName', str),
'db_parameter_group_name': ('DBParameterGroupName', str),
'db_port_number': ('DBPortNumber', int),
'db_security_groups': ('DBSecurityGroups', list),
'db_subnet_group_name': ('DBSubnetGroupName', str),
'domain': ('Domain', str),
'domain_iam_role_name': ('DomainIAMRoleName', str),
'engine': ('Engine', str),
'engine_version': ('EngineVersion', str),
'iops': ('Iops', int),
'kms_key_id': ('KmsKeyId', str),
'license_model': ('LicenseModel', str),
'master_user_password': ('MasterUserPassword', str),
'master_username': ('MasterUsername', str),
'monitoring_interval': ('MonitoringInterval', int),
'monitoring_role_arn': ('MonitoringRoleArn', str),
'multi_az': ('MultiAZ', bool),
'name': ('DBInstanceIdentifier', str),
'new_db_instance_identifier': ('NewDBInstanceIdentifier', str),
'option_group_name': ('OptionGroupName', str),
'port': ('Port', int),
'preferred_backup_window': ('PreferredBackupWindow', str),
'preferred_maintenance_window': ('PreferredMaintenanceWindow', str),
'promotion_tier': ('PromotionTier', int),
'publicly_accessible': ('PubliclyAccessible', bool),
'storage_encrypted': ('StorageEncrypted', bool),
'storage_type': ('StorageType', str),
'tags': ('Tags', list),
'tde_credential_arn': ('TdeCredentialArn', str),
'tde_credential_password': ('TdeCredentialPassword', str),
'vpc_security_group_ids': ('VpcSecurityGroupIds', list),
}
def __virtual__():
'''
Only load if boto libraries exist and if boto libraries are greater than
a given version.
'''
return salt.utils.versions.check_boto_reqs(
boto3_ver='1.3.1'
)
def __init__(opts):
salt.utils.compat.pack_dunder(__name__)
if HAS_BOTO:
__utils__['boto3.assign_funcs'](__name__, 'rds')
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 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 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 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 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_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_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_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_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 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_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_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 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 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_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_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_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 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_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 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 _tag_doc(tags):
taglist = []
if tags is not None:
for k, v in six.iteritems(tags):
if six.text_type(k).startswith('__'):
continue
taglist.append({'Key': six.text_type(k), 'Value': six.text_type(v)})
return taglist
|
saltstack/salt
|
salt/modules/boto_rds.py
|
describe
|
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}
|
Return RDS instance details.
CLI example::
salt myminion boto_rds.describe myrds
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_rds.py#L525-L572
| null |
# -*- coding: utf-8 -*-
'''
Connection module for Amazon RDS
.. versionadded:: 2015.8.0
:configuration: This module accepts explicit rds credentials but can also
utilize IAM roles assigned to the instance through Instance Profiles.
Dynamic credentials are then automatically obtained from AWS API and no
further configuration is necessary. More Information available at:
.. code-block:: text
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
If IAM roles are not used you need to specify them either in a pillar or
in the minion's config file:
.. code-block:: yaml
rds.keyid: GKTADJGHEIQSXMKKRBJ08H
rds.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
rds.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
:depends: boto3
'''
# keep lint from choking on _get_conn and _cache_id
#pylint: disable=E0602
# pylint whinging perfectly valid code
#pylint: disable=W0106
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import time
# Import Salt libs
import salt.utils.compat
import salt.utils.odict as odict
import salt.utils.versions
from salt.exceptions import SaltInvocationError
log = logging.getLogger(__name__)
# Import third party libs
from salt.ext import six
# pylint: disable=import-error
try:
#pylint: disable=unused-import
import boto
import boto3
#pylint: enable=unused-import
from botocore.exceptions import ClientError
logging.getLogger('boto').setLevel(logging.CRITICAL)
logging.getLogger('boto3').setLevel(logging.CRITICAL)
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
# pylint: enable=import-error
boto3_param_map = {
'allocated_storage': ('AllocatedStorage', int),
'allow_major_version_upgrade': ('AllowMajorVersionUpgrade', bool),
'apply_immediately': ('ApplyImmediately', bool),
'auto_minor_version_upgrade': ('AutoMinorVersionUpgrade', bool),
'availability_zone': ('AvailabilityZone', str),
'backup_retention_period': ('BackupRetentionPeriod', int),
'ca_certificate_identifier': ('CACertificateIdentifier', str),
'character_set_name': ('CharacterSetName', str),
'copy_tags_to_snapshot': ('CopyTagsToSnapshot', bool),
'db_cluster_identifier': ('DBClusterIdentifier', str),
'db_instance_class': ('DBInstanceClass', str),
'db_name': ('DBName', str),
'db_parameter_group_name': ('DBParameterGroupName', str),
'db_port_number': ('DBPortNumber', int),
'db_security_groups': ('DBSecurityGroups', list),
'db_subnet_group_name': ('DBSubnetGroupName', str),
'domain': ('Domain', str),
'domain_iam_role_name': ('DomainIAMRoleName', str),
'engine': ('Engine', str),
'engine_version': ('EngineVersion', str),
'iops': ('Iops', int),
'kms_key_id': ('KmsKeyId', str),
'license_model': ('LicenseModel', str),
'master_user_password': ('MasterUserPassword', str),
'master_username': ('MasterUsername', str),
'monitoring_interval': ('MonitoringInterval', int),
'monitoring_role_arn': ('MonitoringRoleArn', str),
'multi_az': ('MultiAZ', bool),
'name': ('DBInstanceIdentifier', str),
'new_db_instance_identifier': ('NewDBInstanceIdentifier', str),
'option_group_name': ('OptionGroupName', str),
'port': ('Port', int),
'preferred_backup_window': ('PreferredBackupWindow', str),
'preferred_maintenance_window': ('PreferredMaintenanceWindow', str),
'promotion_tier': ('PromotionTier', int),
'publicly_accessible': ('PubliclyAccessible', bool),
'storage_encrypted': ('StorageEncrypted', bool),
'storage_type': ('StorageType', str),
'tags': ('Tags', list),
'tde_credential_arn': ('TdeCredentialArn', str),
'tde_credential_password': ('TdeCredentialPassword', str),
'vpc_security_group_ids': ('VpcSecurityGroupIds', list),
}
def __virtual__():
'''
Only load if boto libraries exist and if boto libraries are greater than
a given version.
'''
return salt.utils.versions.check_boto_reqs(
boto3_ver='1.3.1'
)
def __init__(opts):
salt.utils.compat.pack_dunder(__name__)
if HAS_BOTO:
__utils__['boto3.assign_funcs'](__name__, 'rds')
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 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 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 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 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_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_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_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_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 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 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_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 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 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_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_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_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 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_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 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 _tag_doc(tags):
taglist = []
if tags is not None:
for k, v in six.iteritems(tags):
if six.text_type(k).startswith('__'):
continue
taglist.append({'Key': six.text_type(k), 'Value': six.text_type(v)})
return taglist
|
saltstack/salt
|
salt/modules/boto_rds.py
|
describe_db_instances
|
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 []
|
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'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_rds.py#L575-L600
| null |
# -*- coding: utf-8 -*-
'''
Connection module for Amazon RDS
.. versionadded:: 2015.8.0
:configuration: This module accepts explicit rds credentials but can also
utilize IAM roles assigned to the instance through Instance Profiles.
Dynamic credentials are then automatically obtained from AWS API and no
further configuration is necessary. More Information available at:
.. code-block:: text
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
If IAM roles are not used you need to specify them either in a pillar or
in the minion's config file:
.. code-block:: yaml
rds.keyid: GKTADJGHEIQSXMKKRBJ08H
rds.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
rds.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
:depends: boto3
'''
# keep lint from choking on _get_conn and _cache_id
#pylint: disable=E0602
# pylint whinging perfectly valid code
#pylint: disable=W0106
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import time
# Import Salt libs
import salt.utils.compat
import salt.utils.odict as odict
import salt.utils.versions
from salt.exceptions import SaltInvocationError
log = logging.getLogger(__name__)
# Import third party libs
from salt.ext import six
# pylint: disable=import-error
try:
#pylint: disable=unused-import
import boto
import boto3
#pylint: enable=unused-import
from botocore.exceptions import ClientError
logging.getLogger('boto').setLevel(logging.CRITICAL)
logging.getLogger('boto3').setLevel(logging.CRITICAL)
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
# pylint: enable=import-error
boto3_param_map = {
'allocated_storage': ('AllocatedStorage', int),
'allow_major_version_upgrade': ('AllowMajorVersionUpgrade', bool),
'apply_immediately': ('ApplyImmediately', bool),
'auto_minor_version_upgrade': ('AutoMinorVersionUpgrade', bool),
'availability_zone': ('AvailabilityZone', str),
'backup_retention_period': ('BackupRetentionPeriod', int),
'ca_certificate_identifier': ('CACertificateIdentifier', str),
'character_set_name': ('CharacterSetName', str),
'copy_tags_to_snapshot': ('CopyTagsToSnapshot', bool),
'db_cluster_identifier': ('DBClusterIdentifier', str),
'db_instance_class': ('DBInstanceClass', str),
'db_name': ('DBName', str),
'db_parameter_group_name': ('DBParameterGroupName', str),
'db_port_number': ('DBPortNumber', int),
'db_security_groups': ('DBSecurityGroups', list),
'db_subnet_group_name': ('DBSubnetGroupName', str),
'domain': ('Domain', str),
'domain_iam_role_name': ('DomainIAMRoleName', str),
'engine': ('Engine', str),
'engine_version': ('EngineVersion', str),
'iops': ('Iops', int),
'kms_key_id': ('KmsKeyId', str),
'license_model': ('LicenseModel', str),
'master_user_password': ('MasterUserPassword', str),
'master_username': ('MasterUsername', str),
'monitoring_interval': ('MonitoringInterval', int),
'monitoring_role_arn': ('MonitoringRoleArn', str),
'multi_az': ('MultiAZ', bool),
'name': ('DBInstanceIdentifier', str),
'new_db_instance_identifier': ('NewDBInstanceIdentifier', str),
'option_group_name': ('OptionGroupName', str),
'port': ('Port', int),
'preferred_backup_window': ('PreferredBackupWindow', str),
'preferred_maintenance_window': ('PreferredMaintenanceWindow', str),
'promotion_tier': ('PromotionTier', int),
'publicly_accessible': ('PubliclyAccessible', bool),
'storage_encrypted': ('StorageEncrypted', bool),
'storage_type': ('StorageType', str),
'tags': ('Tags', list),
'tde_credential_arn': ('TdeCredentialArn', str),
'tde_credential_password': ('TdeCredentialPassword', str),
'vpc_security_group_ids': ('VpcSecurityGroupIds', list),
}
def __virtual__():
'''
Only load if boto libraries exist and if boto libraries are greater than
a given version.
'''
return salt.utils.versions.check_boto_reqs(
boto3_ver='1.3.1'
)
def __init__(opts):
salt.utils.compat.pack_dunder(__name__)
if HAS_BOTO:
__utils__['boto3.assign_funcs'](__name__, 'rds')
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 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 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 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 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_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_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_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_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 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 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_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 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 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_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_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_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 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_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 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 _tag_doc(tags):
taglist = []
if tags is not None:
for k, v in six.iteritems(tags):
if six.text_type(k).startswith('__'):
continue
taglist.append({'Key': six.text_type(k), 'Value': six.text_type(v)})
return taglist
|
saltstack/salt
|
salt/modules/boto_rds.py
|
describe_db_subnet_groups
|
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]
|
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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_rds.py#L603-L622
| null |
# -*- coding: utf-8 -*-
'''
Connection module for Amazon RDS
.. versionadded:: 2015.8.0
:configuration: This module accepts explicit rds credentials but can also
utilize IAM roles assigned to the instance through Instance Profiles.
Dynamic credentials are then automatically obtained from AWS API and no
further configuration is necessary. More Information available at:
.. code-block:: text
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
If IAM roles are not used you need to specify them either in a pillar or
in the minion's config file:
.. code-block:: yaml
rds.keyid: GKTADJGHEIQSXMKKRBJ08H
rds.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
rds.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
:depends: boto3
'''
# keep lint from choking on _get_conn and _cache_id
#pylint: disable=E0602
# pylint whinging perfectly valid code
#pylint: disable=W0106
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import time
# Import Salt libs
import salt.utils.compat
import salt.utils.odict as odict
import salt.utils.versions
from salt.exceptions import SaltInvocationError
log = logging.getLogger(__name__)
# Import third party libs
from salt.ext import six
# pylint: disable=import-error
try:
#pylint: disable=unused-import
import boto
import boto3
#pylint: enable=unused-import
from botocore.exceptions import ClientError
logging.getLogger('boto').setLevel(logging.CRITICAL)
logging.getLogger('boto3').setLevel(logging.CRITICAL)
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
# pylint: enable=import-error
boto3_param_map = {
'allocated_storage': ('AllocatedStorage', int),
'allow_major_version_upgrade': ('AllowMajorVersionUpgrade', bool),
'apply_immediately': ('ApplyImmediately', bool),
'auto_minor_version_upgrade': ('AutoMinorVersionUpgrade', bool),
'availability_zone': ('AvailabilityZone', str),
'backup_retention_period': ('BackupRetentionPeriod', int),
'ca_certificate_identifier': ('CACertificateIdentifier', str),
'character_set_name': ('CharacterSetName', str),
'copy_tags_to_snapshot': ('CopyTagsToSnapshot', bool),
'db_cluster_identifier': ('DBClusterIdentifier', str),
'db_instance_class': ('DBInstanceClass', str),
'db_name': ('DBName', str),
'db_parameter_group_name': ('DBParameterGroupName', str),
'db_port_number': ('DBPortNumber', int),
'db_security_groups': ('DBSecurityGroups', list),
'db_subnet_group_name': ('DBSubnetGroupName', str),
'domain': ('Domain', str),
'domain_iam_role_name': ('DomainIAMRoleName', str),
'engine': ('Engine', str),
'engine_version': ('EngineVersion', str),
'iops': ('Iops', int),
'kms_key_id': ('KmsKeyId', str),
'license_model': ('LicenseModel', str),
'master_user_password': ('MasterUserPassword', str),
'master_username': ('MasterUsername', str),
'monitoring_interval': ('MonitoringInterval', int),
'monitoring_role_arn': ('MonitoringRoleArn', str),
'multi_az': ('MultiAZ', bool),
'name': ('DBInstanceIdentifier', str),
'new_db_instance_identifier': ('NewDBInstanceIdentifier', str),
'option_group_name': ('OptionGroupName', str),
'port': ('Port', int),
'preferred_backup_window': ('PreferredBackupWindow', str),
'preferred_maintenance_window': ('PreferredMaintenanceWindow', str),
'promotion_tier': ('PromotionTier', int),
'publicly_accessible': ('PubliclyAccessible', bool),
'storage_encrypted': ('StorageEncrypted', bool),
'storage_type': ('StorageType', str),
'tags': ('Tags', list),
'tde_credential_arn': ('TdeCredentialArn', str),
'tde_credential_password': ('TdeCredentialPassword', str),
'vpc_security_group_ids': ('VpcSecurityGroupIds', list),
}
def __virtual__():
'''
Only load if boto libraries exist and if boto libraries are greater than
a given version.
'''
return salt.utils.versions.check_boto_reqs(
boto3_ver='1.3.1'
)
def __init__(opts):
salt.utils.compat.pack_dunder(__name__)
if HAS_BOTO:
__utils__['boto3.assign_funcs'](__name__, 'rds')
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 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 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 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 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_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_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_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_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 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 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_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 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 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_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_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_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 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_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 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 _tag_doc(tags):
taglist = []
if tags is not None:
for k, v in six.iteritems(tags):
if six.text_type(k).startswith('__'):
continue
taglist.append({'Key': six.text_type(k), 'Value': six.text_type(v)})
return taglist
|
saltstack/salt
|
salt/modules/boto_rds.py
|
get_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
|
Return the endpoint of an RDS instance.
CLI example::
salt myminion boto_rds.get_endpoint myrds
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_rds.py#L625-L651
| null |
# -*- coding: utf-8 -*-
'''
Connection module for Amazon RDS
.. versionadded:: 2015.8.0
:configuration: This module accepts explicit rds credentials but can also
utilize IAM roles assigned to the instance through Instance Profiles.
Dynamic credentials are then automatically obtained from AWS API and no
further configuration is necessary. More Information available at:
.. code-block:: text
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
If IAM roles are not used you need to specify them either in a pillar or
in the minion's config file:
.. code-block:: yaml
rds.keyid: GKTADJGHEIQSXMKKRBJ08H
rds.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
rds.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
:depends: boto3
'''
# keep lint from choking on _get_conn and _cache_id
#pylint: disable=E0602
# pylint whinging perfectly valid code
#pylint: disable=W0106
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import time
# Import Salt libs
import salt.utils.compat
import salt.utils.odict as odict
import salt.utils.versions
from salt.exceptions import SaltInvocationError
log = logging.getLogger(__name__)
# Import third party libs
from salt.ext import six
# pylint: disable=import-error
try:
#pylint: disable=unused-import
import boto
import boto3
#pylint: enable=unused-import
from botocore.exceptions import ClientError
logging.getLogger('boto').setLevel(logging.CRITICAL)
logging.getLogger('boto3').setLevel(logging.CRITICAL)
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
# pylint: enable=import-error
boto3_param_map = {
'allocated_storage': ('AllocatedStorage', int),
'allow_major_version_upgrade': ('AllowMajorVersionUpgrade', bool),
'apply_immediately': ('ApplyImmediately', bool),
'auto_minor_version_upgrade': ('AutoMinorVersionUpgrade', bool),
'availability_zone': ('AvailabilityZone', str),
'backup_retention_period': ('BackupRetentionPeriod', int),
'ca_certificate_identifier': ('CACertificateIdentifier', str),
'character_set_name': ('CharacterSetName', str),
'copy_tags_to_snapshot': ('CopyTagsToSnapshot', bool),
'db_cluster_identifier': ('DBClusterIdentifier', str),
'db_instance_class': ('DBInstanceClass', str),
'db_name': ('DBName', str),
'db_parameter_group_name': ('DBParameterGroupName', str),
'db_port_number': ('DBPortNumber', int),
'db_security_groups': ('DBSecurityGroups', list),
'db_subnet_group_name': ('DBSubnetGroupName', str),
'domain': ('Domain', str),
'domain_iam_role_name': ('DomainIAMRoleName', str),
'engine': ('Engine', str),
'engine_version': ('EngineVersion', str),
'iops': ('Iops', int),
'kms_key_id': ('KmsKeyId', str),
'license_model': ('LicenseModel', str),
'master_user_password': ('MasterUserPassword', str),
'master_username': ('MasterUsername', str),
'monitoring_interval': ('MonitoringInterval', int),
'monitoring_role_arn': ('MonitoringRoleArn', str),
'multi_az': ('MultiAZ', bool),
'name': ('DBInstanceIdentifier', str),
'new_db_instance_identifier': ('NewDBInstanceIdentifier', str),
'option_group_name': ('OptionGroupName', str),
'port': ('Port', int),
'preferred_backup_window': ('PreferredBackupWindow', str),
'preferred_maintenance_window': ('PreferredMaintenanceWindow', str),
'promotion_tier': ('PromotionTier', int),
'publicly_accessible': ('PubliclyAccessible', bool),
'storage_encrypted': ('StorageEncrypted', bool),
'storage_type': ('StorageType', str),
'tags': ('Tags', list),
'tde_credential_arn': ('TdeCredentialArn', str),
'tde_credential_password': ('TdeCredentialPassword', str),
'vpc_security_group_ids': ('VpcSecurityGroupIds', list),
}
def __virtual__():
'''
Only load if boto libraries exist and if boto libraries are greater than
a given version.
'''
return salt.utils.versions.check_boto_reqs(
boto3_ver='1.3.1'
)
def __init__(opts):
salt.utils.compat.pack_dunder(__name__)
if HAS_BOTO:
__utils__['boto3.assign_funcs'](__name__, 'rds')
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 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 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 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 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_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_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_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_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 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 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_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_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 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_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_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_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 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_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 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 _tag_doc(tags):
taglist = []
if tags is not None:
for k, v in six.iteritems(tags):
if six.text_type(k).startswith('__'):
continue
taglist.append({'Key': six.text_type(k), 'Value': six.text_type(v)})
return taglist
|
saltstack/salt
|
salt/modules/boto_rds.py
|
delete
|
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)}
|
Delete an RDS instance.
CLI example::
salt myminion boto_rds.delete myrds skip_final_snapshot=True \
region=us-east-1
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_rds.py#L654-L708
| null |
# -*- coding: utf-8 -*-
'''
Connection module for Amazon RDS
.. versionadded:: 2015.8.0
:configuration: This module accepts explicit rds credentials but can also
utilize IAM roles assigned to the instance through Instance Profiles.
Dynamic credentials are then automatically obtained from AWS API and no
further configuration is necessary. More Information available at:
.. code-block:: text
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
If IAM roles are not used you need to specify them either in a pillar or
in the minion's config file:
.. code-block:: yaml
rds.keyid: GKTADJGHEIQSXMKKRBJ08H
rds.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
rds.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
:depends: boto3
'''
# keep lint from choking on _get_conn and _cache_id
#pylint: disable=E0602
# pylint whinging perfectly valid code
#pylint: disable=W0106
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import time
# Import Salt libs
import salt.utils.compat
import salt.utils.odict as odict
import salt.utils.versions
from salt.exceptions import SaltInvocationError
log = logging.getLogger(__name__)
# Import third party libs
from salt.ext import six
# pylint: disable=import-error
try:
#pylint: disable=unused-import
import boto
import boto3
#pylint: enable=unused-import
from botocore.exceptions import ClientError
logging.getLogger('boto').setLevel(logging.CRITICAL)
logging.getLogger('boto3').setLevel(logging.CRITICAL)
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
# pylint: enable=import-error
boto3_param_map = {
'allocated_storage': ('AllocatedStorage', int),
'allow_major_version_upgrade': ('AllowMajorVersionUpgrade', bool),
'apply_immediately': ('ApplyImmediately', bool),
'auto_minor_version_upgrade': ('AutoMinorVersionUpgrade', bool),
'availability_zone': ('AvailabilityZone', str),
'backup_retention_period': ('BackupRetentionPeriod', int),
'ca_certificate_identifier': ('CACertificateIdentifier', str),
'character_set_name': ('CharacterSetName', str),
'copy_tags_to_snapshot': ('CopyTagsToSnapshot', bool),
'db_cluster_identifier': ('DBClusterIdentifier', str),
'db_instance_class': ('DBInstanceClass', str),
'db_name': ('DBName', str),
'db_parameter_group_name': ('DBParameterGroupName', str),
'db_port_number': ('DBPortNumber', int),
'db_security_groups': ('DBSecurityGroups', list),
'db_subnet_group_name': ('DBSubnetGroupName', str),
'domain': ('Domain', str),
'domain_iam_role_name': ('DomainIAMRoleName', str),
'engine': ('Engine', str),
'engine_version': ('EngineVersion', str),
'iops': ('Iops', int),
'kms_key_id': ('KmsKeyId', str),
'license_model': ('LicenseModel', str),
'master_user_password': ('MasterUserPassword', str),
'master_username': ('MasterUsername', str),
'monitoring_interval': ('MonitoringInterval', int),
'monitoring_role_arn': ('MonitoringRoleArn', str),
'multi_az': ('MultiAZ', bool),
'name': ('DBInstanceIdentifier', str),
'new_db_instance_identifier': ('NewDBInstanceIdentifier', str),
'option_group_name': ('OptionGroupName', str),
'port': ('Port', int),
'preferred_backup_window': ('PreferredBackupWindow', str),
'preferred_maintenance_window': ('PreferredMaintenanceWindow', str),
'promotion_tier': ('PromotionTier', int),
'publicly_accessible': ('PubliclyAccessible', bool),
'storage_encrypted': ('StorageEncrypted', bool),
'storage_type': ('StorageType', str),
'tags': ('Tags', list),
'tde_credential_arn': ('TdeCredentialArn', str),
'tde_credential_password': ('TdeCredentialPassword', str),
'vpc_security_group_ids': ('VpcSecurityGroupIds', list),
}
def __virtual__():
'''
Only load if boto libraries exist and if boto libraries are greater than
a given version.
'''
return salt.utils.versions.check_boto_reqs(
boto3_ver='1.3.1'
)
def __init__(opts):
salt.utils.compat.pack_dunder(__name__)
if HAS_BOTO:
__utils__['boto3.assign_funcs'](__name__, 'rds')
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 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 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 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 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_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_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_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_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 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 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_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_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 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 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_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_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 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_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 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 _tag_doc(tags):
taglist = []
if tags is not None:
for k, v in six.iteritems(tags):
if six.text_type(k).startswith('__'):
continue
taglist.append({'Key': six.text_type(k), 'Value': six.text_type(v)})
return taglist
|
saltstack/salt
|
salt/modules/boto_rds.py
|
delete_option_group
|
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)}
|
Delete an RDS option group.
CLI example::
salt myminion boto_rds.delete_option_group my-opt-group \
region=us-east-1
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_rds.py#L711-L733
| null |
# -*- coding: utf-8 -*-
'''
Connection module for Amazon RDS
.. versionadded:: 2015.8.0
:configuration: This module accepts explicit rds credentials but can also
utilize IAM roles assigned to the instance through Instance Profiles.
Dynamic credentials are then automatically obtained from AWS API and no
further configuration is necessary. More Information available at:
.. code-block:: text
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
If IAM roles are not used you need to specify them either in a pillar or
in the minion's config file:
.. code-block:: yaml
rds.keyid: GKTADJGHEIQSXMKKRBJ08H
rds.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
rds.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
:depends: boto3
'''
# keep lint from choking on _get_conn and _cache_id
#pylint: disable=E0602
# pylint whinging perfectly valid code
#pylint: disable=W0106
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import time
# Import Salt libs
import salt.utils.compat
import salt.utils.odict as odict
import salt.utils.versions
from salt.exceptions import SaltInvocationError
log = logging.getLogger(__name__)
# Import third party libs
from salt.ext import six
# pylint: disable=import-error
try:
#pylint: disable=unused-import
import boto
import boto3
#pylint: enable=unused-import
from botocore.exceptions import ClientError
logging.getLogger('boto').setLevel(logging.CRITICAL)
logging.getLogger('boto3').setLevel(logging.CRITICAL)
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
# pylint: enable=import-error
boto3_param_map = {
'allocated_storage': ('AllocatedStorage', int),
'allow_major_version_upgrade': ('AllowMajorVersionUpgrade', bool),
'apply_immediately': ('ApplyImmediately', bool),
'auto_minor_version_upgrade': ('AutoMinorVersionUpgrade', bool),
'availability_zone': ('AvailabilityZone', str),
'backup_retention_period': ('BackupRetentionPeriod', int),
'ca_certificate_identifier': ('CACertificateIdentifier', str),
'character_set_name': ('CharacterSetName', str),
'copy_tags_to_snapshot': ('CopyTagsToSnapshot', bool),
'db_cluster_identifier': ('DBClusterIdentifier', str),
'db_instance_class': ('DBInstanceClass', str),
'db_name': ('DBName', str),
'db_parameter_group_name': ('DBParameterGroupName', str),
'db_port_number': ('DBPortNumber', int),
'db_security_groups': ('DBSecurityGroups', list),
'db_subnet_group_name': ('DBSubnetGroupName', str),
'domain': ('Domain', str),
'domain_iam_role_name': ('DomainIAMRoleName', str),
'engine': ('Engine', str),
'engine_version': ('EngineVersion', str),
'iops': ('Iops', int),
'kms_key_id': ('KmsKeyId', str),
'license_model': ('LicenseModel', str),
'master_user_password': ('MasterUserPassword', str),
'master_username': ('MasterUsername', str),
'monitoring_interval': ('MonitoringInterval', int),
'monitoring_role_arn': ('MonitoringRoleArn', str),
'multi_az': ('MultiAZ', bool),
'name': ('DBInstanceIdentifier', str),
'new_db_instance_identifier': ('NewDBInstanceIdentifier', str),
'option_group_name': ('OptionGroupName', str),
'port': ('Port', int),
'preferred_backup_window': ('PreferredBackupWindow', str),
'preferred_maintenance_window': ('PreferredMaintenanceWindow', str),
'promotion_tier': ('PromotionTier', int),
'publicly_accessible': ('PubliclyAccessible', bool),
'storage_encrypted': ('StorageEncrypted', bool),
'storage_type': ('StorageType', str),
'tags': ('Tags', list),
'tde_credential_arn': ('TdeCredentialArn', str),
'tde_credential_password': ('TdeCredentialPassword', str),
'vpc_security_group_ids': ('VpcSecurityGroupIds', list),
}
def __virtual__():
'''
Only load if boto libraries exist and if boto libraries are greater than
a given version.
'''
return salt.utils.versions.check_boto_reqs(
boto3_ver='1.3.1'
)
def __init__(opts):
salt.utils.compat.pack_dunder(__name__)
if HAS_BOTO:
__utils__['boto3.assign_funcs'](__name__, 'rds')
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 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 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 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 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_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_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_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_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 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 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_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_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 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 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_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_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 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_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 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 _tag_doc(tags):
taglist = []
if tags is not None:
for k, v in six.iteritems(tags):
if six.text_type(k).startswith('__'):
continue
taglist.append({'Key': six.text_type(k), 'Value': six.text_type(v)})
return taglist
|
saltstack/salt
|
salt/modules/boto_rds.py
|
delete_parameter_group
|
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)}
|
Delete an RDS parameter group.
CLI example::
salt myminion boto_rds.delete_parameter_group my-param-group \
region=us-east-1
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_rds.py#L736-L755
| null |
# -*- coding: utf-8 -*-
'''
Connection module for Amazon RDS
.. versionadded:: 2015.8.0
:configuration: This module accepts explicit rds credentials but can also
utilize IAM roles assigned to the instance through Instance Profiles.
Dynamic credentials are then automatically obtained from AWS API and no
further configuration is necessary. More Information available at:
.. code-block:: text
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
If IAM roles are not used you need to specify them either in a pillar or
in the minion's config file:
.. code-block:: yaml
rds.keyid: GKTADJGHEIQSXMKKRBJ08H
rds.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
rds.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
:depends: boto3
'''
# keep lint from choking on _get_conn and _cache_id
#pylint: disable=E0602
# pylint whinging perfectly valid code
#pylint: disable=W0106
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import time
# Import Salt libs
import salt.utils.compat
import salt.utils.odict as odict
import salt.utils.versions
from salt.exceptions import SaltInvocationError
log = logging.getLogger(__name__)
# Import third party libs
from salt.ext import six
# pylint: disable=import-error
try:
#pylint: disable=unused-import
import boto
import boto3
#pylint: enable=unused-import
from botocore.exceptions import ClientError
logging.getLogger('boto').setLevel(logging.CRITICAL)
logging.getLogger('boto3').setLevel(logging.CRITICAL)
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
# pylint: enable=import-error
boto3_param_map = {
'allocated_storage': ('AllocatedStorage', int),
'allow_major_version_upgrade': ('AllowMajorVersionUpgrade', bool),
'apply_immediately': ('ApplyImmediately', bool),
'auto_minor_version_upgrade': ('AutoMinorVersionUpgrade', bool),
'availability_zone': ('AvailabilityZone', str),
'backup_retention_period': ('BackupRetentionPeriod', int),
'ca_certificate_identifier': ('CACertificateIdentifier', str),
'character_set_name': ('CharacterSetName', str),
'copy_tags_to_snapshot': ('CopyTagsToSnapshot', bool),
'db_cluster_identifier': ('DBClusterIdentifier', str),
'db_instance_class': ('DBInstanceClass', str),
'db_name': ('DBName', str),
'db_parameter_group_name': ('DBParameterGroupName', str),
'db_port_number': ('DBPortNumber', int),
'db_security_groups': ('DBSecurityGroups', list),
'db_subnet_group_name': ('DBSubnetGroupName', str),
'domain': ('Domain', str),
'domain_iam_role_name': ('DomainIAMRoleName', str),
'engine': ('Engine', str),
'engine_version': ('EngineVersion', str),
'iops': ('Iops', int),
'kms_key_id': ('KmsKeyId', str),
'license_model': ('LicenseModel', str),
'master_user_password': ('MasterUserPassword', str),
'master_username': ('MasterUsername', str),
'monitoring_interval': ('MonitoringInterval', int),
'monitoring_role_arn': ('MonitoringRoleArn', str),
'multi_az': ('MultiAZ', bool),
'name': ('DBInstanceIdentifier', str),
'new_db_instance_identifier': ('NewDBInstanceIdentifier', str),
'option_group_name': ('OptionGroupName', str),
'port': ('Port', int),
'preferred_backup_window': ('PreferredBackupWindow', str),
'preferred_maintenance_window': ('PreferredMaintenanceWindow', str),
'promotion_tier': ('PromotionTier', int),
'publicly_accessible': ('PubliclyAccessible', bool),
'storage_encrypted': ('StorageEncrypted', bool),
'storage_type': ('StorageType', str),
'tags': ('Tags', list),
'tde_credential_arn': ('TdeCredentialArn', str),
'tde_credential_password': ('TdeCredentialPassword', str),
'vpc_security_group_ids': ('VpcSecurityGroupIds', list),
}
def __virtual__():
'''
Only load if boto libraries exist and if boto libraries are greater than
a given version.
'''
return salt.utils.versions.check_boto_reqs(
boto3_ver='1.3.1'
)
def __init__(opts):
salt.utils.compat.pack_dunder(__name__)
if HAS_BOTO:
__utils__['boto3.assign_funcs'](__name__, 'rds')
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 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 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 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 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_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_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_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_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 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 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_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_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 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 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_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_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 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_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 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 _tag_doc(tags):
taglist = []
if tags is not None:
for k, v in six.iteritems(tags):
if six.text_type(k).startswith('__'):
continue
taglist.append({'Key': six.text_type(k), 'Value': six.text_type(v)})
return taglist
|
saltstack/salt
|
salt/modules/boto_rds.py
|
delete_subnet_group
|
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)}
|
Delete an RDS subnet group.
CLI example::
salt myminion boto_rds.delete_subnet_group my-subnet-group \
region=us-east-1
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_rds.py#L758-L777
| null |
# -*- coding: utf-8 -*-
'''
Connection module for Amazon RDS
.. versionadded:: 2015.8.0
:configuration: This module accepts explicit rds credentials but can also
utilize IAM roles assigned to the instance through Instance Profiles.
Dynamic credentials are then automatically obtained from AWS API and no
further configuration is necessary. More Information available at:
.. code-block:: text
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
If IAM roles are not used you need to specify them either in a pillar or
in the minion's config file:
.. code-block:: yaml
rds.keyid: GKTADJGHEIQSXMKKRBJ08H
rds.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
rds.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
:depends: boto3
'''
# keep lint from choking on _get_conn and _cache_id
#pylint: disable=E0602
# pylint whinging perfectly valid code
#pylint: disable=W0106
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import time
# Import Salt libs
import salt.utils.compat
import salt.utils.odict as odict
import salt.utils.versions
from salt.exceptions import SaltInvocationError
log = logging.getLogger(__name__)
# Import third party libs
from salt.ext import six
# pylint: disable=import-error
try:
#pylint: disable=unused-import
import boto
import boto3
#pylint: enable=unused-import
from botocore.exceptions import ClientError
logging.getLogger('boto').setLevel(logging.CRITICAL)
logging.getLogger('boto3').setLevel(logging.CRITICAL)
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
# pylint: enable=import-error
boto3_param_map = {
'allocated_storage': ('AllocatedStorage', int),
'allow_major_version_upgrade': ('AllowMajorVersionUpgrade', bool),
'apply_immediately': ('ApplyImmediately', bool),
'auto_minor_version_upgrade': ('AutoMinorVersionUpgrade', bool),
'availability_zone': ('AvailabilityZone', str),
'backup_retention_period': ('BackupRetentionPeriod', int),
'ca_certificate_identifier': ('CACertificateIdentifier', str),
'character_set_name': ('CharacterSetName', str),
'copy_tags_to_snapshot': ('CopyTagsToSnapshot', bool),
'db_cluster_identifier': ('DBClusterIdentifier', str),
'db_instance_class': ('DBInstanceClass', str),
'db_name': ('DBName', str),
'db_parameter_group_name': ('DBParameterGroupName', str),
'db_port_number': ('DBPortNumber', int),
'db_security_groups': ('DBSecurityGroups', list),
'db_subnet_group_name': ('DBSubnetGroupName', str),
'domain': ('Domain', str),
'domain_iam_role_name': ('DomainIAMRoleName', str),
'engine': ('Engine', str),
'engine_version': ('EngineVersion', str),
'iops': ('Iops', int),
'kms_key_id': ('KmsKeyId', str),
'license_model': ('LicenseModel', str),
'master_user_password': ('MasterUserPassword', str),
'master_username': ('MasterUsername', str),
'monitoring_interval': ('MonitoringInterval', int),
'monitoring_role_arn': ('MonitoringRoleArn', str),
'multi_az': ('MultiAZ', bool),
'name': ('DBInstanceIdentifier', str),
'new_db_instance_identifier': ('NewDBInstanceIdentifier', str),
'option_group_name': ('OptionGroupName', str),
'port': ('Port', int),
'preferred_backup_window': ('PreferredBackupWindow', str),
'preferred_maintenance_window': ('PreferredMaintenanceWindow', str),
'promotion_tier': ('PromotionTier', int),
'publicly_accessible': ('PubliclyAccessible', bool),
'storage_encrypted': ('StorageEncrypted', bool),
'storage_type': ('StorageType', str),
'tags': ('Tags', list),
'tde_credential_arn': ('TdeCredentialArn', str),
'tde_credential_password': ('TdeCredentialPassword', str),
'vpc_security_group_ids': ('VpcSecurityGroupIds', list),
}
def __virtual__():
'''
Only load if boto libraries exist and if boto libraries are greater than
a given version.
'''
return salt.utils.versions.check_boto_reqs(
boto3_ver='1.3.1'
)
def __init__(opts):
salt.utils.compat.pack_dunder(__name__)
if HAS_BOTO:
__utils__['boto3.assign_funcs'](__name__, 'rds')
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 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 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 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 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_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_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_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_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 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 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_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_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 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 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_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_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 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_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 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 _tag_doc(tags):
taglist = []
if tags is not None:
for k, v in six.iteritems(tags):
if six.text_type(k).startswith('__'):
continue
taglist.append({'Key': six.text_type(k), 'Value': six.text_type(v)})
return taglist
|
saltstack/salt
|
salt/modules/boto_rds.py
|
describe_parameter_group
|
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)}
|
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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_rds.py#L780-L819
| null |
# -*- coding: utf-8 -*-
'''
Connection module for Amazon RDS
.. versionadded:: 2015.8.0
:configuration: This module accepts explicit rds credentials but can also
utilize IAM roles assigned to the instance through Instance Profiles.
Dynamic credentials are then automatically obtained from AWS API and no
further configuration is necessary. More Information available at:
.. code-block:: text
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
If IAM roles are not used you need to specify them either in a pillar or
in the minion's config file:
.. code-block:: yaml
rds.keyid: GKTADJGHEIQSXMKKRBJ08H
rds.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
rds.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
:depends: boto3
'''
# keep lint from choking on _get_conn and _cache_id
#pylint: disable=E0602
# pylint whinging perfectly valid code
#pylint: disable=W0106
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import time
# Import Salt libs
import salt.utils.compat
import salt.utils.odict as odict
import salt.utils.versions
from salt.exceptions import SaltInvocationError
log = logging.getLogger(__name__)
# Import third party libs
from salt.ext import six
# pylint: disable=import-error
try:
#pylint: disable=unused-import
import boto
import boto3
#pylint: enable=unused-import
from botocore.exceptions import ClientError
logging.getLogger('boto').setLevel(logging.CRITICAL)
logging.getLogger('boto3').setLevel(logging.CRITICAL)
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
# pylint: enable=import-error
boto3_param_map = {
'allocated_storage': ('AllocatedStorage', int),
'allow_major_version_upgrade': ('AllowMajorVersionUpgrade', bool),
'apply_immediately': ('ApplyImmediately', bool),
'auto_minor_version_upgrade': ('AutoMinorVersionUpgrade', bool),
'availability_zone': ('AvailabilityZone', str),
'backup_retention_period': ('BackupRetentionPeriod', int),
'ca_certificate_identifier': ('CACertificateIdentifier', str),
'character_set_name': ('CharacterSetName', str),
'copy_tags_to_snapshot': ('CopyTagsToSnapshot', bool),
'db_cluster_identifier': ('DBClusterIdentifier', str),
'db_instance_class': ('DBInstanceClass', str),
'db_name': ('DBName', str),
'db_parameter_group_name': ('DBParameterGroupName', str),
'db_port_number': ('DBPortNumber', int),
'db_security_groups': ('DBSecurityGroups', list),
'db_subnet_group_name': ('DBSubnetGroupName', str),
'domain': ('Domain', str),
'domain_iam_role_name': ('DomainIAMRoleName', str),
'engine': ('Engine', str),
'engine_version': ('EngineVersion', str),
'iops': ('Iops', int),
'kms_key_id': ('KmsKeyId', str),
'license_model': ('LicenseModel', str),
'master_user_password': ('MasterUserPassword', str),
'master_username': ('MasterUsername', str),
'monitoring_interval': ('MonitoringInterval', int),
'monitoring_role_arn': ('MonitoringRoleArn', str),
'multi_az': ('MultiAZ', bool),
'name': ('DBInstanceIdentifier', str),
'new_db_instance_identifier': ('NewDBInstanceIdentifier', str),
'option_group_name': ('OptionGroupName', str),
'port': ('Port', int),
'preferred_backup_window': ('PreferredBackupWindow', str),
'preferred_maintenance_window': ('PreferredMaintenanceWindow', str),
'promotion_tier': ('PromotionTier', int),
'publicly_accessible': ('PubliclyAccessible', bool),
'storage_encrypted': ('StorageEncrypted', bool),
'storage_type': ('StorageType', str),
'tags': ('Tags', list),
'tde_credential_arn': ('TdeCredentialArn', str),
'tde_credential_password': ('TdeCredentialPassword', str),
'vpc_security_group_ids': ('VpcSecurityGroupIds', list),
}
def __virtual__():
'''
Only load if boto libraries exist and if boto libraries are greater than
a given version.
'''
return salt.utils.versions.check_boto_reqs(
boto3_ver='1.3.1'
)
def __init__(opts):
salt.utils.compat.pack_dunder(__name__)
if HAS_BOTO:
__utils__['boto3.assign_funcs'](__name__, 'rds')
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 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 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 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 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_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_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_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_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 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 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_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_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 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 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_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_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_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 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 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 _tag_doc(tags):
taglist = []
if tags is not None:
for k, v in six.iteritems(tags):
if six.text_type(k).startswith('__'):
continue
taglist.append({'Key': six.text_type(k), 'Value': six.text_type(v)})
return taglist
|
saltstack/salt
|
salt/modules/boto_rds.py
|
describe_parameters
|
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)}
|
Returns a list of `DBParameterGroup` parameters.
CLI example to description of parameters ::
salt myminion boto_rds.describe_parameters parametergroupname\
region=us-east-1
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_rds.py#L822-L875
| null |
# -*- coding: utf-8 -*-
'''
Connection module for Amazon RDS
.. versionadded:: 2015.8.0
:configuration: This module accepts explicit rds credentials but can also
utilize IAM roles assigned to the instance through Instance Profiles.
Dynamic credentials are then automatically obtained from AWS API and no
further configuration is necessary. More Information available at:
.. code-block:: text
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
If IAM roles are not used you need to specify them either in a pillar or
in the minion's config file:
.. code-block:: yaml
rds.keyid: GKTADJGHEIQSXMKKRBJ08H
rds.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
rds.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
:depends: boto3
'''
# keep lint from choking on _get_conn and _cache_id
#pylint: disable=E0602
# pylint whinging perfectly valid code
#pylint: disable=W0106
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import time
# Import Salt libs
import salt.utils.compat
import salt.utils.odict as odict
import salt.utils.versions
from salt.exceptions import SaltInvocationError
log = logging.getLogger(__name__)
# Import third party libs
from salt.ext import six
# pylint: disable=import-error
try:
#pylint: disable=unused-import
import boto
import boto3
#pylint: enable=unused-import
from botocore.exceptions import ClientError
logging.getLogger('boto').setLevel(logging.CRITICAL)
logging.getLogger('boto3').setLevel(logging.CRITICAL)
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
# pylint: enable=import-error
boto3_param_map = {
'allocated_storage': ('AllocatedStorage', int),
'allow_major_version_upgrade': ('AllowMajorVersionUpgrade', bool),
'apply_immediately': ('ApplyImmediately', bool),
'auto_minor_version_upgrade': ('AutoMinorVersionUpgrade', bool),
'availability_zone': ('AvailabilityZone', str),
'backup_retention_period': ('BackupRetentionPeriod', int),
'ca_certificate_identifier': ('CACertificateIdentifier', str),
'character_set_name': ('CharacterSetName', str),
'copy_tags_to_snapshot': ('CopyTagsToSnapshot', bool),
'db_cluster_identifier': ('DBClusterIdentifier', str),
'db_instance_class': ('DBInstanceClass', str),
'db_name': ('DBName', str),
'db_parameter_group_name': ('DBParameterGroupName', str),
'db_port_number': ('DBPortNumber', int),
'db_security_groups': ('DBSecurityGroups', list),
'db_subnet_group_name': ('DBSubnetGroupName', str),
'domain': ('Domain', str),
'domain_iam_role_name': ('DomainIAMRoleName', str),
'engine': ('Engine', str),
'engine_version': ('EngineVersion', str),
'iops': ('Iops', int),
'kms_key_id': ('KmsKeyId', str),
'license_model': ('LicenseModel', str),
'master_user_password': ('MasterUserPassword', str),
'master_username': ('MasterUsername', str),
'monitoring_interval': ('MonitoringInterval', int),
'monitoring_role_arn': ('MonitoringRoleArn', str),
'multi_az': ('MultiAZ', bool),
'name': ('DBInstanceIdentifier', str),
'new_db_instance_identifier': ('NewDBInstanceIdentifier', str),
'option_group_name': ('OptionGroupName', str),
'port': ('Port', int),
'preferred_backup_window': ('PreferredBackupWindow', str),
'preferred_maintenance_window': ('PreferredMaintenanceWindow', str),
'promotion_tier': ('PromotionTier', int),
'publicly_accessible': ('PubliclyAccessible', bool),
'storage_encrypted': ('StorageEncrypted', bool),
'storage_type': ('StorageType', str),
'tags': ('Tags', list),
'tde_credential_arn': ('TdeCredentialArn', str),
'tde_credential_password': ('TdeCredentialPassword', str),
'vpc_security_group_ids': ('VpcSecurityGroupIds', list),
}
def __virtual__():
'''
Only load if boto libraries exist and if boto libraries are greater than
a given version.
'''
return salt.utils.versions.check_boto_reqs(
boto3_ver='1.3.1'
)
def __init__(opts):
salt.utils.compat.pack_dunder(__name__)
if HAS_BOTO:
__utils__['boto3.assign_funcs'](__name__, 'rds')
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 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 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 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 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_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_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_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_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 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 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_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_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 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 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_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_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_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 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 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 _tag_doc(tags):
taglist = []
if tags is not None:
for k, v in six.iteritems(tags):
if six.text_type(k).startswith('__'):
continue
taglist.append({'Key': six.text_type(k), 'Value': six.text_type(v)})
return taglist
|
saltstack/salt
|
salt/modules/boto_rds.py
|
modify_db_instance
|
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)}
|
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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_rds.py#L878-L952
| null |
# -*- coding: utf-8 -*-
'''
Connection module for Amazon RDS
.. versionadded:: 2015.8.0
:configuration: This module accepts explicit rds credentials but can also
utilize IAM roles assigned to the instance through Instance Profiles.
Dynamic credentials are then automatically obtained from AWS API and no
further configuration is necessary. More Information available at:
.. code-block:: text
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
If IAM roles are not used you need to specify them either in a pillar or
in the minion's config file:
.. code-block:: yaml
rds.keyid: GKTADJGHEIQSXMKKRBJ08H
rds.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
rds.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
:depends: boto3
'''
# keep lint from choking on _get_conn and _cache_id
#pylint: disable=E0602
# pylint whinging perfectly valid code
#pylint: disable=W0106
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import time
# Import Salt libs
import salt.utils.compat
import salt.utils.odict as odict
import salt.utils.versions
from salt.exceptions import SaltInvocationError
log = logging.getLogger(__name__)
# Import third party libs
from salt.ext import six
# pylint: disable=import-error
try:
#pylint: disable=unused-import
import boto
import boto3
#pylint: enable=unused-import
from botocore.exceptions import ClientError
logging.getLogger('boto').setLevel(logging.CRITICAL)
logging.getLogger('boto3').setLevel(logging.CRITICAL)
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
# pylint: enable=import-error
boto3_param_map = {
'allocated_storage': ('AllocatedStorage', int),
'allow_major_version_upgrade': ('AllowMajorVersionUpgrade', bool),
'apply_immediately': ('ApplyImmediately', bool),
'auto_minor_version_upgrade': ('AutoMinorVersionUpgrade', bool),
'availability_zone': ('AvailabilityZone', str),
'backup_retention_period': ('BackupRetentionPeriod', int),
'ca_certificate_identifier': ('CACertificateIdentifier', str),
'character_set_name': ('CharacterSetName', str),
'copy_tags_to_snapshot': ('CopyTagsToSnapshot', bool),
'db_cluster_identifier': ('DBClusterIdentifier', str),
'db_instance_class': ('DBInstanceClass', str),
'db_name': ('DBName', str),
'db_parameter_group_name': ('DBParameterGroupName', str),
'db_port_number': ('DBPortNumber', int),
'db_security_groups': ('DBSecurityGroups', list),
'db_subnet_group_name': ('DBSubnetGroupName', str),
'domain': ('Domain', str),
'domain_iam_role_name': ('DomainIAMRoleName', str),
'engine': ('Engine', str),
'engine_version': ('EngineVersion', str),
'iops': ('Iops', int),
'kms_key_id': ('KmsKeyId', str),
'license_model': ('LicenseModel', str),
'master_user_password': ('MasterUserPassword', str),
'master_username': ('MasterUsername', str),
'monitoring_interval': ('MonitoringInterval', int),
'monitoring_role_arn': ('MonitoringRoleArn', str),
'multi_az': ('MultiAZ', bool),
'name': ('DBInstanceIdentifier', str),
'new_db_instance_identifier': ('NewDBInstanceIdentifier', str),
'option_group_name': ('OptionGroupName', str),
'port': ('Port', int),
'preferred_backup_window': ('PreferredBackupWindow', str),
'preferred_maintenance_window': ('PreferredMaintenanceWindow', str),
'promotion_tier': ('PromotionTier', int),
'publicly_accessible': ('PubliclyAccessible', bool),
'storage_encrypted': ('StorageEncrypted', bool),
'storage_type': ('StorageType', str),
'tags': ('Tags', list),
'tde_credential_arn': ('TdeCredentialArn', str),
'tde_credential_password': ('TdeCredentialPassword', str),
'vpc_security_group_ids': ('VpcSecurityGroupIds', list),
}
def __virtual__():
'''
Only load if boto libraries exist and if boto libraries are greater than
a given version.
'''
return salt.utils.versions.check_boto_reqs(
boto3_ver='1.3.1'
)
def __init__(opts):
salt.utils.compat.pack_dunder(__name__)
if HAS_BOTO:
__utils__['boto3.assign_funcs'](__name__, 'rds')
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 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 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 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 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_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_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_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_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 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 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_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_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 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 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_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_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_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 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_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 _tag_doc(tags):
taglist = []
if tags is not None:
for k, v in six.iteritems(tags):
if six.text_type(k).startswith('__'):
continue
taglist.append({'Key': six.text_type(k), 'Value': six.text_type(v)})
return taglist
|
saltstack/salt
|
salt/beacons/sensehat.py
|
beacon
|
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
|
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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/beacons/sensehat.py#L47-L109
| null |
# -*- coding: utf-8 -*-
'''
Monitor temperature, humidity and pressure using the SenseHat of a Raspberry Pi
===============================================================================
.. versionadded:: 2017.7.0
:maintainer: Benedikt Werner <1benediktwerner@gmail.com>
:maturity: new
:depends: sense_hat Python module
'''
from __future__ import absolute_import, unicode_literals
import logging
import re
from salt.ext import six
from salt.ext.six.moves import map
log = logging.getLogger(__name__)
def __virtual__():
return 'sensehat.get_pressure' in __salt__
def validate(config):
'''
Validate the beacon configuration
'''
# Configuration for sensehat beacon should be a list
if not isinstance(config, list):
return False, ('Configuration for sensehat beacon '
'must be a list.')
else:
_config = {}
list(map(_config.update, config))
if 'sensors' not in _config:
return False, ('Configuration for sensehat'
' beacon requires sensors.')
return True, 'Valid beacon configuration'
|
saltstack/salt
|
salt/states/nova.py
|
flavor_present
|
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
|
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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/nova.py#L27-L78
| null |
# -*- coding: utf-8 -*-
'''
.. versionadded:: 2017.7
Module for handling OpenStack Nova calls
:codeauthor: Jakub Sliva <jakub.sliva@ultimum.io>
'''
from __future__ import absolute_import
from __future__ import unicode_literals
import logging
from salt.ext import six
log = logging.getLogger(__name__)
def __virtual__():
'''
Only make these states available if nova module is available
'''
if 'nova.flavor_list' in __salt__:
return True
return False, 'nova execution module not imported properly.'
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_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
|
saltstack/salt
|
salt/states/nova.py
|
flavor_access_list
|
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
|
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: []
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/nova.py#L81-L141
| null |
# -*- coding: utf-8 -*-
'''
.. versionadded:: 2017.7
Module for handling OpenStack Nova calls
:codeauthor: Jakub Sliva <jakub.sliva@ultimum.io>
'''
from __future__ import absolute_import
from __future__ import unicode_literals
import logging
from salt.ext import six
log = logging.getLogger(__name__)
def __virtual__():
'''
Only make these states available if nova module is available
'''
if 'nova.flavor_list' in __salt__:
return True
return False, 'nova execution module not imported properly.'
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_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
|
saltstack/salt
|
salt/states/nova.py
|
flavor_absent
|
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
|
Makes flavor to be absent
:param name: flavor name
.. code-block:: yaml
nova-flavor-absent:
nova.flavor_absent:
- name: flavor_name
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/nova.py#L144-L183
| null |
# -*- coding: utf-8 -*-
'''
.. versionadded:: 2017.7
Module for handling OpenStack Nova calls
:codeauthor: Jakub Sliva <jakub.sliva@ultimum.io>
'''
from __future__ import absolute_import
from __future__ import unicode_literals
import logging
from salt.ext import six
log = logging.getLogger(__name__)
def __virtual__():
'''
Only make these states available if nova module is available
'''
if 'nova.flavor_list' in __salt__:
return True
return False, 'nova execution module not imported properly.'
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_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
|
saltstack/salt
|
salt/matchers/nodegroup_match.py
|
match
|
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
|
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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/matchers/nodegroup_match.py#L14-L30
|
[
"def nodegroup_comp(nodegroup, nodegroups, skip=None, first_call=True):\n '''\n Recursively expand ``nodegroup`` from ``nodegroups``; ignore nodegroups in ``skip``\n\n If a top-level (non-recursive) call finds no nodegroups, return the original\n nodegroup definition (for backwards compatibility). Keep track of recursive\n calls via `first_call` argument\n '''\n expanded_nodegroup = False\n if skip is None:\n skip = set()\n elif nodegroup in skip:\n log.error('Failed nodegroup expansion: illegal nested nodegroup \"%s\"', nodegroup)\n return ''\n\n if nodegroup not in nodegroups:\n log.error('Failed nodegroup expansion: unknown nodegroup \"%s\"', nodegroup)\n return ''\n\n nglookup = nodegroups[nodegroup]\n if isinstance(nglookup, six.string_types):\n words = nglookup.split()\n elif isinstance(nglookup, (list, tuple)):\n words = nglookup\n else:\n log.error('Nodegroup \\'%s\\' (%s) is neither a string, list nor tuple',\n nodegroup, nglookup)\n return ''\n\n skip.add(nodegroup)\n ret = []\n opers = ['and', 'or', 'not', '(', ')']\n for word in words:\n if not isinstance(word, six.string_types):\n word = six.text_type(word)\n if word in opers:\n ret.append(word)\n elif len(word) >= 3 and word.startswith('N@'):\n expanded_nodegroup = True\n ret.extend(nodegroup_comp(word[2:], nodegroups, skip=skip, first_call=False))\n else:\n ret.append(word)\n\n if ret:\n ret.insert(0, '(')\n ret.append(')')\n\n skip.remove(nodegroup)\n\n log.debug('nodegroup_comp(%s) => %s', nodegroup, ret)\n # Only return list form if a nodegroup was expanded. Otherwise return\n # the original string to conserve backwards compat\n if expanded_nodegroup or not first_call:\n return ret\n else:\n opers_set = set(opers)\n ret = words\n if (set(ret) - opers_set) == set(ret):\n # No compound operators found in nodegroup definition. Check for\n # group type specifiers\n group_type_re = re.compile('^[A-Z]@')\n regex_chars = ['(', '[', '{', '\\\\', '?', '}', ']', ')']\n if not [x for x in ret if '*' in x or group_type_re.match(x)]:\n # No group type specifiers and no wildcards.\n # Treat this as an expression.\n if [x for x in ret if x in [x for y in regex_chars if y in x]]:\n joined = 'E@' + ','.join(ret)\n log.debug(\n 'Nodegroup \\'%s\\' (%s) detected as an expression. '\n 'Assuming compound matching syntax of \\'%s\\'',\n nodegroup, ret, joined\n )\n else:\n # Treat this as a list of nodenames.\n joined = 'L@' + ','.join(ret)\n log.debug(\n 'Nodegroup \\'%s\\' (%s) detected as list of nodenames. '\n 'Assuming compound matching syntax of \\'%s\\'',\n nodegroup, ret, joined\n )\n # Return data must be a list of compound matching components\n # to be fed into compound matcher. Enclose return data in list.\n return [joined]\n\n log.debug(\n 'No nested nodegroups detected. Using original nodegroup '\n 'definition: %s', nodegroups[nodegroup]\n )\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
This is the default nodegroup matcher.
'''
from __future__ import absolute_import, print_function, unicode_literals
import salt.utils.minions # pylint: disable=3rd-party-module-not-gated
import salt.loader
import logging
log = logging.getLogger(__name__)
|
saltstack/salt
|
salt/states/ldap.py
|
managed
|
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
|
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.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/ldap.py#L26-L368
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n",
"def _process_entries(l, entries):\n '''Helper for managed() to process entries and return before/after views\n\n Collect the current database state and update it according to the\n data in :py:func:`managed`'s ``entries`` parameter. Return the\n current database state and what it will look like after\n modification.\n\n :param l:\n the LDAP connection object\n\n :param entries:\n the same object passed to the ``entries`` parameter of\n :py:func:`manage`\n\n :return:\n an ``(old, new)`` tuple that describes the current state of\n the entries and what they will look like after modification.\n Each item in the tuple is an OrderedDict that maps an entry DN\n to another dict that maps an attribute name to a set of its\n values (it's a set because according to the LDAP spec,\n attribute value ordering is unspecified and there can't be\n duplicates). The structure looks like this:\n\n {dn1: {attr1: set([val1])},\n dn2: {attr1: set([val2]), attr2: set([val3, val4])}}\n\n All of an entry's attributes and values will be included, even\n if they will not be modified. If an entry mentioned in the\n entries variable doesn't yet exist in the database, the DN in\n ``old`` will be mapped to an empty dict. If an entry in the\n database will be deleted, the DN in ``new`` will be mapped to\n an empty dict. All value sets are non-empty: An attribute\n that will be added to an entry is not included in ``old``, and\n an attribute that will be deleted frm an entry is not included\n in ``new``.\n\n These are OrderedDicts to ensure that the user-supplied\n entries are processed in the user-specified order (in case\n there are dependencies, such as ACL rules specified in an\n early entry that make it possible to modify a later entry).\n '''\n\n old = OrderedDict()\n new = OrderedDict()\n\n for entries_dict in entries:\n for dn, directives_seq in six.iteritems(entries_dict):\n # get the old entry's state. first check to see if we've\n # previously processed the entry.\n olde = new.get(dn, None)\n if olde is None:\n # next check the database\n results = __salt__['ldap3.search'](l, dn, 'base')\n if len(results) == 1:\n attrs = results[dn]\n olde = dict(((attr, OrderedSet(attrs[attr]))\n for attr in attrs\n if len(attrs[attr])))\n else:\n # nothing, so it must be a brand new entry\n assert not results\n olde = {}\n old[dn] = olde\n # copy the old entry to create the new (don't do a simple\n # assignment or else modifications to newe will affect\n # olde)\n newe = copy.deepcopy(olde)\n new[dn] = newe\n\n # process the directives\n entry_status = {\n 'delete_others': False,\n 'mentioned_attributes': set(),\n }\n for directives in directives_seq:\n _update_entry(newe, entry_status, directives)\n if entry_status['delete_others']:\n to_delete = set()\n for attr in newe:\n if attr not in entry_status['mentioned_attributes']:\n to_delete.add(attr)\n for attr in to_delete:\n del newe[attr]\n return old, new\n",
"def update(*args, **kwds): # pylint: disable=E0211\n '''od.update(E, **F) -> None. Update od from dict/iterable E and F.\n\n If E is a dict instance, does: for k in E: od[k] = E[k]\n If E has a .keys() method, does: for k in E.keys(): od[k] = E[k]\n Or if E is an iterable of items, does: for k, v in E: od[k] = v\n In either case, this is followed by: for k, v in F.items(): od[k] = v\n\n '''\n if len(args) > 2:\n raise TypeError(\n 'update() takes at most 2 positional '\n 'arguments ({0} given)'.format(len(args))\n )\n elif not args:\n raise TypeError('update() takes at least 1 argument (0 given)')\n self = args[0]\n # Make progressively weaker assumptions about \"other\"\n other = ()\n if len(args) == 2:\n other = args[1]\n if isinstance(other, dict):\n for key in other:\n self[key] = other[key]\n elif hasattr(other, 'keys'):\n for key in other:\n self[key] = other[key]\n else:\n for key, value in other:\n self[key] = value\n for key, value in six.iteritems(kwds):\n self[key] = value\n"
] |
# -*- coding: utf-8 -*-
'''
Manage entries in an LDAP database
==================================
.. versionadded:: 2016.3.0
The ``states.ldap`` state module allows you to manage LDAP entries and
their attributes.
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import inspect
import logging
# Import Salt libs
from salt.ext import six
from salt.utils.odict import OrderedDict
from salt.utils.oset import OrderedSet
log = logging.getLogger(__name__)
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 _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 _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),))
|
saltstack/salt
|
salt/states/ldap.py
|
_process_entries
|
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
|
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).
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/ldap.py#L371-L455
| null |
# -*- coding: utf-8 -*-
'''
Manage entries in an LDAP database
==================================
.. versionadded:: 2016.3.0
The ``states.ldap`` state module allows you to manage LDAP entries and
their attributes.
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import inspect
import logging
# Import Salt libs
from salt.ext import six
from salt.utils.odict import OrderedDict
from salt.utils.oset import OrderedSet
log = logging.getLogger(__name__)
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 _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 _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),))
|
saltstack/salt
|
salt/states/ldap.py
|
_update_entry
|
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)
|
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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/ldap.py#L458-L494
| null |
# -*- coding: utf-8 -*-
'''
Manage entries in an LDAP database
==================================
.. versionadded:: 2016.3.0
The ``states.ldap`` state module allows you to manage LDAP entries and
their attributes.
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import inspect
import logging
# Import Salt libs
from salt.ext import six
from salt.utils.odict import OrderedDict
from salt.utils.oset import OrderedSet
log = logging.getLogger(__name__)
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 _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 _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),))
|
saltstack/salt
|
salt/states/ldap.py
|
_toset
|
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),))
|
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.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/ldap.py#L497-L528
| null |
# -*- coding: utf-8 -*-
'''
Manage entries in an LDAP database
==================================
.. versionadded:: 2016.3.0
The ``states.ldap`` state module allows you to manage LDAP entries and
their attributes.
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import inspect
import logging
# Import Salt libs
from salt.ext import six
from salt.utils.odict import OrderedDict
from salt.utils.oset import OrderedSet
log = logging.getLogger(__name__)
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 _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 _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)
|
saltstack/salt
|
salt/modules/shadow.py
|
info
|
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
|
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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/shadow.py#L53-L95
| null |
# -*- coding: utf-8 -*-
'''
Manage the shadow file on Linux systems
.. important::
If you feel that Salt should be using this module to manage passwords on a
minion, and it is using a different module (or gives an error similar to
*'shadow.info' is not available*), see :ref:`here
<module-provider-override>`.
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
import datetime
import functools
try:
import spwd
except ImportError:
pass
# Import salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.stringutils
from salt.exceptions import CommandExecutionError
from salt.ext import six
from salt.ext.six.moves import range
try:
import salt.utils.pycrypto
HAS_CRYPT = True
except ImportError:
HAS_CRYPT = False
def __virtual__():
return __grains__.get('kernel', '') == 'Linux'
def default_hash():
'''
Returns the default hash used for unset passwords
CLI Example:
.. code-block:: bash
salt '*' shadow.default_hash
'''
return '!'
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_inactdays(name, inactdays, root=None):
'''
Set the number of days of inactivity after a password has expired before
the account is locked. See man chage.
name
User to modify
inactdays
Set password inactive after this number of days
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' shadow.set_inactdays username 7
'''
return _set_attrib(name, 'inact', inactdays, '-I', root=root)
def set_maxdays(name, maxdays, root=None):
'''
Set the maximum number of days during which a password is valid.
See man chage.
name
User to modify
maxdays
Maximum number of days during which a password is valid
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' shadow.set_maxdays username 90
'''
return _set_attrib(name, 'max', maxdays, '-M', root=root)
def set_mindays(name, mindays, root=None):
'''
Set the minimum number of days between password changes. See man chage.
name
User to modify
mindays
Minimum number of days between password changes
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' shadow.set_mindays username 7
'''
return _set_attrib(name, 'min', mindays, '-m', root=root)
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 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 lock_password(name, root=None):
'''
.. versionadded:: 2016.11.0
Lock the password from specified user
name
User to lock
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' shadow.lock_password username
'''
pre_info = info(name, root=root)
if not pre_info['name']:
return False
if pre_info['passwd'].startswith('!'):
return True
cmd = ['passwd']
if root is not None:
cmd.extend(('-R', root))
cmd.extend(('-l', name))
__salt__['cmd.run'](cmd, python_shell=False)
return info(name, root=root)['passwd'].startswith('!')
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 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_warndays(name, warndays, root=None):
'''
Set the number of days of warning before a password change is required.
See man chage.
name
User to modify
warndays
Number of days of warning before a password change is required
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' shadow.set_warndays username 7
'''
return _set_attrib(name, 'warn', warndays, '-W', root=root)
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_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 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 _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 _getspall(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(':')
# Generate a getspall compatible output
for i in range(2, 9):
comps[i] = int(comps[i]) if comps[i] else -1
yield spwd.struct_spwd(comps)
|
saltstack/salt
|
salt/modules/shadow.py
|
_set_attrib
|
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
|
Set a parameter in /etc/shadow
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/shadow.py#L98-L122
|
[
"def info(name, root=None):\n '''\n Return information for the specified user\n\n name\n User to get the information for\n\n root\n Directory to chroot into\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' shadow.info root\n '''\n if root is not None:\n getspnam = functools.partial(_getspnam, root=root)\n else:\n getspnam = functools.partial(spwd.getspnam)\n\n try:\n data = getspnam(name)\n ret = {\n 'name': data.sp_namp if hasattr(data, 'sp_namp') else data.sp_nam,\n 'passwd': data.sp_pwdp if hasattr(data, 'sp_pwdp') else data.sp_pwd,\n 'lstchg': data.sp_lstchg,\n 'min': data.sp_min,\n 'max': data.sp_max,\n 'warn': data.sp_warn,\n 'inact': data.sp_inact,\n 'expire': data.sp_expire}\n except KeyError:\n return {\n 'name': '',\n 'passwd': '',\n 'lstchg': '',\n 'min': '',\n 'max': '',\n 'warn': '',\n 'inact': '',\n 'expire': ''}\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Manage the shadow file on Linux systems
.. important::
If you feel that Salt should be using this module to manage passwords on a
minion, and it is using a different module (or gives an error similar to
*'shadow.info' is not available*), see :ref:`here
<module-provider-override>`.
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
import datetime
import functools
try:
import spwd
except ImportError:
pass
# Import salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.stringutils
from salt.exceptions import CommandExecutionError
from salt.ext import six
from salt.ext.six.moves import range
try:
import salt.utils.pycrypto
HAS_CRYPT = True
except ImportError:
HAS_CRYPT = False
def __virtual__():
return __grains__.get('kernel', '') == 'Linux'
def default_hash():
'''
Returns the default hash used for unset passwords
CLI Example:
.. code-block:: bash
salt '*' shadow.default_hash
'''
return '!'
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 set_inactdays(name, inactdays, root=None):
'''
Set the number of days of inactivity after a password has expired before
the account is locked. See man chage.
name
User to modify
inactdays
Set password inactive after this number of days
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' shadow.set_inactdays username 7
'''
return _set_attrib(name, 'inact', inactdays, '-I', root=root)
def set_maxdays(name, maxdays, root=None):
'''
Set the maximum number of days during which a password is valid.
See man chage.
name
User to modify
maxdays
Maximum number of days during which a password is valid
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' shadow.set_maxdays username 90
'''
return _set_attrib(name, 'max', maxdays, '-M', root=root)
def set_mindays(name, mindays, root=None):
'''
Set the minimum number of days between password changes. See man chage.
name
User to modify
mindays
Minimum number of days between password changes
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' shadow.set_mindays username 7
'''
return _set_attrib(name, 'min', mindays, '-m', root=root)
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 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 lock_password(name, root=None):
'''
.. versionadded:: 2016.11.0
Lock the password from specified user
name
User to lock
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' shadow.lock_password username
'''
pre_info = info(name, root=root)
if not pre_info['name']:
return False
if pre_info['passwd'].startswith('!'):
return True
cmd = ['passwd']
if root is not None:
cmd.extend(('-R', root))
cmd.extend(('-l', name))
__salt__['cmd.run'](cmd, python_shell=False)
return info(name, root=root)['passwd'].startswith('!')
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 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_warndays(name, warndays, root=None):
'''
Set the number of days of warning before a password change is required.
See man chage.
name
User to modify
warndays
Number of days of warning before a password change is required
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' shadow.set_warndays username 7
'''
return _set_attrib(name, 'warn', warndays, '-W', root=root)
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_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 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 _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 _getspall(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(':')
# Generate a getspall compatible output
for i in range(2, 9):
comps[i] = int(comps[i]) if comps[i] else -1
yield spwd.struct_spwd(comps)
|
saltstack/salt
|
salt/modules/shadow.py
|
gen_password
|
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)
|
.. 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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/shadow.py#L193-L232
|
[
"def gen_hash(crypt_salt=None, password=None, algorithm='sha512'):\n '''\n Generate /etc/shadow hash\n '''\n if not HAS_CRYPT:\n raise SaltInvocationError('No crypt module for windows')\n\n hash_algorithms = dict(\n md5='$1$', blowfish='$2a$', sha256='$5$', sha512='$6$'\n )\n if algorithm not in hash_algorithms:\n raise SaltInvocationError(\n 'Algorithm \\'{0}\\' is not supported'.format(algorithm)\n )\n\n if password is None:\n password = secure_password()\n\n if crypt_salt is None:\n crypt_salt = secure_password(8)\n\n crypt_salt = hash_algorithms[algorithm] + crypt_salt\n\n return crypt.crypt(password, crypt_salt)\n"
] |
# -*- coding: utf-8 -*-
'''
Manage the shadow file on Linux systems
.. important::
If you feel that Salt should be using this module to manage passwords on a
minion, and it is using a different module (or gives an error similar to
*'shadow.info' is not available*), see :ref:`here
<module-provider-override>`.
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
import datetime
import functools
try:
import spwd
except ImportError:
pass
# Import salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.stringutils
from salt.exceptions import CommandExecutionError
from salt.ext import six
from salt.ext.six.moves import range
try:
import salt.utils.pycrypto
HAS_CRYPT = True
except ImportError:
HAS_CRYPT = False
def __virtual__():
return __grains__.get('kernel', '') == 'Linux'
def default_hash():
'''
Returns the default hash used for unset passwords
CLI Example:
.. code-block:: bash
salt '*' shadow.default_hash
'''
return '!'
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 _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_inactdays(name, inactdays, root=None):
'''
Set the number of days of inactivity after a password has expired before
the account is locked. See man chage.
name
User to modify
inactdays
Set password inactive after this number of days
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' shadow.set_inactdays username 7
'''
return _set_attrib(name, 'inact', inactdays, '-I', root=root)
def set_maxdays(name, maxdays, root=None):
'''
Set the maximum number of days during which a password is valid.
See man chage.
name
User to modify
maxdays
Maximum number of days during which a password is valid
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' shadow.set_maxdays username 90
'''
return _set_attrib(name, 'max', maxdays, '-M', root=root)
def set_mindays(name, mindays, root=None):
'''
Set the minimum number of days between password changes. See man chage.
name
User to modify
mindays
Minimum number of days between password changes
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' shadow.set_mindays username 7
'''
return _set_attrib(name, 'min', mindays, '-m', root=root)
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 lock_password(name, root=None):
'''
.. versionadded:: 2016.11.0
Lock the password from specified user
name
User to lock
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' shadow.lock_password username
'''
pre_info = info(name, root=root)
if not pre_info['name']:
return False
if pre_info['passwd'].startswith('!'):
return True
cmd = ['passwd']
if root is not None:
cmd.extend(('-R', root))
cmd.extend(('-l', name))
__salt__['cmd.run'](cmd, python_shell=False)
return info(name, root=root)['passwd'].startswith('!')
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 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_warndays(name, warndays, root=None):
'''
Set the number of days of warning before a password change is required.
See man chage.
name
User to modify
warndays
Number of days of warning before a password change is required
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' shadow.set_warndays username 7
'''
return _set_attrib(name, 'warn', warndays, '-W', root=root)
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_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 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 _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 _getspall(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(':')
# Generate a getspall compatible output
for i in range(2, 9):
comps[i] = int(comps[i]) if comps[i] else -1
yield spwd.struct_spwd(comps)
|
saltstack/salt
|
salt/modules/shadow.py
|
del_password
|
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
|
.. 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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/shadow.py#L235-L260
|
[
"def info(name, root=None):\n '''\n Return information for the specified user\n\n name\n User to get the information for\n\n root\n Directory to chroot into\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' shadow.info root\n '''\n if root is not None:\n getspnam = functools.partial(_getspnam, root=root)\n else:\n getspnam = functools.partial(spwd.getspnam)\n\n try:\n data = getspnam(name)\n ret = {\n 'name': data.sp_namp if hasattr(data, 'sp_namp') else data.sp_nam,\n 'passwd': data.sp_pwdp if hasattr(data, 'sp_pwdp') else data.sp_pwd,\n 'lstchg': data.sp_lstchg,\n 'min': data.sp_min,\n 'max': data.sp_max,\n 'warn': data.sp_warn,\n 'inact': data.sp_inact,\n 'expire': data.sp_expire}\n except KeyError:\n return {\n 'name': '',\n 'passwd': '',\n 'lstchg': '',\n 'min': '',\n 'max': '',\n 'warn': '',\n 'inact': '',\n 'expire': ''}\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Manage the shadow file on Linux systems
.. important::
If you feel that Salt should be using this module to manage passwords on a
minion, and it is using a different module (or gives an error similar to
*'shadow.info' is not available*), see :ref:`here
<module-provider-override>`.
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
import datetime
import functools
try:
import spwd
except ImportError:
pass
# Import salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.stringutils
from salt.exceptions import CommandExecutionError
from salt.ext import six
from salt.ext.six.moves import range
try:
import salt.utils.pycrypto
HAS_CRYPT = True
except ImportError:
HAS_CRYPT = False
def __virtual__():
return __grains__.get('kernel', '') == 'Linux'
def default_hash():
'''
Returns the default hash used for unset passwords
CLI Example:
.. code-block:: bash
salt '*' shadow.default_hash
'''
return '!'
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 _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_inactdays(name, inactdays, root=None):
'''
Set the number of days of inactivity after a password has expired before
the account is locked. See man chage.
name
User to modify
inactdays
Set password inactive after this number of days
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' shadow.set_inactdays username 7
'''
return _set_attrib(name, 'inact', inactdays, '-I', root=root)
def set_maxdays(name, maxdays, root=None):
'''
Set the maximum number of days during which a password is valid.
See man chage.
name
User to modify
maxdays
Maximum number of days during which a password is valid
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' shadow.set_maxdays username 90
'''
return _set_attrib(name, 'max', maxdays, '-M', root=root)
def set_mindays(name, mindays, root=None):
'''
Set the minimum number of days between password changes. See man chage.
name
User to modify
mindays
Minimum number of days between password changes
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' shadow.set_mindays username 7
'''
return _set_attrib(name, 'min', mindays, '-m', root=root)
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 lock_password(name, root=None):
'''
.. versionadded:: 2016.11.0
Lock the password from specified user
name
User to lock
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' shadow.lock_password username
'''
pre_info = info(name, root=root)
if not pre_info['name']:
return False
if pre_info['passwd'].startswith('!'):
return True
cmd = ['passwd']
if root is not None:
cmd.extend(('-R', root))
cmd.extend(('-l', name))
__salt__['cmd.run'](cmd, python_shell=False)
return info(name, root=root)['passwd'].startswith('!')
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 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_warndays(name, warndays, root=None):
'''
Set the number of days of warning before a password change is required.
See man chage.
name
User to modify
warndays
Number of days of warning before a password change is required
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' shadow.set_warndays username 7
'''
return _set_attrib(name, 'warn', warndays, '-W', root=root)
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_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 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 _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 _getspall(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(':')
# Generate a getspall compatible output
for i in range(2, 9):
comps[i] = int(comps[i]) if comps[i] else -1
yield spwd.struct_spwd(comps)
|
saltstack/salt
|
salt/modules/shadow.py
|
unlock_password
|
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('!')
|
.. 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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/shadow.py#L299-L332
|
[
"def info(name, root=None):\n '''\n Return information for the specified user\n\n name\n User to get the information for\n\n root\n Directory to chroot into\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' shadow.info root\n '''\n if root is not None:\n getspnam = functools.partial(_getspnam, root=root)\n else:\n getspnam = functools.partial(spwd.getspnam)\n\n try:\n data = getspnam(name)\n ret = {\n 'name': data.sp_namp if hasattr(data, 'sp_namp') else data.sp_nam,\n 'passwd': data.sp_pwdp if hasattr(data, 'sp_pwdp') else data.sp_pwd,\n 'lstchg': data.sp_lstchg,\n 'min': data.sp_min,\n 'max': data.sp_max,\n 'warn': data.sp_warn,\n 'inact': data.sp_inact,\n 'expire': data.sp_expire}\n except KeyError:\n return {\n 'name': '',\n 'passwd': '',\n 'lstchg': '',\n 'min': '',\n 'max': '',\n 'warn': '',\n 'inact': '',\n 'expire': ''}\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Manage the shadow file on Linux systems
.. important::
If you feel that Salt should be using this module to manage passwords on a
minion, and it is using a different module (or gives an error similar to
*'shadow.info' is not available*), see :ref:`here
<module-provider-override>`.
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
import datetime
import functools
try:
import spwd
except ImportError:
pass
# Import salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.stringutils
from salt.exceptions import CommandExecutionError
from salt.ext import six
from salt.ext.six.moves import range
try:
import salt.utils.pycrypto
HAS_CRYPT = True
except ImportError:
HAS_CRYPT = False
def __virtual__():
return __grains__.get('kernel', '') == 'Linux'
def default_hash():
'''
Returns the default hash used for unset passwords
CLI Example:
.. code-block:: bash
salt '*' shadow.default_hash
'''
return '!'
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 _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_inactdays(name, inactdays, root=None):
'''
Set the number of days of inactivity after a password has expired before
the account is locked. See man chage.
name
User to modify
inactdays
Set password inactive after this number of days
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' shadow.set_inactdays username 7
'''
return _set_attrib(name, 'inact', inactdays, '-I', root=root)
def set_maxdays(name, maxdays, root=None):
'''
Set the maximum number of days during which a password is valid.
See man chage.
name
User to modify
maxdays
Maximum number of days during which a password is valid
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' shadow.set_maxdays username 90
'''
return _set_attrib(name, 'max', maxdays, '-M', root=root)
def set_mindays(name, mindays, root=None):
'''
Set the minimum number of days between password changes. See man chage.
name
User to modify
mindays
Minimum number of days between password changes
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' shadow.set_mindays username 7
'''
return _set_attrib(name, 'min', mindays, '-m', root=root)
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 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 lock_password(name, root=None):
'''
.. versionadded:: 2016.11.0
Lock the password from specified user
name
User to lock
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' shadow.lock_password username
'''
pre_info = info(name, root=root)
if not pre_info['name']:
return False
if pre_info['passwd'].startswith('!'):
return True
cmd = ['passwd']
if root is not None:
cmd.extend(('-R', root))
cmd.extend(('-l', name))
__salt__['cmd.run'](cmd, python_shell=False)
return info(name, root=root)['passwd'].startswith('!')
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_warndays(name, warndays, root=None):
'''
Set the number of days of warning before a password change is required.
See man chage.
name
User to modify
warndays
Number of days of warning before a password change is required
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' shadow.set_warndays username 7
'''
return _set_attrib(name, 'warn', warndays, '-W', root=root)
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_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 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 _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 _getspall(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(':')
# Generate a getspall compatible output
for i in range(2, 9):
comps[i] = int(comps[i]) if comps[i] else -1
yield spwd.struct_spwd(comps)
|
saltstack/salt
|
salt/modules/shadow.py
|
set_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
|
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..'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/shadow.py#L335-L408
|
[
"def info(name, root=None):\n '''\n Return information for the specified user\n\n name\n User to get the information for\n\n root\n Directory to chroot into\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' shadow.info root\n '''\n if root is not None:\n getspnam = functools.partial(_getspnam, root=root)\n else:\n getspnam = functools.partial(spwd.getspnam)\n\n try:\n data = getspnam(name)\n ret = {\n 'name': data.sp_namp if hasattr(data, 'sp_namp') else data.sp_nam,\n 'passwd': data.sp_pwdp if hasattr(data, 'sp_pwdp') else data.sp_pwd,\n 'lstchg': data.sp_lstchg,\n 'min': data.sp_min,\n 'max': data.sp_max,\n 'warn': data.sp_warn,\n 'inact': data.sp_inact,\n 'expire': data.sp_expire}\n except KeyError:\n return {\n 'name': '',\n 'passwd': '',\n 'lstchg': '',\n 'min': '',\n 'max': '',\n 'warn': '',\n 'inact': '',\n 'expire': ''}\n return ret\n",
"def is_true(value=None):\n '''\n Returns a boolean value representing the \"truth\" of the value passed. The\n rules for what is a \"True\" value are:\n\n 1. Integer/float values greater than 0\n 2. The string values \"True\" and \"true\"\n 3. Any object for which bool(obj) returns True\n '''\n # First, try int/float conversion\n try:\n value = int(value)\n except (ValueError, TypeError):\n pass\n try:\n value = float(value)\n except (ValueError, TypeError):\n pass\n\n # Now check for truthiness\n if isinstance(value, (six.integer_types, float)):\n return value > 0\n elif isinstance(value, six.string_types):\n return six.text_type(value).lower() == 'true'\n else:\n return bool(value)\n"
] |
# -*- coding: utf-8 -*-
'''
Manage the shadow file on Linux systems
.. important::
If you feel that Salt should be using this module to manage passwords on a
minion, and it is using a different module (or gives an error similar to
*'shadow.info' is not available*), see :ref:`here
<module-provider-override>`.
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
import datetime
import functools
try:
import spwd
except ImportError:
pass
# Import salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.stringutils
from salt.exceptions import CommandExecutionError
from salt.ext import six
from salt.ext.six.moves import range
try:
import salt.utils.pycrypto
HAS_CRYPT = True
except ImportError:
HAS_CRYPT = False
def __virtual__():
return __grains__.get('kernel', '') == 'Linux'
def default_hash():
'''
Returns the default hash used for unset passwords
CLI Example:
.. code-block:: bash
salt '*' shadow.default_hash
'''
return '!'
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 _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_inactdays(name, inactdays, root=None):
'''
Set the number of days of inactivity after a password has expired before
the account is locked. See man chage.
name
User to modify
inactdays
Set password inactive after this number of days
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' shadow.set_inactdays username 7
'''
return _set_attrib(name, 'inact', inactdays, '-I', root=root)
def set_maxdays(name, maxdays, root=None):
'''
Set the maximum number of days during which a password is valid.
See man chage.
name
User to modify
maxdays
Maximum number of days during which a password is valid
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' shadow.set_maxdays username 90
'''
return _set_attrib(name, 'max', maxdays, '-M', root=root)
def set_mindays(name, mindays, root=None):
'''
Set the minimum number of days between password changes. See man chage.
name
User to modify
mindays
Minimum number of days between password changes
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' shadow.set_mindays username 7
'''
return _set_attrib(name, 'min', mindays, '-m', root=root)
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 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 lock_password(name, root=None):
'''
.. versionadded:: 2016.11.0
Lock the password from specified user
name
User to lock
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' shadow.lock_password username
'''
pre_info = info(name, root=root)
if not pre_info['name']:
return False
if pre_info['passwd'].startswith('!'):
return True
cmd = ['passwd']
if root is not None:
cmd.extend(('-R', root))
cmd.extend(('-l', name))
__salt__['cmd.run'](cmd, python_shell=False)
return info(name, root=root)['passwd'].startswith('!')
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 set_warndays(name, warndays, root=None):
'''
Set the number of days of warning before a password change is required.
See man chage.
name
User to modify
warndays
Number of days of warning before a password change is required
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' shadow.set_warndays username 7
'''
return _set_attrib(name, 'warn', warndays, '-W', root=root)
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_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 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 _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 _getspall(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(':')
# Generate a getspall compatible output
for i in range(2, 9):
comps[i] = int(comps[i]) if comps[i] else -1
yield spwd.struct_spwd(comps)
|
saltstack/salt
|
salt/modules/shadow.py
|
set_date
|
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)
|
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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/shadow.py#L434-L454
|
[
"def _set_attrib(name, key, value, param, root=None, validate=True):\n '''\n Set a parameter in /etc/shadow\n '''\n pre_info = info(name, root=root)\n\n # If the user is not present or the attribute is already present,\n # we return early\n if not pre_info['name']:\n return False\n\n if value == pre_info[key]:\n return True\n\n cmd = ['chage']\n\n if root is not None:\n cmd.extend(('-R', root))\n\n cmd.extend((param, value, name))\n\n ret = not __salt__['cmd.run'](cmd, python_shell=False)\n if validate:\n ret = info(name, root=root).get(key) == value\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Manage the shadow file on Linux systems
.. important::
If you feel that Salt should be using this module to manage passwords on a
minion, and it is using a different module (or gives an error similar to
*'shadow.info' is not available*), see :ref:`here
<module-provider-override>`.
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
import datetime
import functools
try:
import spwd
except ImportError:
pass
# Import salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.stringutils
from salt.exceptions import CommandExecutionError
from salt.ext import six
from salt.ext.six.moves import range
try:
import salt.utils.pycrypto
HAS_CRYPT = True
except ImportError:
HAS_CRYPT = False
def __virtual__():
return __grains__.get('kernel', '') == 'Linux'
def default_hash():
'''
Returns the default hash used for unset passwords
CLI Example:
.. code-block:: bash
salt '*' shadow.default_hash
'''
return '!'
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 _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_inactdays(name, inactdays, root=None):
'''
Set the number of days of inactivity after a password has expired before
the account is locked. See man chage.
name
User to modify
inactdays
Set password inactive after this number of days
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' shadow.set_inactdays username 7
'''
return _set_attrib(name, 'inact', inactdays, '-I', root=root)
def set_maxdays(name, maxdays, root=None):
'''
Set the maximum number of days during which a password is valid.
See man chage.
name
User to modify
maxdays
Maximum number of days during which a password is valid
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' shadow.set_maxdays username 90
'''
return _set_attrib(name, 'max', maxdays, '-M', root=root)
def set_mindays(name, mindays, root=None):
'''
Set the minimum number of days between password changes. See man chage.
name
User to modify
mindays
Minimum number of days between password changes
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' shadow.set_mindays username 7
'''
return _set_attrib(name, 'min', mindays, '-m', root=root)
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 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 lock_password(name, root=None):
'''
.. versionadded:: 2016.11.0
Lock the password from specified user
name
User to lock
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' shadow.lock_password username
'''
pre_info = info(name, root=root)
if not pre_info['name']:
return False
if pre_info['passwd'].startswith('!'):
return True
cmd = ['passwd']
if root is not None:
cmd.extend(('-R', root))
cmd.extend(('-l', name))
__salt__['cmd.run'](cmd, python_shell=False)
return info(name, root=root)['passwd'].startswith('!')
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 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_warndays(name, warndays, root=None):
'''
Set the number of days of warning before a password change is required.
See man chage.
name
User to modify
warndays
Number of days of warning before a password change is required
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' shadow.set_warndays username 7
'''
return _set_attrib(name, 'warn', warndays, '-W', root=root)
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 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 _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 _getspall(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(':')
# Generate a getspall compatible output
for i in range(2, 9):
comps[i] = int(comps[i]) if comps[i] else -1
yield spwd.struct_spwd(comps)
|
saltstack/salt
|
salt/modules/shadow.py
|
set_expire
|
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)
|
.. 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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/shadow.py#L457-L480
|
[
"def _set_attrib(name, key, value, param, root=None, validate=True):\n '''\n Set a parameter in /etc/shadow\n '''\n pre_info = info(name, root=root)\n\n # If the user is not present or the attribute is already present,\n # we return early\n if not pre_info['name']:\n return False\n\n if value == pre_info[key]:\n return True\n\n cmd = ['chage']\n\n if root is not None:\n cmd.extend(('-R', root))\n\n cmd.extend((param, value, name))\n\n ret = not __salt__['cmd.run'](cmd, python_shell=False)\n if validate:\n ret = info(name, root=root).get(key) == value\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Manage the shadow file on Linux systems
.. important::
If you feel that Salt should be using this module to manage passwords on a
minion, and it is using a different module (or gives an error similar to
*'shadow.info' is not available*), see :ref:`here
<module-provider-override>`.
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
import datetime
import functools
try:
import spwd
except ImportError:
pass
# Import salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.stringutils
from salt.exceptions import CommandExecutionError
from salt.ext import six
from salt.ext.six.moves import range
try:
import salt.utils.pycrypto
HAS_CRYPT = True
except ImportError:
HAS_CRYPT = False
def __virtual__():
return __grains__.get('kernel', '') == 'Linux'
def default_hash():
'''
Returns the default hash used for unset passwords
CLI Example:
.. code-block:: bash
salt '*' shadow.default_hash
'''
return '!'
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 _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_inactdays(name, inactdays, root=None):
'''
Set the number of days of inactivity after a password has expired before
the account is locked. See man chage.
name
User to modify
inactdays
Set password inactive after this number of days
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' shadow.set_inactdays username 7
'''
return _set_attrib(name, 'inact', inactdays, '-I', root=root)
def set_maxdays(name, maxdays, root=None):
'''
Set the maximum number of days during which a password is valid.
See man chage.
name
User to modify
maxdays
Maximum number of days during which a password is valid
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' shadow.set_maxdays username 90
'''
return _set_attrib(name, 'max', maxdays, '-M', root=root)
def set_mindays(name, mindays, root=None):
'''
Set the minimum number of days between password changes. See man chage.
name
User to modify
mindays
Minimum number of days between password changes
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' shadow.set_mindays username 7
'''
return _set_attrib(name, 'min', mindays, '-m', root=root)
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 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 lock_password(name, root=None):
'''
.. versionadded:: 2016.11.0
Lock the password from specified user
name
User to lock
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' shadow.lock_password username
'''
pre_info = info(name, root=root)
if not pre_info['name']:
return False
if pre_info['passwd'].startswith('!'):
return True
cmd = ['passwd']
if root is not None:
cmd.extend(('-R', root))
cmd.extend(('-l', name))
__salt__['cmd.run'](cmd, python_shell=False)
return info(name, root=root)['passwd'].startswith('!')
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 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_warndays(name, warndays, root=None):
'''
Set the number of days of warning before a password change is required.
See man chage.
name
User to modify
warndays
Number of days of warning before a password change is required
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' shadow.set_warndays username 7
'''
return _set_attrib(name, 'warn', warndays, '-W', root=root)
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 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 _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 _getspall(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(':')
# Generate a getspall compatible output
for i in range(2, 9):
comps[i] = int(comps[i]) if comps[i] else -1
yield spwd.struct_spwd(comps)
|
saltstack/salt
|
salt/modules/shadow.py
|
list_users
|
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()])
|
.. 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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/shadow.py#L483-L504
| null |
# -*- coding: utf-8 -*-
'''
Manage the shadow file on Linux systems
.. important::
If you feel that Salt should be using this module to manage passwords on a
minion, and it is using a different module (or gives an error similar to
*'shadow.info' is not available*), see :ref:`here
<module-provider-override>`.
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
import datetime
import functools
try:
import spwd
except ImportError:
pass
# Import salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.stringutils
from salt.exceptions import CommandExecutionError
from salt.ext import six
from salt.ext.six.moves import range
try:
import salt.utils.pycrypto
HAS_CRYPT = True
except ImportError:
HAS_CRYPT = False
def __virtual__():
return __grains__.get('kernel', '') == 'Linux'
def default_hash():
'''
Returns the default hash used for unset passwords
CLI Example:
.. code-block:: bash
salt '*' shadow.default_hash
'''
return '!'
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 _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_inactdays(name, inactdays, root=None):
'''
Set the number of days of inactivity after a password has expired before
the account is locked. See man chage.
name
User to modify
inactdays
Set password inactive after this number of days
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' shadow.set_inactdays username 7
'''
return _set_attrib(name, 'inact', inactdays, '-I', root=root)
def set_maxdays(name, maxdays, root=None):
'''
Set the maximum number of days during which a password is valid.
See man chage.
name
User to modify
maxdays
Maximum number of days during which a password is valid
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' shadow.set_maxdays username 90
'''
return _set_attrib(name, 'max', maxdays, '-M', root=root)
def set_mindays(name, mindays, root=None):
'''
Set the minimum number of days between password changes. See man chage.
name
User to modify
mindays
Minimum number of days between password changes
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' shadow.set_mindays username 7
'''
return _set_attrib(name, 'min', mindays, '-m', root=root)
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 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 lock_password(name, root=None):
'''
.. versionadded:: 2016.11.0
Lock the password from specified user
name
User to lock
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' shadow.lock_password username
'''
pre_info = info(name, root=root)
if not pre_info['name']:
return False
if pre_info['passwd'].startswith('!'):
return True
cmd = ['passwd']
if root is not None:
cmd.extend(('-R', root))
cmd.extend(('-l', name))
__salt__['cmd.run'](cmd, python_shell=False)
return info(name, root=root)['passwd'].startswith('!')
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 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_warndays(name, warndays, root=None):
'''
Set the number of days of warning before a password change is required.
See man chage.
name
User to modify
warndays
Number of days of warning before a password change is required
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' shadow.set_warndays username 7
'''
return _set_attrib(name, 'warn', warndays, '-W', root=root)
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_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 _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 _getspall(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(':')
# Generate a getspall compatible output
for i in range(2, 9):
comps[i] = int(comps[i]) if comps[i] else -1
yield spwd.struct_spwd(comps)
|
saltstack/salt
|
salt/modules/shadow.py
|
_getspnam
|
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
|
Alternative implementation for getspnam, that use only /etc/shadow
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/shadow.py#L507-L522
| null |
# -*- coding: utf-8 -*-
'''
Manage the shadow file on Linux systems
.. important::
If you feel that Salt should be using this module to manage passwords on a
minion, and it is using a different module (or gives an error similar to
*'shadow.info' is not available*), see :ref:`here
<module-provider-override>`.
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
import datetime
import functools
try:
import spwd
except ImportError:
pass
# Import salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.stringutils
from salt.exceptions import CommandExecutionError
from salt.ext import six
from salt.ext.six.moves import range
try:
import salt.utils.pycrypto
HAS_CRYPT = True
except ImportError:
HAS_CRYPT = False
def __virtual__():
return __grains__.get('kernel', '') == 'Linux'
def default_hash():
'''
Returns the default hash used for unset passwords
CLI Example:
.. code-block:: bash
salt '*' shadow.default_hash
'''
return '!'
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 _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_inactdays(name, inactdays, root=None):
'''
Set the number of days of inactivity after a password has expired before
the account is locked. See man chage.
name
User to modify
inactdays
Set password inactive after this number of days
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' shadow.set_inactdays username 7
'''
return _set_attrib(name, 'inact', inactdays, '-I', root=root)
def set_maxdays(name, maxdays, root=None):
'''
Set the maximum number of days during which a password is valid.
See man chage.
name
User to modify
maxdays
Maximum number of days during which a password is valid
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' shadow.set_maxdays username 90
'''
return _set_attrib(name, 'max', maxdays, '-M', root=root)
def set_mindays(name, mindays, root=None):
'''
Set the minimum number of days between password changes. See man chage.
name
User to modify
mindays
Minimum number of days between password changes
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' shadow.set_mindays username 7
'''
return _set_attrib(name, 'min', mindays, '-m', root=root)
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 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 lock_password(name, root=None):
'''
.. versionadded:: 2016.11.0
Lock the password from specified user
name
User to lock
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' shadow.lock_password username
'''
pre_info = info(name, root=root)
if not pre_info['name']:
return False
if pre_info['passwd'].startswith('!'):
return True
cmd = ['passwd']
if root is not None:
cmd.extend(('-R', root))
cmd.extend(('-l', name))
__salt__['cmd.run'](cmd, python_shell=False)
return info(name, root=root)['passwd'].startswith('!')
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 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_warndays(name, warndays, root=None):
'''
Set the number of days of warning before a password change is required.
See man chage.
name
User to modify
warndays
Number of days of warning before a password change is required
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' shadow.set_warndays username 7
'''
return _set_attrib(name, 'warn', warndays, '-W', root=root)
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_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 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 _getspall(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(':')
# Generate a getspall compatible output
for i in range(2, 9):
comps[i] = int(comps[i]) if comps[i] else -1
yield spwd.struct_spwd(comps)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.