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/grains/core.py
ip_fqdn
python
def ip_fqdn(): ''' Return ip address and FQDN grains ''' if salt.utils.platform.is_proxy(): return {} ret = {} ret['ipv4'] = salt.utils.network.ip_addrs(include_loopback=True) ret['ipv6'] = salt.utils.network.ip_addrs6(include_loopback=True) _fqdn = hostname()['fqdn'] for socket_type, ipv_num in ((socket.AF_INET, '4'), (socket.AF_INET6, '6')): key = 'fqdn_ip' + ipv_num if not ret['ipv' + ipv_num]: ret[key] = [] else: try: start_time = datetime.datetime.utcnow() info = socket.getaddrinfo(_fqdn, None, socket_type) ret[key] = list(set(item[4][0] for item in info)) except socket.error: timediff = datetime.datetime.utcnow() - start_time if timediff.seconds > 5 and __opts__['__role'] == 'master': log.warning( 'Unable to find IPv%s record for "%s" causing a %s ' 'second timeout when rendering grains. Set the dns or ' '/etc/hosts for IPv%s to clear this.', ipv_num, _fqdn, timediff, ipv_num ) ret[key] = [] return ret
Return ip address and FQDN grains
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/grains/core.py#L2194-L2226
[ "def hostname():\n '''\n Return fqdn, hostname, domainname\n '''\n # This is going to need some work\n # Provides:\n # fqdn\n # host\n # localhost\n # domain\n global __FQDN__\n grains = {}\n\n if salt.utils.platform.is_proxy():\n return grains\n\n grains['localhost'] = socket.gethostname()\n if __FQDN__ is None:\n __FQDN__ = salt.utils.network.get_fqhostname()\n\n # On some distros (notably FreeBSD) if there is no hostname set\n # salt.utils.network.get_fqhostname() will return None.\n # In this case we punt and log a message at error level, but force the\n # hostname and domain to be localhost.localdomain\n # Otherwise we would stacktrace below\n if __FQDN__ is None: # still!\n log.error('Having trouble getting a hostname. Does this machine have its hostname and domain set properly?')\n __FQDN__ = 'localhost.localdomain'\n\n grains['fqdn'] = __FQDN__\n (grains['host'], grains['domain']) = grains['fqdn'].partition('.')[::2]\n return grains\n" ]
# -*- coding: utf-8 -*- ''' The static grains, these are the core, or built in grains. When grains are loaded they are not loaded in the same way that modules are loaded, grain functions are detected and executed, the functions MUST return a dict which will be applied to the main grains dict. This module will always be executed first, so that any grains loaded here in the core module can be overwritten just by returning dict keys with the same value as those returned here ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import socket import sys import re import platform import logging import locale import uuid import zlib from errno import EACCES, EPERM import datetime import warnings # pylint: disable=import-error try: import dateutil.tz _DATEUTIL_TZ = True except ImportError: _DATEUTIL_TZ = False __proxyenabled__ = ['*'] __FQDN__ = None # Extend the default list of supported distros. This will be used for the # /etc/DISTRO-release checking that is part of linux_distribution() from platform import _supported_dists _supported_dists += ('arch', 'mageia', 'meego', 'vmware', 'bluewhite64', 'slamd64', 'ovs', 'system', 'mint', 'oracle', 'void') # linux_distribution deprecated in py3.7 try: from platform import linux_distribution as _deprecated_linux_distribution def linux_distribution(**kwargs): with warnings.catch_warnings(): warnings.simplefilter("ignore") return _deprecated_linux_distribution(**kwargs) except ImportError: from distro import linux_distribution # Import salt libs import salt.exceptions import salt.log import salt.utils.args import salt.utils.dns import salt.utils.files import salt.utils.network import salt.utils.path import salt.utils.pkg.rpm import salt.utils.platform import salt.utils.stringutils import salt.utils.versions from salt.ext import six from salt.ext.six.moves import range if salt.utils.platform.is_windows(): import salt.utils.win_osinfo # Solve the Chicken and egg problem where grains need to run before any # of the modules are loaded and are generally available for any usage. import salt.modules.cmdmod import salt.modules.smbios __salt__ = { 'cmd.run': salt.modules.cmdmod._run_quiet, 'cmd.retcode': salt.modules.cmdmod._retcode_quiet, 'cmd.run_all': salt.modules.cmdmod._run_all_quiet, 'smbios.records': salt.modules.smbios.records, 'smbios.get': salt.modules.smbios.get, } log = logging.getLogger(__name__) HAS_WMI = False if salt.utils.platform.is_windows(): # attempt to import the python wmi module # the Windows minion uses WMI for some of its grains try: import wmi # pylint: disable=import-error import salt.utils.winapi import win32api import salt.utils.win_reg HAS_WMI = True except ImportError: log.exception( 'Unable to import Python wmi module, some core grains ' 'will be missing' ) HAS_UNAME = True if not hasattr(os, 'uname'): HAS_UNAME = False _INTERFACES = {} def _windows_cpudata(): ''' Return some CPU information on Windows minions ''' # Provides: # num_cpus # cpu_model grains = {} if 'NUMBER_OF_PROCESSORS' in os.environ: # Cast to int so that the logic isn't broken when used as a # conditional in templating. Also follows _linux_cpudata() try: grains['num_cpus'] = int(os.environ['NUMBER_OF_PROCESSORS']) except ValueError: grains['num_cpus'] = 1 grains['cpu_model'] = salt.utils.win_reg.read_value( hive="HKEY_LOCAL_MACHINE", key="HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", vname="ProcessorNameString").get('vdata') return grains def _linux_cpudata(): ''' Return some CPU information for Linux minions ''' # Provides: # num_cpus # cpu_model # cpu_flags grains = {} cpuinfo = '/proc/cpuinfo' # Parse over the cpuinfo file if os.path.isfile(cpuinfo): with salt.utils.files.fopen(cpuinfo, 'r') as _fp: grains['num_cpus'] = 0 for line in _fp: comps = line.split(':') if not len(comps) > 1: continue key = comps[0].strip() val = comps[1].strip() if key == 'processor': grains['num_cpus'] += 1 elif key == 'model name': grains['cpu_model'] = val elif key == 'flags': grains['cpu_flags'] = val.split() elif key == 'Features': grains['cpu_flags'] = val.split() # ARM support - /proc/cpuinfo # # Processor : ARMv6-compatible processor rev 7 (v6l) # BogoMIPS : 697.95 # Features : swp half thumb fastmult vfp edsp java tls # CPU implementer : 0x41 # CPU architecture: 7 # CPU variant : 0x0 # CPU part : 0xb76 # CPU revision : 7 # # Hardware : BCM2708 # Revision : 0002 # Serial : 00000000 elif key == 'Processor': grains['cpu_model'] = val.split('-')[0] grains['num_cpus'] = 1 if 'num_cpus' not in grains: grains['num_cpus'] = 0 if 'cpu_model' not in grains: grains['cpu_model'] = 'Unknown' if 'cpu_flags' not in grains: grains['cpu_flags'] = [] return grains def _linux_gpu_data(): ''' num_gpus: int gpus: - vendor: nvidia|amd|ati|... model: string ''' if __opts__.get('enable_lspci', True) is False: return {} if __opts__.get('enable_gpu_grains', True) is False: return {} lspci = salt.utils.path.which('lspci') if not lspci: log.debug( 'The `lspci` binary is not available on the system. GPU grains ' 'will not be available.' ) return {} # dominant gpu vendors to search for (MUST be lowercase for matching below) known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed'] gpu_classes = ('vga compatible controller', '3d controller') devs = [] try: lspci_out = __salt__['cmd.run']('{0} -vmm'.format(lspci)) cur_dev = {} error = False # Add a blank element to the lspci_out.splitlines() list, # otherwise the last device is not evaluated as a cur_dev and ignored. lspci_list = lspci_out.splitlines() lspci_list.append('') for line in lspci_list: # check for record-separating empty lines if line == '': if cur_dev.get('Class', '').lower() in gpu_classes: devs.append(cur_dev) cur_dev = {} continue if re.match(r'^\w+:\s+.*', line): key, val = line.split(':', 1) cur_dev[key.strip()] = val.strip() else: error = True log.debug('Unexpected lspci output: \'%s\'', line) if error: log.warning( 'Error loading grains, unexpected linux_gpu_data output, ' 'check that you have a valid shell configured and ' 'permissions to run lspci command' ) except OSError: pass gpus = [] for gpu in devs: vendor_strings = re.split('[^A-Za-z0-9]', gpu['Vendor'].lower()) # default vendor to 'unknown', overwrite if we match a known one vendor = 'unknown' for name in known_vendors: # search for an 'expected' vendor name in the list of strings if name in vendor_strings: vendor = name break gpus.append({'vendor': vendor, 'model': gpu['Device']}) grains = {} grains['num_gpus'] = len(gpus) grains['gpus'] = gpus return grains def _netbsd_gpu_data(): ''' num_gpus: int gpus: - vendor: nvidia|amd|ati|... model: string ''' known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed'] gpus = [] try: pcictl_out = __salt__['cmd.run']('pcictl pci0 list') for line in pcictl_out.splitlines(): for vendor in known_vendors: vendor_match = re.match( r'[0-9:]+ ({0}) (.+) \(VGA .+\)'.format(vendor), line, re.IGNORECASE ) if vendor_match: gpus.append({'vendor': vendor_match.group(1), 'model': vendor_match.group(2)}) except OSError: pass grains = {} grains['num_gpus'] = len(gpus) grains['gpus'] = gpus return grains def _osx_gpudata(): ''' num_gpus: int gpus: - vendor: nvidia|amd|ati|... model: string ''' gpus = [] try: pcictl_out = __salt__['cmd.run']('system_profiler SPDisplaysDataType') for line in pcictl_out.splitlines(): fieldname, _, fieldval = line.partition(': ') if fieldname.strip() == "Chipset Model": vendor, _, model = fieldval.partition(' ') vendor = vendor.lower() gpus.append({'vendor': vendor, 'model': model}) except OSError: pass grains = {} grains['num_gpus'] = len(gpus) grains['gpus'] = gpus return grains def _bsd_cpudata(osdata): ''' Return CPU information for BSD-like systems ''' # Provides: # cpuarch # num_cpus # cpu_model # cpu_flags sysctl = salt.utils.path.which('sysctl') arch = salt.utils.path.which('arch') cmds = {} if sysctl: cmds.update({ 'num_cpus': '{0} -n hw.ncpu'.format(sysctl), 'cpuarch': '{0} -n hw.machine'.format(sysctl), 'cpu_model': '{0} -n hw.model'.format(sysctl), }) if arch and osdata['kernel'] == 'OpenBSD': cmds['cpuarch'] = '{0} -s'.format(arch) if osdata['kernel'] == 'Darwin': cmds['cpu_model'] = '{0} -n machdep.cpu.brand_string'.format(sysctl) cmds['cpu_flags'] = '{0} -n machdep.cpu.features'.format(sysctl) grains = dict([(k, __salt__['cmd.run'](v)) for k, v in six.iteritems(cmds)]) if 'cpu_flags' in grains and isinstance(grains['cpu_flags'], six.string_types): grains['cpu_flags'] = grains['cpu_flags'].split(' ') if osdata['kernel'] == 'NetBSD': grains['cpu_flags'] = [] for line in __salt__['cmd.run']('cpuctl identify 0').splitlines(): cpu_match = re.match(r'cpu[0-9]:\ features[0-9]?\ .+<(.+)>', line) if cpu_match: flag = cpu_match.group(1).split(',') grains['cpu_flags'].extend(flag) if osdata['kernel'] == 'FreeBSD' and os.path.isfile('/var/run/dmesg.boot'): grains['cpu_flags'] = [] # TODO: at least it needs to be tested for BSD other then FreeBSD with salt.utils.files.fopen('/var/run/dmesg.boot', 'r') as _fp: cpu_here = False for line in _fp: if line.startswith('CPU: '): cpu_here = True # starts CPU descr continue if cpu_here: if not line.startswith(' '): break # game over if 'Features' in line: start = line.find('<') end = line.find('>') if start > 0 and end > 0: flag = line[start + 1:end].split(',') grains['cpu_flags'].extend(flag) try: grains['num_cpus'] = int(grains['num_cpus']) except ValueError: grains['num_cpus'] = 1 return grains def _sunos_cpudata(): ''' Return the CPU information for Solaris-like systems ''' # Provides: # cpuarch # num_cpus # cpu_model # cpu_flags grains = {} grains['cpu_flags'] = [] grains['cpuarch'] = __salt__['cmd.run']('isainfo -k') psrinfo = '/usr/sbin/psrinfo 2>/dev/null' grains['num_cpus'] = len(__salt__['cmd.run'](psrinfo, python_shell=True).splitlines()) kstat_info = 'kstat -p cpu_info:*:*:brand' for line in __salt__['cmd.run'](kstat_info).splitlines(): match = re.match(r'(\w+:\d+:\w+\d+:\w+)\s+(.+)', line) if match: grains['cpu_model'] = match.group(2) isainfo = 'isainfo -n -v' for line in __salt__['cmd.run'](isainfo).splitlines(): match = re.match(r'^\s+(.+)', line) if match: cpu_flags = match.group(1).split() grains['cpu_flags'].extend(cpu_flags) return grains def _aix_cpudata(): ''' Return CPU information for AIX systems ''' # Provides: # cpuarch # num_cpus # cpu_model # cpu_flags grains = {} cmd = salt.utils.path.which('prtconf') if cmd: data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep for dest, regstring in (('cpuarch', r'(?im)^\s*Processor\s+Type:\s+(\S+)'), ('cpu_flags', r'(?im)^\s*Processor\s+Version:\s+(\S+)'), ('cpu_model', r'(?im)^\s*Processor\s+Implementation\s+Mode:\s+(.*)'), ('num_cpus', r'(?im)^\s*Number\s+Of\s+Processors:\s+(\S+)')): for regex in [re.compile(r) for r in [regstring]]: res = regex.search(data) if res and len(res.groups()) >= 1: grains[dest] = res.group(1).strip().replace("'", '') else: log.error('The \'prtconf\' binary was not found in $PATH.') return grains def _linux_memdata(): ''' Return the memory information for Linux-like systems ''' grains = {'mem_total': 0, 'swap_total': 0} meminfo = '/proc/meminfo' if os.path.isfile(meminfo): with salt.utils.files.fopen(meminfo, 'r') as ifile: for line in ifile: comps = line.rstrip('\n').split(':') if not len(comps) > 1: continue if comps[0].strip() == 'MemTotal': # Use floor division to force output to be an integer grains['mem_total'] = int(comps[1].split()[0]) // 1024 if comps[0].strip() == 'SwapTotal': # Use floor division to force output to be an integer grains['swap_total'] = int(comps[1].split()[0]) // 1024 return grains def _osx_memdata(): ''' Return the memory information for BSD-like systems ''' grains = {'mem_total': 0, 'swap_total': 0} sysctl = salt.utils.path.which('sysctl') if sysctl: mem = __salt__['cmd.run']('{0} -n hw.memsize'.format(sysctl)) swap_total = __salt__['cmd.run']('{0} -n vm.swapusage'.format(sysctl)).split()[2].replace(',', '.') if swap_total.endswith('K'): _power = 2**10 elif swap_total.endswith('M'): _power = 2**20 elif swap_total.endswith('G'): _power = 2**30 swap_total = float(swap_total[:-1]) * _power grains['mem_total'] = int(mem) // 1024 // 1024 grains['swap_total'] = int(swap_total) // 1024 // 1024 return grains def _bsd_memdata(osdata): ''' Return the memory information for BSD-like systems ''' grains = {'mem_total': 0, 'swap_total': 0} sysctl = salt.utils.path.which('sysctl') if sysctl: mem = __salt__['cmd.run']('{0} -n hw.physmem'.format(sysctl)) if osdata['kernel'] == 'NetBSD' and mem.startswith('-'): mem = __salt__['cmd.run']('{0} -n hw.physmem64'.format(sysctl)) grains['mem_total'] = int(mem) // 1024 // 1024 if osdata['kernel'] in ['OpenBSD', 'NetBSD']: swapctl = salt.utils.path.which('swapctl') swap_data = __salt__['cmd.run']('{0} -sk'.format(swapctl)) if swap_data == 'no swap devices configured': swap_total = 0 else: swap_total = swap_data.split(' ')[1] else: swap_total = __salt__['cmd.run']('{0} -n vm.swap_total'.format(sysctl)) grains['swap_total'] = int(swap_total) // 1024 // 1024 return grains def _sunos_memdata(): ''' Return the memory information for SunOS-like systems ''' grains = {'mem_total': 0, 'swap_total': 0} prtconf = '/usr/sbin/prtconf 2>/dev/null' for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines(): comps = line.split(' ') if comps[0].strip() == 'Memory' and comps[1].strip() == 'size:': grains['mem_total'] = int(comps[2].strip()) swap_cmd = salt.utils.path.which('swap') swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split() try: swap_avail = int(swap_data[-2][:-1]) swap_used = int(swap_data[-4][:-1]) swap_total = (swap_avail + swap_used) // 1024 except ValueError: swap_total = None grains['swap_total'] = swap_total return grains def _aix_memdata(): ''' Return the memory information for AIX systems ''' grains = {'mem_total': 0, 'swap_total': 0} prtconf = salt.utils.path.which('prtconf') if prtconf: for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines(): comps = [x for x in line.strip().split(' ') if x] if len(comps) > 2 and 'Memory' in comps[0] and 'Size' in comps[1]: grains['mem_total'] = int(comps[2]) break else: log.error('The \'prtconf\' binary was not found in $PATH.') swap_cmd = salt.utils.path.which('swap') if swap_cmd: swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split() try: swap_total = (int(swap_data[-2]) + int(swap_data[-6])) * 4 except ValueError: swap_total = None grains['swap_total'] = swap_total else: log.error('The \'swap\' binary was not found in $PATH.') return grains def _windows_memdata(): ''' Return the memory information for Windows systems ''' grains = {'mem_total': 0} # get the Total Physical memory as reported by msinfo32 tot_bytes = win32api.GlobalMemoryStatusEx()['TotalPhys'] # return memory info in gigabytes grains['mem_total'] = int(tot_bytes / (1024 ** 2)) return grains def _memdata(osdata): ''' Gather information about the system memory ''' # Provides: # mem_total # swap_total, for supported systems. grains = {'mem_total': 0} if osdata['kernel'] == 'Linux': grains.update(_linux_memdata()) elif osdata['kernel'] in ('FreeBSD', 'OpenBSD', 'NetBSD'): grains.update(_bsd_memdata(osdata)) elif osdata['kernel'] == 'Darwin': grains.update(_osx_memdata()) elif osdata['kernel'] == 'SunOS': grains.update(_sunos_memdata()) elif osdata['kernel'] == 'AIX': grains.update(_aix_memdata()) elif osdata['kernel'] == 'Windows' and HAS_WMI: grains.update(_windows_memdata()) return grains def _aix_get_machine_id(): ''' Parse the output of lsattr -El sys0 for os_uuid ''' grains = {} cmd = salt.utils.path.which('lsattr') if cmd: data = __salt__['cmd.run']('{0} -El sys0'.format(cmd)) + os.linesep uuid_regexes = [re.compile(r'(?im)^\s*os_uuid\s+(\S+)\s+(.*)')] for regex in uuid_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: grains['machine_id'] = res.group(1).strip() break else: log.error('The \'lsattr\' binary was not found in $PATH.') return grains def _windows_virtual(osdata): ''' Returns what type of virtual hardware is under the hood, kvm or physical ''' # Provides: # virtual # virtual_subtype grains = dict() if osdata['kernel'] != 'Windows': return grains grains['virtual'] = 'physical' # It is possible that the 'manufacturer' and/or 'productname' grains # exist but have a value of None. manufacturer = osdata.get('manufacturer', '') if manufacturer is None: manufacturer = '' productname = osdata.get('productname', '') if productname is None: productname = '' if 'QEMU' in manufacturer: # FIXME: Make this detect between kvm or qemu grains['virtual'] = 'kvm' if 'Bochs' in manufacturer: grains['virtual'] = 'kvm' # Product Name: (oVirt) www.ovirt.org # Red Hat Community virtualization Project based on kvm elif 'oVirt' in productname: grains['virtual'] = 'kvm' grains['virtual_subtype'] = 'oVirt' # Red Hat Enterprise Virtualization elif 'RHEV Hypervisor' in productname: grains['virtual'] = 'kvm' grains['virtual_subtype'] = 'rhev' # Product Name: VirtualBox elif 'VirtualBox' in productname: grains['virtual'] = 'VirtualBox' # Product Name: VMware Virtual Platform elif 'VMware Virtual Platform' in productname: grains['virtual'] = 'VMware' # Manufacturer: Microsoft Corporation # Product Name: Virtual Machine elif 'Microsoft' in manufacturer and \ 'Virtual Machine' in productname: grains['virtual'] = 'VirtualPC' # Manufacturer: Parallels Software International Inc. elif 'Parallels Software' in manufacturer: grains['virtual'] = 'Parallels' # Apache CloudStack elif 'CloudStack KVM Hypervisor' in productname: grains['virtual'] = 'kvm' grains['virtual_subtype'] = 'cloudstack' return grains def _virtual(osdata): ''' Returns what type of virtual hardware is under the hood, kvm or physical ''' # This is going to be a monster, if you are running a vm you can test this # grain with please submit patches! # Provides: # virtual # virtual_subtype grains = {'virtual': 'physical'} # Skip the below loop on platforms which have none of the desired cmds # This is a temporary measure until we can write proper virtual hardware # detection. skip_cmds = ('AIX',) # list of commands to be executed to determine the 'virtual' grain _cmds = ['systemd-detect-virt', 'virt-what', 'dmidecode'] # test first for virt-what, which covers most of the desired functionality # on most platforms if not salt.utils.platform.is_windows() and osdata['kernel'] not in skip_cmds: if salt.utils.path.which('virt-what'): _cmds = ['virt-what'] # Check if enable_lspci is True or False if __opts__.get('enable_lspci', True) is True: # /proc/bus/pci does not exists, lspci will fail if os.path.exists('/proc/bus/pci'): _cmds += ['lspci'] # Add additional last resort commands if osdata['kernel'] in skip_cmds: _cmds = () # Quick backout for BrandZ (Solaris LX Branded zones) # Don't waste time trying other commands to detect the virtual grain if HAS_UNAME and osdata['kernel'] == 'Linux' and 'BrandZ virtual linux' in os.uname(): grains['virtual'] = 'zone' return grains failed_commands = set() for command in _cmds: args = [] if osdata['kernel'] == 'Darwin': command = 'system_profiler' args = ['SPDisplaysDataType'] elif osdata['kernel'] == 'SunOS': virtinfo = salt.utils.path.which('virtinfo') if virtinfo: try: ret = __salt__['cmd.run_all']('{0} -a'.format(virtinfo)) except salt.exceptions.CommandExecutionError: if salt.log.is_logging_configured(): failed_commands.add(virtinfo) else: if ret['stdout'].endswith('not supported'): command = 'prtdiag' else: command = 'virtinfo' else: command = 'prtdiag' cmd = salt.utils.path.which(command) if not cmd: continue cmd = '{0} {1}'.format(cmd, ' '.join(args)) try: ret = __salt__['cmd.run_all'](cmd) if ret['retcode'] > 0: if salt.log.is_logging_configured(): # systemd-detect-virt always returns > 0 on non-virtualized # systems # prtdiag only works in the global zone, skip if it fails if salt.utils.platform.is_windows() or 'systemd-detect-virt' in cmd or 'prtdiag' in cmd: continue failed_commands.add(command) continue except salt.exceptions.CommandExecutionError: if salt.log.is_logging_configured(): if salt.utils.platform.is_windows(): continue failed_commands.add(command) continue output = ret['stdout'] if command == "system_profiler": macoutput = output.lower() if '0x1ab8' in macoutput: grains['virtual'] = 'Parallels' if 'parallels' in macoutput: grains['virtual'] = 'Parallels' if 'vmware' in macoutput: grains['virtual'] = 'VMware' if '0x15ad' in macoutput: grains['virtual'] = 'VMware' if 'virtualbox' in macoutput: grains['virtual'] = 'VirtualBox' # Break out of the loop so the next log message is not issued break elif command == 'systemd-detect-virt': if output in ('qemu', 'kvm', 'oracle', 'xen', 'bochs', 'chroot', 'uml', 'systemd-nspawn'): grains['virtual'] = output break elif 'vmware' in output: grains['virtual'] = 'VMware' break elif 'microsoft' in output: grains['virtual'] = 'VirtualPC' break elif 'lxc' in output: grains['virtual'] = 'LXC' break elif 'systemd-nspawn' in output: grains['virtual'] = 'LXC' break elif command == 'virt-what': try: output = output.splitlines()[-1] except IndexError: pass if output in ('kvm', 'qemu', 'uml', 'xen', 'lxc'): grains['virtual'] = output break elif 'vmware' in output: grains['virtual'] = 'VMware' break elif 'parallels' in output: grains['virtual'] = 'Parallels' break elif 'hyperv' in output: grains['virtual'] = 'HyperV' break elif command == 'dmidecode': # Product Name: VirtualBox if 'Vendor: QEMU' in output: # FIXME: Make this detect between kvm or qemu grains['virtual'] = 'kvm' if 'Manufacturer: QEMU' in output: grains['virtual'] = 'kvm' if 'Vendor: Bochs' in output: grains['virtual'] = 'kvm' if 'Manufacturer: Bochs' in output: grains['virtual'] = 'kvm' if 'BHYVE' in output: grains['virtual'] = 'bhyve' # Product Name: (oVirt) www.ovirt.org # Red Hat Community virtualization Project based on kvm elif 'Manufacturer: oVirt' in output: grains['virtual'] = 'kvm' grains['virtual_subtype'] = 'ovirt' # Red Hat Enterprise Virtualization elif 'Product Name: RHEV Hypervisor' in output: grains['virtual'] = 'kvm' grains['virtual_subtype'] = 'rhev' elif 'VirtualBox' in output: grains['virtual'] = 'VirtualBox' # Product Name: VMware Virtual Platform elif 'VMware' in output: grains['virtual'] = 'VMware' # Manufacturer: Microsoft Corporation # Product Name: Virtual Machine elif ': Microsoft' in output and 'Virtual Machine' in output: grains['virtual'] = 'VirtualPC' # Manufacturer: Parallels Software International Inc. elif 'Parallels Software' in output: grains['virtual'] = 'Parallels' elif 'Manufacturer: Google' in output: grains['virtual'] = 'kvm' # Proxmox KVM elif 'Vendor: SeaBIOS' in output: grains['virtual'] = 'kvm' # Break out of the loop, lspci parsing is not necessary break elif command == 'lspci': # dmidecode not available or the user does not have the necessary # permissions model = output.lower() if 'vmware' in model: grains['virtual'] = 'VMware' # 00:04.0 System peripheral: InnoTek Systemberatung GmbH # VirtualBox Guest Service elif 'virtualbox' in model: grains['virtual'] = 'VirtualBox' elif 'qemu' in model: grains['virtual'] = 'kvm' elif 'virtio' in model: grains['virtual'] = 'kvm' # Break out of the loop so the next log message is not issued break elif command == 'prtdiag': model = output.lower().split("\n")[0] if 'vmware' in model: grains['virtual'] = 'VMware' elif 'virtualbox' in model: grains['virtual'] = 'VirtualBox' elif 'qemu' in model: grains['virtual'] = 'kvm' elif 'joyent smartdc hvm' in model: grains['virtual'] = 'kvm' break elif command == 'virtinfo': grains['virtual'] = 'LDOM' break choices = ('Linux', 'HP-UX') isdir = os.path.isdir sysctl = salt.utils.path.which('sysctl') if osdata['kernel'] in choices: if os.path.isdir('/proc'): try: self_root = os.stat('/') init_root = os.stat('/proc/1/root/.') if self_root != init_root: grains['virtual_subtype'] = 'chroot' except (IOError, OSError): pass if isdir('/proc/vz'): if os.path.isfile('/proc/vz/version'): grains['virtual'] = 'openvzhn' elif os.path.isfile('/proc/vz/veinfo'): grains['virtual'] = 'openvzve' # a posteriori, it's expected for these to have failed: failed_commands.discard('lspci') failed_commands.discard('dmidecode') # Provide additional detection for OpenVZ if os.path.isfile('/proc/self/status'): with salt.utils.files.fopen('/proc/self/status') as status_file: vz_re = re.compile(r'^envID:\s+(\d+)$') for line in status_file: vz_match = vz_re.match(line.rstrip('\n')) if vz_match and int(vz_match.groups()[0]) != 0: grains['virtual'] = 'openvzve' elif vz_match and int(vz_match.groups()[0]) == 0: grains['virtual'] = 'openvzhn' if isdir('/proc/sys/xen') or \ isdir('/sys/bus/xen') or isdir('/proc/xen'): if os.path.isfile('/proc/xen/xsd_kva'): # Tested on CentOS 5.3 / 2.6.18-194.26.1.el5xen # Tested on CentOS 5.4 / 2.6.18-164.15.1.el5xen grains['virtual_subtype'] = 'Xen Dom0' else: if osdata.get('productname', '') == 'HVM domU': # Requires dmidecode! grains['virtual_subtype'] = 'Xen HVM DomU' elif os.path.isfile('/proc/xen/capabilities') and \ os.access('/proc/xen/capabilities', os.R_OK): with salt.utils.files.fopen('/proc/xen/capabilities') as fhr: if 'control_d' not in fhr.read(): # Tested on CentOS 5.5 / 2.6.18-194.3.1.el5xen grains['virtual_subtype'] = 'Xen PV DomU' else: # Shouldn't get to this, but just in case grains['virtual_subtype'] = 'Xen Dom0' # Tested on Fedora 10 / 2.6.27.30-170.2.82 with xen # Tested on Fedora 15 / 2.6.41.4-1 without running xen elif isdir('/sys/bus/xen'): if 'xen:' in __salt__['cmd.run']('dmesg').lower(): grains['virtual_subtype'] = 'Xen PV DomU' elif os.path.isfile('/sys/bus/xen/drivers/xenconsole'): # An actual DomU will have the xenconsole driver grains['virtual_subtype'] = 'Xen PV DomU' # If a Dom0 or DomU was detected, obviously this is xen if 'dom' in grains.get('virtual_subtype', '').lower(): grains['virtual'] = 'xen' # Check container type after hypervisors, to avoid variable overwrite on containers running in virtual environment. if os.path.isfile('/proc/1/cgroup'): try: with salt.utils.files.fopen('/proc/1/cgroup', 'r') as fhr: fhr_contents = fhr.read() if ':/lxc/' in fhr_contents: grains['virtual_subtype'] = 'LXC' elif ':/kubepods/' in fhr_contents: grains['virtual_subtype'] = 'kubernetes' elif ':/libpod_parent/' in fhr_contents: grains['virtual_subtype'] = 'libpod' else: if any(x in fhr_contents for x in (':/system.slice/docker', ':/docker/', ':/docker-ce/')): grains['virtual_subtype'] = 'Docker' except IOError: pass if os.path.isfile('/proc/cpuinfo'): with salt.utils.files.fopen('/proc/cpuinfo', 'r') as fhr: if 'QEMU Virtual CPU' in fhr.read(): grains['virtual'] = 'kvm' if os.path.isfile('/sys/devices/virtual/dmi/id/product_name'): try: with salt.utils.files.fopen('/sys/devices/virtual/dmi/id/product_name', 'r') as fhr: output = salt.utils.stringutils.to_unicode(fhr.read(), errors='replace') if 'VirtualBox' in output: grains['virtual'] = 'VirtualBox' elif 'RHEV Hypervisor' in output: grains['virtual'] = 'kvm' grains['virtual_subtype'] = 'rhev' elif 'oVirt Node' in output: grains['virtual'] = 'kvm' grains['virtual_subtype'] = 'ovirt' elif 'Google' in output: grains['virtual'] = 'gce' elif 'BHYVE' in output: grains['virtual'] = 'bhyve' except IOError: pass elif osdata['kernel'] == 'FreeBSD': kenv = salt.utils.path.which('kenv') if kenv: product = __salt__['cmd.run']( '{0} smbios.system.product'.format(kenv) ) maker = __salt__['cmd.run']( '{0} smbios.system.maker'.format(kenv) ) if product.startswith('VMware'): grains['virtual'] = 'VMware' if product.startswith('VirtualBox'): grains['virtual'] = 'VirtualBox' if maker.startswith('Xen'): grains['virtual_subtype'] = '{0} {1}'.format(maker, product) grains['virtual'] = 'xen' if maker.startswith('Microsoft') and product.startswith('Virtual'): grains['virtual'] = 'VirtualPC' if maker.startswith('OpenStack'): grains['virtual'] = 'OpenStack' if maker.startswith('Bochs'): grains['virtual'] = 'kvm' if sysctl: hv_vendor = __salt__['cmd.run']('{0} hw.hv_vendor'.format(sysctl)) model = __salt__['cmd.run']('{0} hw.model'.format(sysctl)) jail = __salt__['cmd.run']( '{0} -n security.jail.jailed'.format(sysctl) ) if 'bhyve' in hv_vendor: grains['virtual'] = 'bhyve' if jail == '1': grains['virtual_subtype'] = 'jail' if 'QEMU Virtual CPU' in model: grains['virtual'] = 'kvm' elif osdata['kernel'] == 'OpenBSD': if 'manufacturer' in osdata: if osdata['manufacturer'] in ['QEMU', 'Red Hat', 'Joyent']: grains['virtual'] = 'kvm' if osdata['manufacturer'] == 'OpenBSD': grains['virtual'] = 'vmm' elif osdata['kernel'] == 'SunOS': if grains['virtual'] == 'LDOM': roles = [] for role in ('control', 'io', 'root', 'service'): subtype_cmd = '{0} -c current get -H -o value {1}-role'.format(cmd, role) ret = __salt__['cmd.run_all']('{0}'.format(subtype_cmd)) if ret['stdout'] == 'true': roles.append(role) if roles: grains['virtual_subtype'] = roles else: # Check if it's a "regular" zone. (i.e. Solaris 10/11 zone) zonename = salt.utils.path.which('zonename') if zonename: zone = __salt__['cmd.run']('{0}'.format(zonename)) if zone != 'global': grains['virtual'] = 'zone' # Check if it's a branded zone (i.e. Solaris 8/9 zone) if isdir('/.SUNWnative'): grains['virtual'] = 'zone' elif osdata['kernel'] == 'NetBSD': if sysctl: if 'QEMU Virtual CPU' in __salt__['cmd.run']( '{0} -n machdep.cpu_brand'.format(sysctl)): grains['virtual'] = 'kvm' elif 'invalid' not in __salt__['cmd.run']( '{0} -n machdep.xen.suspend'.format(sysctl)): grains['virtual'] = 'Xen PV DomU' elif 'VMware' in __salt__['cmd.run']( '{0} -n machdep.dmi.system-vendor'.format(sysctl)): grains['virtual'] = 'VMware' # NetBSD has Xen dom0 support elif __salt__['cmd.run']( '{0} -n machdep.idle-mechanism'.format(sysctl)) == 'xen': if os.path.isfile('/var/run/xenconsoled.pid'): grains['virtual_subtype'] = 'Xen Dom0' for command in failed_commands: log.info( "Although '%s' was found in path, the current user " 'cannot execute it. Grains output might not be ' 'accurate.', command ) return grains def _virtual_hv(osdata): ''' Returns detailed hypervisor information from sysfs Currently this seems to be used only by Xen ''' grains = {} # Bail early if we're not running on Xen try: if 'xen' not in osdata['virtual']: return grains except KeyError: return grains # Try to get the exact hypervisor version from sysfs try: version = {} for fn in ('major', 'minor', 'extra'): with salt.utils.files.fopen('/sys/hypervisor/version/{}'.format(fn), 'r') as fhr: version[fn] = salt.utils.stringutils.to_unicode(fhr.read().strip()) grains['virtual_hv_version'] = '{}.{}{}'.format(version['major'], version['minor'], version['extra']) grains['virtual_hv_version_info'] = [version['major'], version['minor'], version['extra']] except (IOError, OSError, KeyError): pass # Try to read and decode the supported feature set of the hypervisor # Based on https://github.com/brendangregg/Misc/blob/master/xen/xen-features.py # Table data from include/xen/interface/features.h xen_feature_table = {0: 'writable_page_tables', 1: 'writable_descriptor_tables', 2: 'auto_translated_physmap', 3: 'supervisor_mode_kernel', 4: 'pae_pgdir_above_4gb', 5: 'mmu_pt_update_preserve_ad', 7: 'gnttab_map_avail_bits', 8: 'hvm_callback_vector', 9: 'hvm_safe_pvclock', 10: 'hvm_pirqs', 11: 'dom0', 12: 'grant_map_identity', 13: 'memory_op_vnode_supported', 14: 'ARM_SMCCC_supported'} try: with salt.utils.files.fopen('/sys/hypervisor/properties/features', 'r') as fhr: features = salt.utils.stringutils.to_unicode(fhr.read().strip()) enabled_features = [] for bit, feat in six.iteritems(xen_feature_table): if int(features, 16) & (1 << bit): enabled_features.append(feat) grains['virtual_hv_features'] = features grains['virtual_hv_features_list'] = enabled_features except (IOError, OSError, KeyError): pass return grains def _ps(osdata): ''' Return the ps grain ''' grains = {} bsd_choices = ('FreeBSD', 'NetBSD', 'OpenBSD', 'MacOS') if osdata['os'] in bsd_choices: grains['ps'] = 'ps auxwww' elif osdata['os_family'] == 'Solaris': grains['ps'] = '/usr/ucb/ps auxwww' elif osdata['os'] == 'Windows': grains['ps'] = 'tasklist.exe' elif osdata.get('virtual', '') == 'openvzhn': grains['ps'] = ( 'ps -fH -p $(grep -l \"^envID:[[:space:]]*0\\$\" ' '/proc/[0-9]*/status | sed -e \"s=/proc/\\([0-9]*\\)/.*=\\1=\") ' '| awk \'{ $7=\"\"; print }\'' ) elif osdata['os_family'] == 'AIX': grains['ps'] = '/usr/bin/ps auxww' elif osdata['os_family'] == 'NILinuxRT': grains['ps'] = 'ps -o user,pid,ppid,tty,time,comm' else: grains['ps'] = 'ps -efHww' return grains def _clean_value(key, val): ''' Clean out well-known bogus values. If it isn't clean (for example has value 'None'), return None. Otherwise, return the original value. NOTE: This logic also exists in the smbios module. This function is for use when not using smbios to retrieve the value. ''' if (val is None or not val or re.match('none', val, flags=re.IGNORECASE)): return None elif 'uuid' in key: # Try each version (1-5) of RFC4122 to check if it's actually a UUID for uuidver in range(1, 5): try: uuid.UUID(val, version=uuidver) return val except ValueError: continue log.trace('HW %s value %s is an invalid UUID', key, val.replace('\n', ' ')) return None elif re.search('serial|part|version', key): # 'To be filled by O.E.M. # 'Not applicable' etc. # 'Not specified' etc. # 0000000, 1234567 etc. # begone! if (re.match(r'^[0]+$', val) or re.match(r'[0]?1234567[8]?[9]?[0]?', val) or re.search(r'sernum|part[_-]?number|specified|filled|applicable', val, flags=re.IGNORECASE)): return None elif re.search('asset|manufacturer', key): # AssetTag0. Manufacturer04. Begone. if re.search(r'manufacturer|to be filled|available|asset|^no(ne|t)', val, flags=re.IGNORECASE): return None else: # map unspecified, undefined, unknown & whatever to None if (re.search(r'to be filled', val, flags=re.IGNORECASE) or re.search(r'un(known|specified)|no(t|ne)? (asset|provided|defined|available|present|specified)', val, flags=re.IGNORECASE)): return None return val def _windows_platform_data(): ''' Use the platform module for as much as we can. ''' # Provides: # kernelrelease # kernelversion # osversion # osrelease # osservicepack # osmanufacturer # manufacturer # productname # biosversion # serialnumber # osfullname # timezone # windowsdomain # windowsdomaintype # motherboard.productname # motherboard.serialnumber # virtual if not HAS_WMI: return {} with salt.utils.winapi.Com(): wmi_c = wmi.WMI() # http://msdn.microsoft.com/en-us/library/windows/desktop/aa394102%28v=vs.85%29.aspx systeminfo = wmi_c.Win32_ComputerSystem()[0] # https://msdn.microsoft.com/en-us/library/aa394239(v=vs.85).aspx osinfo = wmi_c.Win32_OperatingSystem()[0] # http://msdn.microsoft.com/en-us/library/windows/desktop/aa394077(v=vs.85).aspx biosinfo = wmi_c.Win32_BIOS()[0] # http://msdn.microsoft.com/en-us/library/windows/desktop/aa394498(v=vs.85).aspx timeinfo = wmi_c.Win32_TimeZone()[0] # http://msdn.microsoft.com/en-us/library/windows/desktop/aa394072(v=vs.85).aspx motherboard = {'product': None, 'serial': None} try: motherboardinfo = wmi_c.Win32_BaseBoard()[0] motherboard['product'] = motherboardinfo.Product motherboard['serial'] = motherboardinfo.SerialNumber except IndexError: log.debug('Motherboard info not available on this system') os_release = platform.release() kernel_version = platform.version() info = salt.utils.win_osinfo.get_os_version_info() net_info = salt.utils.win_osinfo.get_join_info() service_pack = None if info['ServicePackMajor'] > 0: service_pack = ''.join(['SP', six.text_type(info['ServicePackMajor'])]) # This creates the osrelease grain based on the Windows Operating # System Product Name. As long as Microsoft maintains a similar format # this should be future proof version = 'Unknown' release = '' if 'Server' in osinfo.Caption: for item in osinfo.Caption.split(' '): # If it's all digits, then it's version if re.match(r'\d+', item): version = item # If it starts with R and then numbers, it's the release # ie: R2 if re.match(r'^R\d+$', item): release = item os_release = '{0}Server{1}'.format(version, release) else: for item in osinfo.Caption.split(' '): # If it's a number, decimal number, Thin or Vista, then it's the # version if re.match(r'^(\d+(\.\d+)?)|Thin|Vista$', item): version = item os_release = version grains = { 'kernelrelease': _clean_value('kernelrelease', osinfo.Version), 'kernelversion': _clean_value('kernelversion', kernel_version), 'osversion': _clean_value('osversion', osinfo.Version), 'osrelease': _clean_value('osrelease', os_release), 'osservicepack': _clean_value('osservicepack', service_pack), 'osmanufacturer': _clean_value('osmanufacturer', osinfo.Manufacturer), 'manufacturer': _clean_value('manufacturer', systeminfo.Manufacturer), 'productname': _clean_value('productname', systeminfo.Model), # bios name had a bunch of whitespace appended to it in my testing # 'PhoenixBIOS 4.0 Release 6.0 ' 'biosversion': _clean_value('biosversion', biosinfo.Name.strip()), 'serialnumber': _clean_value('serialnumber', biosinfo.SerialNumber), 'osfullname': _clean_value('osfullname', osinfo.Caption), 'timezone': _clean_value('timezone', timeinfo.Description), 'windowsdomain': _clean_value('windowsdomain', net_info['Domain']), 'windowsdomaintype': _clean_value('windowsdomaintype', net_info['DomainType']), 'motherboard': { 'productname': _clean_value('motherboard.productname', motherboard['product']), 'serialnumber': _clean_value('motherboard.serialnumber', motherboard['serial']), } } # test for virtualized environments # I only had VMware available so the rest are unvalidated if 'VRTUAL' in biosinfo.Version: # (not a typo) grains['virtual'] = 'HyperV' elif 'A M I' in biosinfo.Version: grains['virtual'] = 'VirtualPC' elif 'VMware' in systeminfo.Model: grains['virtual'] = 'VMware' elif 'VirtualBox' in systeminfo.Model: grains['virtual'] = 'VirtualBox' elif 'Xen' in biosinfo.Version: grains['virtual'] = 'Xen' if 'HVM domU' in systeminfo.Model: grains['virtual_subtype'] = 'HVM domU' elif 'OpenStack' in systeminfo.Model: grains['virtual'] = 'OpenStack' return grains def _osx_platform_data(): ''' Additional data for macOS systems Returns: A dictionary containing values for the following: - model_name - boot_rom_version - smc_version - system_serialnumber ''' cmd = 'system_profiler SPHardwareDataType' hardware = __salt__['cmd.run'](cmd) grains = {} for line in hardware.splitlines(): field_name, _, field_val = line.partition(': ') if field_name.strip() == "Model Name": key = 'model_name' grains[key] = _clean_value(key, field_val) if field_name.strip() == "Boot ROM Version": key = 'boot_rom_version' grains[key] = _clean_value(key, field_val) if field_name.strip() == "SMC Version (system)": key = 'smc_version' grains[key] = _clean_value(key, field_val) if field_name.strip() == "Serial Number (system)": key = 'system_serialnumber' grains[key] = _clean_value(key, field_val) return grains def id_(): ''' Return the id ''' return {'id': __opts__.get('id', '')} _REPLACE_LINUX_RE = re.compile(r'\W(?:gnu/)?linux', re.IGNORECASE) # This maps (at most) the first ten characters (no spaces, lowercased) of # 'osfullname' to the 'os' grain that Salt traditionally uses. # Please see os_data() and _supported_dists. # If your system is not detecting properly it likely needs an entry here. _OS_NAME_MAP = { 'redhatente': 'RedHat', 'gentoobase': 'Gentoo', 'archarm': 'Arch ARM', 'arch': 'Arch', 'debian': 'Debian', 'raspbian': 'Raspbian', 'fedoraremi': 'Fedora', 'chapeau': 'Chapeau', 'korora': 'Korora', 'amazonami': 'Amazon', 'alt': 'ALT', 'enterprise': 'OEL', 'oracleserv': 'OEL', 'cloudserve': 'CloudLinux', 'cloudlinux': 'CloudLinux', 'pidora': 'Fedora', 'scientific': 'ScientificLinux', 'synology': 'Synology', 'nilrt': 'NILinuxRT', 'poky': 'Poky', 'manjaro': 'Manjaro', 'manjarolin': 'Manjaro', 'univention': 'Univention', 'antergos': 'Antergos', 'sles': 'SUSE', 'void': 'Void', 'slesexpand': 'RES', 'linuxmint': 'Mint', 'neon': 'KDE neon', } # Map the 'os' grain to the 'os_family' grain # These should always be capitalized entries as the lookup comes # post-_OS_NAME_MAP. If your system is having trouble with detection, please # make sure that the 'os' grain is capitalized and working correctly first. _OS_FAMILY_MAP = { 'Ubuntu': 'Debian', 'Fedora': 'RedHat', 'Chapeau': 'RedHat', 'Korora': 'RedHat', 'FedBerry': 'RedHat', 'CentOS': 'RedHat', 'GoOSe': 'RedHat', 'Scientific': 'RedHat', 'Amazon': 'RedHat', 'CloudLinux': 'RedHat', 'OVS': 'RedHat', 'OEL': 'RedHat', 'XCP': 'RedHat', 'XCP-ng': 'RedHat', 'XenServer': 'RedHat', 'RES': 'RedHat', 'Sangoma': 'RedHat', 'Mandrake': 'Mandriva', 'ESXi': 'VMware', 'Mint': 'Debian', 'VMwareESX': 'VMware', 'Bluewhite64': 'Bluewhite', 'Slamd64': 'Slackware', 'SLES': 'Suse', 'SUSE Enterprise Server': 'Suse', 'SUSE Enterprise Server': 'Suse', 'SLED': 'Suse', 'openSUSE': 'Suse', 'SUSE': 'Suse', 'openSUSE Leap': 'Suse', 'openSUSE Tumbleweed': 'Suse', 'SLES_SAP': 'Suse', 'Solaris': 'Solaris', 'SmartOS': 'Solaris', 'OmniOS': 'Solaris', 'OpenIndiana Development': 'Solaris', 'OpenIndiana': 'Solaris', 'OpenSolaris Development': 'Solaris', 'OpenSolaris': 'Solaris', 'Oracle Solaris': 'Solaris', 'Arch ARM': 'Arch', 'Manjaro': 'Arch', 'Antergos': 'Arch', 'ALT': 'RedHat', 'Trisquel': 'Debian', 'GCEL': 'Debian', 'Linaro': 'Debian', 'elementary OS': 'Debian', 'elementary': 'Debian', 'Univention': 'Debian', 'ScientificLinux': 'RedHat', 'Raspbian': 'Debian', 'Devuan': 'Debian', 'antiX': 'Debian', 'Kali': 'Debian', 'neon': 'Debian', 'Cumulus': 'Debian', 'Deepin': 'Debian', 'NILinuxRT': 'NILinuxRT', 'KDE neon': 'Debian', 'Void': 'Void', 'IDMS': 'Debian', 'Funtoo': 'Gentoo', 'AIX': 'AIX', 'TurnKey': 'Debian', } # Matches any possible format: # DISTRIB_ID="Ubuntu" # DISTRIB_ID='Mageia' # DISTRIB_ID=Fedora # DISTRIB_RELEASE='10.10' # DISTRIB_CODENAME='squeeze' # DISTRIB_DESCRIPTION='Ubuntu 10.10' _LSB_REGEX = re.compile(( '^(DISTRIB_(?:ID|RELEASE|CODENAME|DESCRIPTION))=(?:\'|")?' '([\\w\\s\\.\\-_]+)(?:\'|")?' )) def _linux_bin_exists(binary): ''' Does a binary exist in linux (depends on which, type, or whereis) ''' for search_cmd in ('which', 'type -ap'): try: return __salt__['cmd.retcode']( '{0} {1}'.format(search_cmd, binary) ) == 0 except salt.exceptions.CommandExecutionError: pass try: return len(__salt__['cmd.run_all']( 'whereis -b {0}'.format(binary) )['stdout'].split()) > 1 except salt.exceptions.CommandExecutionError: return False def _get_interfaces(): ''' Provide a dict of the connected interfaces and their ip addresses ''' global _INTERFACES if not _INTERFACES: _INTERFACES = salt.utils.network.interfaces() return _INTERFACES def _parse_lsb_release(): ret = {} try: log.trace('Attempting to parse /etc/lsb-release') with salt.utils.files.fopen('/etc/lsb-release') as ifile: for line in ifile: try: key, value = _LSB_REGEX.match(line.rstrip('\n')).groups()[:2] except AttributeError: pass else: # Adds lsb_distrib_{id,release,codename,description} ret['lsb_{0}'.format(key.lower())] = value.rstrip() except (IOError, OSError) as exc: log.trace('Failed to parse /etc/lsb-release: %s', exc) return ret def _parse_os_release(*os_release_files): ''' Parse os-release and return a parameter dictionary See http://www.freedesktop.org/software/systemd/man/os-release.html for specification of the file format. ''' ret = {} for filename in os_release_files: try: with salt.utils.files.fopen(filename) as ifile: regex = re.compile('^([\\w]+)=(?:\'|")?(.*?)(?:\'|")?$') for line in ifile: match = regex.match(line.strip()) if match: # Shell special characters ("$", quotes, backslash, # backtick) are escaped with backslashes ret[match.group(1)] = re.sub( r'\\([$"\'\\`])', r'\1', match.group(2) ) break except (IOError, OSError): pass return ret def _parse_cpe_name(cpe): ''' Parse CPE_NAME data from the os-release Info: https://csrc.nist.gov/projects/security-content-automation-protocol/scap-specifications/cpe :param cpe: :return: ''' part = { 'o': 'operating system', 'h': 'hardware', 'a': 'application', } ret = {} cpe = (cpe or '').split(':') if len(cpe) > 4 and cpe[0] == 'cpe': if cpe[1].startswith('/'): # WFN to URI ret['vendor'], ret['product'], ret['version'] = cpe[2:5] ret['phase'] = cpe[5] if len(cpe) > 5 else None ret['part'] = part.get(cpe[1][1:]) elif len(cpe) == 13 and cpe[1] == '2.3': # WFN to a string ret['vendor'], ret['product'], ret['version'], ret['phase'] = [x if x != '*' else None for x in cpe[3:7]] ret['part'] = part.get(cpe[2]) return ret def os_data(): ''' Return grains pertaining to the operating system ''' grains = { 'num_gpus': 0, 'gpus': [], } # Windows Server 2008 64-bit # ('Windows', 'MINIONNAME', '2008ServerR2', '6.1.7601', 'AMD64', # 'Intel64 Fam ily 6 Model 23 Stepping 6, GenuineIntel') # Ubuntu 10.04 # ('Linux', 'MINIONNAME', '2.6.32-38-server', # '#83-Ubuntu SMP Wed Jan 4 11:26:59 UTC 2012', 'x86_64', '') # pylint: disable=unpacking-non-sequence (grains['kernel'], grains['nodename'], grains['kernelrelease'], grains['kernelversion'], grains['cpuarch'], _) = platform.uname() # pylint: enable=unpacking-non-sequence if salt.utils.platform.is_proxy(): grains['kernel'] = 'proxy' grains['kernelrelease'] = 'proxy' grains['kernelversion'] = 'proxy' grains['osrelease'] = 'proxy' grains['os'] = 'proxy' grains['os_family'] = 'proxy' grains['osfullname'] = 'proxy' elif salt.utils.platform.is_windows(): grains['os'] = 'Windows' grains['os_family'] = 'Windows' grains.update(_memdata(grains)) grains.update(_windows_platform_data()) grains.update(_windows_cpudata()) grains.update(_windows_virtual(grains)) grains.update(_ps(grains)) if 'Server' in grains['osrelease']: osrelease_info = grains['osrelease'].split('Server', 1) osrelease_info[1] = osrelease_info[1].lstrip('R') else: osrelease_info = grains['osrelease'].split('.') for idx, value in enumerate(osrelease_info): if not value.isdigit(): continue osrelease_info[idx] = int(value) grains['osrelease_info'] = tuple(osrelease_info) grains['osfinger'] = '{os}-{ver}'.format( os=grains['os'], ver=grains['osrelease']) grains['init'] = 'Windows' return grains elif salt.utils.platform.is_linux(): # Add SELinux grain, if you have it if _linux_bin_exists('selinuxenabled'): log.trace('Adding selinux grains') grains['selinux'] = {} grains['selinux']['enabled'] = __salt__['cmd.retcode']( 'selinuxenabled' ) == 0 if _linux_bin_exists('getenforce'): grains['selinux']['enforced'] = __salt__['cmd.run']( 'getenforce' ).strip() # Add systemd grain, if you have it if _linux_bin_exists('systemctl') and _linux_bin_exists('localectl'): log.trace('Adding systemd grains') grains['systemd'] = {} systemd_info = __salt__['cmd.run']( 'systemctl --version' ).splitlines() grains['systemd']['version'] = systemd_info[0].split()[1] grains['systemd']['features'] = systemd_info[1] # Add init grain grains['init'] = 'unknown' log.trace('Adding init grain') try: os.stat('/run/systemd/system') grains['init'] = 'systemd' except (OSError, IOError): try: with salt.utils.files.fopen('/proc/1/cmdline') as fhr: init_cmdline = fhr.read().replace('\x00', ' ').split() except (IOError, OSError): pass else: try: init_bin = salt.utils.path.which(init_cmdline[0]) except IndexError: # Emtpy init_cmdline init_bin = None log.warning('Unable to fetch data from /proc/1/cmdline') if init_bin is not None and init_bin.endswith('bin/init'): supported_inits = (b'upstart', b'sysvinit', b'systemd') edge_len = max(len(x) for x in supported_inits) - 1 try: buf_size = __opts__['file_buffer_size'] except KeyError: # Default to the value of file_buffer_size for the minion buf_size = 262144 try: with salt.utils.files.fopen(init_bin, 'rb') as fp_: edge = b'' buf = fp_.read(buf_size).lower() while buf: buf = edge + buf for item in supported_inits: if item in buf: if six.PY3: item = item.decode('utf-8') grains['init'] = item buf = b'' break edge = buf[-edge_len:] buf = fp_.read(buf_size).lower() except (IOError, OSError) as exc: log.error( 'Unable to read from init_bin (%s): %s', init_bin, exc ) elif salt.utils.path.which('supervisord') in init_cmdline: grains['init'] = 'supervisord' elif salt.utils.path.which('dumb-init') in init_cmdline: # https://github.com/Yelp/dumb-init grains['init'] = 'dumb-init' elif salt.utils.path.which('tini') in init_cmdline: # https://github.com/krallin/tini grains['init'] = 'tini' elif init_cmdline == ['runit']: grains['init'] = 'runit' elif '/sbin/my_init' in init_cmdline: # Phusion Base docker container use runit for srv mgmt, but # my_init as pid1 grains['init'] = 'runit' else: log.debug( 'Could not determine init system from command line: (%s)', ' '.join(init_cmdline) ) # Add lsb grains on any distro with lsb-release. Note that this import # can fail on systems with lsb-release installed if the system package # does not install the python package for the python interpreter used by # Salt (i.e. python2 or python3) try: log.trace('Getting lsb_release distro information') import lsb_release # pylint: disable=import-error release = lsb_release.get_distro_information() for key, value in six.iteritems(release): key = key.lower() lsb_param = 'lsb_{0}{1}'.format( '' if key.startswith('distrib_') else 'distrib_', key ) grains[lsb_param] = value # Catch a NameError to workaround possible breakage in lsb_release # See https://github.com/saltstack/salt/issues/37867 except (ImportError, NameError): # if the python library isn't available, try to parse # /etc/lsb-release using regex log.trace('lsb_release python bindings not available') grains.update(_parse_lsb_release()) if grains.get('lsb_distrib_description', '').lower().startswith('antergos'): # Antergos incorrectly configures their /etc/lsb-release, # setting the DISTRIB_ID to "Arch". This causes the "os" grain # to be incorrectly set to "Arch". grains['osfullname'] = 'Antergos Linux' elif 'lsb_distrib_id' not in grains: log.trace( 'Failed to get lsb_distrib_id, trying to parse os-release' ) os_release = _parse_os_release('/etc/os-release', '/usr/lib/os-release') if os_release: if 'NAME' in os_release: grains['lsb_distrib_id'] = os_release['NAME'].strip() if 'VERSION_ID' in os_release: grains['lsb_distrib_release'] = os_release['VERSION_ID'] if 'VERSION_CODENAME' in os_release: grains['lsb_distrib_codename'] = os_release['VERSION_CODENAME'] elif 'PRETTY_NAME' in os_release: codename = os_release['PRETTY_NAME'] # https://github.com/saltstack/salt/issues/44108 if os_release['ID'] == 'debian': codename_match = re.search(r'\((\w+)\)$', codename) if codename_match: codename = codename_match.group(1) grains['lsb_distrib_codename'] = codename if 'CPE_NAME' in os_release: cpe = _parse_cpe_name(os_release['CPE_NAME']) if not cpe: log.error('Broken CPE_NAME format in /etc/os-release!') elif cpe.get('vendor', '').lower() in ['suse', 'opensuse']: grains['os'] = "SUSE" # openSUSE `osfullname` grain normalization if os_release.get("NAME") == "openSUSE Leap": grains['osfullname'] = "Leap" elif os_release.get("VERSION") == "Tumbleweed": grains['osfullname'] = os_release["VERSION"] # Override VERSION_ID, if CPE_NAME around if cpe.get('version') and cpe.get('vendor') == 'opensuse': # Keep VERSION_ID for SLES grains['lsb_distrib_release'] = cpe['version'] elif os.path.isfile('/etc/SuSE-release'): log.trace('Parsing distrib info from /etc/SuSE-release') grains['lsb_distrib_id'] = 'SUSE' version = '' patch = '' with salt.utils.files.fopen('/etc/SuSE-release') as fhr: for line in fhr: if 'enterprise' in line.lower(): grains['lsb_distrib_id'] = 'SLES' grains['lsb_distrib_codename'] = re.sub(r'\(.+\)', '', line).strip() elif 'version' in line.lower(): version = re.sub(r'[^0-9]', '', line) elif 'patchlevel' in line.lower(): patch = re.sub(r'[^0-9]', '', line) grains['lsb_distrib_release'] = version if patch: grains['lsb_distrib_release'] += '.' + patch patchstr = 'SP' + patch if grains['lsb_distrib_codename'] and patchstr not in grains['lsb_distrib_codename']: grains['lsb_distrib_codename'] += ' ' + patchstr if not grains.get('lsb_distrib_codename'): grains['lsb_distrib_codename'] = 'n.a' elif os.path.isfile('/etc/altlinux-release'): log.trace('Parsing distrib info from /etc/altlinux-release') # ALT Linux grains['lsb_distrib_id'] = 'altlinux' with salt.utils.files.fopen('/etc/altlinux-release') as ifile: # This file is symlinked to from: # /etc/fedora-release # /etc/redhat-release # /etc/system-release for line in ifile: # ALT Linux Sisyphus (unstable) comps = line.split() if comps[0] == 'ALT': grains['lsb_distrib_release'] = comps[2] grains['lsb_distrib_codename'] = \ comps[3].replace('(', '').replace(')', '') elif os.path.isfile('/etc/centos-release'): log.trace('Parsing distrib info from /etc/centos-release') # Maybe CentOS Linux; could also be SUSE Expanded Support. # SUSE ES has both, centos-release and redhat-release. if os.path.isfile('/etc/redhat-release'): with salt.utils.files.fopen('/etc/redhat-release') as ifile: for line in ifile: if "red hat enterprise linux server" in line.lower(): # This is a SUSE Expanded Support Rhel installation grains['lsb_distrib_id'] = 'RedHat' break grains.setdefault('lsb_distrib_id', 'CentOS') with salt.utils.files.fopen('/etc/centos-release') as ifile: for line in ifile: # Need to pull out the version and codename # in the case of custom content in /etc/centos-release find_release = re.compile(r'\d+\.\d+') find_codename = re.compile(r'(?<=\()(.*?)(?=\))') release = find_release.search(line) codename = find_codename.search(line) if release is not None: grains['lsb_distrib_release'] = release.group() if codename is not None: grains['lsb_distrib_codename'] = codename.group() elif os.path.isfile('/etc.defaults/VERSION') \ and os.path.isfile('/etc.defaults/synoinfo.conf'): grains['osfullname'] = 'Synology' log.trace( 'Parsing Synology distrib info from /etc/.defaults/VERSION' ) with salt.utils.files.fopen('/etc.defaults/VERSION', 'r') as fp_: synoinfo = {} for line in fp_: try: key, val = line.rstrip('\n').split('=') except ValueError: continue if key in ('majorversion', 'minorversion', 'buildnumber'): synoinfo[key] = val.strip('"') if len(synoinfo) != 3: log.warning( 'Unable to determine Synology version info. ' 'Please report this, as it is likely a bug.' ) else: grains['osrelease'] = ( '{majorversion}.{minorversion}-{buildnumber}' .format(**synoinfo) ) # Use the already intelligent platform module to get distro info # (though apparently it's not intelligent enough to strip quotes) log.trace( 'Getting OS name, release, and codename from ' 'distro.linux_distribution()' ) (osname, osrelease, oscodename) = \ [x.strip('"').strip("'") for x in linux_distribution(supported_dists=_supported_dists)] # Try to assign these three names based on the lsb info, they tend to # be more accurate than what python gets from /etc/DISTRO-release. # It's worth noting that Ubuntu has patched their Python distribution # so that linux_distribution() does the /etc/lsb-release parsing, but # we do it anyway here for the sake for full portability. if 'osfullname' not in grains: # If NI Linux RT distribution, set the grains['osfullname'] to 'nilrt' if grains.get('lsb_distrib_id', '').lower().startswith('nilrt'): grains['osfullname'] = 'nilrt' else: grains['osfullname'] = grains.get('lsb_distrib_id', osname).strip() if 'osrelease' not in grains: # NOTE: This is a workaround for CentOS 7 os-release bug # https://bugs.centos.org/view.php?id=8359 # /etc/os-release contains no minor distro release number so we fall back to parse # /etc/centos-release file instead. # Commit introducing this comment should be reverted after the upstream bug is released. if 'CentOS Linux 7' in grains.get('lsb_distrib_codename', ''): grains.pop('lsb_distrib_release', None) grains['osrelease'] = grains.get('lsb_distrib_release', osrelease).strip() grains['oscodename'] = grains.get('lsb_distrib_codename', '').strip() or oscodename if 'Red Hat' in grains['oscodename']: grains['oscodename'] = oscodename distroname = _REPLACE_LINUX_RE.sub('', grains['osfullname']).strip() # return the first ten characters with no spaces, lowercased shortname = distroname.replace(' ', '').lower()[:10] # this maps the long names from the /etc/DISTRO-release files to the # traditional short names that Salt has used. if 'os' not in grains: grains['os'] = _OS_NAME_MAP.get(shortname, distroname) grains.update(_linux_cpudata()) grains.update(_linux_gpu_data()) elif grains['kernel'] == 'SunOS': if salt.utils.platform.is_smartos(): # See https://github.com/joyent/smartos-live/issues/224 if HAS_UNAME: uname_v = os.uname()[3] # format: joyent_20161101T004406Z else: uname_v = os.name uname_v = uname_v[uname_v.index('_')+1:] grains['os'] = grains['osfullname'] = 'SmartOS' # store a parsed version of YYYY.MM.DD as osrelease grains['osrelease'] = ".".join([ uname_v.split('T')[0][0:4], uname_v.split('T')[0][4:6], uname_v.split('T')[0][6:8], ]) # store a untouched copy of the timestamp in osrelease_stamp grains['osrelease_stamp'] = uname_v elif os.path.isfile('/etc/release'): with salt.utils.files.fopen('/etc/release', 'r') as fp_: rel_data = fp_.read() try: release_re = re.compile( r'((?:Open|Oracle )?Solaris|OpenIndiana|OmniOS) (Development)?' r'\s*(\d+\.?\d*|v\d+)\s?[A-Z]*\s?(r\d+|\d+\/\d+|oi_\S+|snv_\S+)?' ) osname, development, osmajorrelease, osminorrelease = release_re.search(rel_data).groups() except AttributeError: # Set a blank osrelease grain and fallback to 'Solaris' # as the 'os' grain. grains['os'] = grains['osfullname'] = 'Solaris' grains['osrelease'] = '' else: if development is not None: osname = ' '.join((osname, development)) if HAS_UNAME: uname_v = os.uname()[3] else: uname_v = os.name grains['os'] = grains['osfullname'] = osname if osname in ['Oracle Solaris'] and uname_v.startswith(osmajorrelease): # Oracla Solars 11 and up have minor version in uname grains['osrelease'] = uname_v elif osname in ['OmniOS']: # OmniOS osrelease = [] osrelease.append(osmajorrelease[1:]) osrelease.append(osminorrelease[1:]) grains['osrelease'] = ".".join(osrelease) grains['osrelease_stamp'] = uname_v else: # Sun Solaris 10 and earlier/comparable osrelease = [] osrelease.append(osmajorrelease) if osminorrelease: osrelease.append(osminorrelease) grains['osrelease'] = ".".join(osrelease) grains['osrelease_stamp'] = uname_v grains.update(_sunos_cpudata()) elif grains['kernel'] == 'VMkernel': grains['os'] = 'ESXi' elif grains['kernel'] == 'Darwin': osrelease = __salt__['cmd.run']('sw_vers -productVersion') osname = __salt__['cmd.run']('sw_vers -productName') osbuild = __salt__['cmd.run']('sw_vers -buildVersion') grains['os'] = 'MacOS' grains['os_family'] = 'MacOS' grains['osfullname'] = "{0} {1}".format(osname, osrelease) grains['osrelease'] = osrelease grains['osbuild'] = osbuild grains['init'] = 'launchd' grains.update(_bsd_cpudata(grains)) grains.update(_osx_gpudata()) grains.update(_osx_platform_data()) elif grains['kernel'] == 'AIX': osrelease = __salt__['cmd.run']('oslevel') osrelease_techlevel = __salt__['cmd.run']('oslevel -r') osname = __salt__['cmd.run']('uname') grains['os'] = 'AIX' grains['osfullname'] = osname grains['osrelease'] = osrelease grains['osrelease_techlevel'] = osrelease_techlevel grains.update(_aix_cpudata()) else: grains['os'] = grains['kernel'] if grains['kernel'] == 'FreeBSD': try: grains['osrelease'] = __salt__['cmd.run']('freebsd-version -u').split('-')[0] except salt.exceptions.CommandExecutionError: # freebsd-version was introduced in 10.0. # derive osrelease from kernelversion prior to that grains['osrelease'] = grains['kernelrelease'].split('-')[0] grains.update(_bsd_cpudata(grains)) if grains['kernel'] in ('OpenBSD', 'NetBSD'): grains.update(_bsd_cpudata(grains)) grains['osrelease'] = grains['kernelrelease'].split('-')[0] if grains['kernel'] == 'NetBSD': grains.update(_netbsd_gpu_data()) if not grains['os']: grains['os'] = 'Unknown {0}'.format(grains['kernel']) grains['os_family'] = 'Unknown' else: # this assigns family names based on the os name # family defaults to the os name if not found grains['os_family'] = _OS_FAMILY_MAP.get(grains['os'], grains['os']) # Build the osarch grain. This grain will be used for platform-specific # considerations such as package management. Fall back to the CPU # architecture. if grains.get('os_family') == 'Debian': osarch = __salt__['cmd.run']('dpkg --print-architecture').strip() elif grains.get('os_family') in ['RedHat', 'Suse']: osarch = salt.utils.pkg.rpm.get_osarch() elif grains.get('os_family') in ('NILinuxRT', 'Poky'): archinfo = {} for line in __salt__['cmd.run']('opkg print-architecture').splitlines(): if line.startswith('arch'): _, arch, priority = line.split() archinfo[arch.strip()] = int(priority.strip()) # Return osarch in priority order (higher to lower) osarch = sorted(archinfo, key=archinfo.get, reverse=True) else: osarch = grains['cpuarch'] grains['osarch'] = osarch grains.update(_memdata(grains)) # Get the hardware and bios data grains.update(_hw_data(grains)) # Load the virtual machine info grains.update(_virtual(grains)) grains.update(_virtual_hv(grains)) grains.update(_ps(grains)) if grains.get('osrelease', ''): osrelease_info = grains['osrelease'].split('.') for idx, value in enumerate(osrelease_info): if not value.isdigit(): continue osrelease_info[idx] = int(value) grains['osrelease_info'] = tuple(osrelease_info) try: grains['osmajorrelease'] = int(grains['osrelease_info'][0]) except (IndexError, TypeError, ValueError): log.debug( 'Unable to derive osmajorrelease from osrelease_info \'%s\'. ' 'The osmajorrelease grain will not be set.', grains['osrelease_info'] ) os_name = grains['os' if grains.get('os') in ( 'Debian', 'FreeBSD', 'OpenBSD', 'NetBSD', 'Mac', 'Raspbian') else 'osfullname'] grains['osfinger'] = '{0}-{1}'.format( os_name, grains['osrelease'] if os_name in ('Ubuntu',) else grains['osrelease_info'][0]) return grains def locale_info(): ''' Provides defaultlanguage defaultencoding ''' grains = {} grains['locale_info'] = {} if salt.utils.platform.is_proxy(): return grains try: ( grains['locale_info']['defaultlanguage'], grains['locale_info']['defaultencoding'] ) = locale.getdefaultlocale() except Exception: # locale.getdefaultlocale can ValueError!! Catch anything else it # might do, per #2205 grains['locale_info']['defaultlanguage'] = 'unknown' grains['locale_info']['defaultencoding'] = 'unknown' grains['locale_info']['detectedencoding'] = __salt_system_encoding__ if _DATEUTIL_TZ: grains['locale_info']['timezone'] = datetime.datetime.now(dateutil.tz.tzlocal()).tzname() return grains def hostname(): ''' Return fqdn, hostname, domainname ''' # This is going to need some work # Provides: # fqdn # host # localhost # domain global __FQDN__ grains = {} if salt.utils.platform.is_proxy(): return grains grains['localhost'] = socket.gethostname() if __FQDN__ is None: __FQDN__ = salt.utils.network.get_fqhostname() # On some distros (notably FreeBSD) if there is no hostname set # salt.utils.network.get_fqhostname() will return None. # In this case we punt and log a message at error level, but force the # hostname and domain to be localhost.localdomain # Otherwise we would stacktrace below if __FQDN__ is None: # still! log.error('Having trouble getting a hostname. Does this machine have its hostname and domain set properly?') __FQDN__ = 'localhost.localdomain' grains['fqdn'] = __FQDN__ (grains['host'], grains['domain']) = grains['fqdn'].partition('.')[::2] return grains def append_domain(): ''' Return append_domain if set ''' grain = {} if salt.utils.platform.is_proxy(): return grain if 'append_domain' in __opts__: grain['append_domain'] = __opts__['append_domain'] return grain def fqdns(): ''' Return all known FQDNs for the system by enumerating all interfaces and then trying to reverse resolve them (excluding 'lo' interface). ''' # Provides: # fqdns grains = {} fqdns = set() addresses = salt.utils.network.ip_addrs(include_loopback=False, interface_data=_get_interfaces()) addresses.extend(salt.utils.network.ip_addrs6(include_loopback=False, interface_data=_get_interfaces())) err_message = 'Exception during resolving address: %s' for ip in addresses: try: name, aliaslist, addresslist = socket.gethostbyaddr(ip) fqdns.update([socket.getfqdn(name)] + [als for als in aliaslist if salt.utils.network.is_fqdn(als)]) except socket.herror as err: if err.errno == 0: # No FQDN for this IP address, so we don't need to know this all the time. log.debug("Unable to resolve address %s: %s", ip, err) else: log.error(err_message, err) except (socket.error, socket.gaierror, socket.timeout) as err: log.error(err_message, err) return {"fqdns": sorted(list(fqdns))} def ip_interfaces(): ''' Provide a dict of the connected interfaces and their ip addresses The addresses will be passed as a list for each interface ''' # Provides: # ip_interfaces if salt.utils.platform.is_proxy(): return {} ret = {} ifaces = _get_interfaces() for face in ifaces: iface_ips = [] for inet in ifaces[face].get('inet', []): if 'address' in inet: iface_ips.append(inet['address']) for inet in ifaces[face].get('inet6', []): if 'address' in inet: iface_ips.append(inet['address']) for secondary in ifaces[face].get('secondary', []): if 'address' in secondary: iface_ips.append(secondary['address']) ret[face] = iface_ips return {'ip_interfaces': ret} def ip4_interfaces(): ''' Provide a dict of the connected interfaces and their ip4 addresses The addresses will be passed as a list for each interface ''' # Provides: # ip_interfaces if salt.utils.platform.is_proxy(): return {} ret = {} ifaces = _get_interfaces() for face in ifaces: iface_ips = [] for inet in ifaces[face].get('inet', []): if 'address' in inet: iface_ips.append(inet['address']) for secondary in ifaces[face].get('secondary', []): if 'address' in secondary: iface_ips.append(secondary['address']) ret[face] = iface_ips return {'ip4_interfaces': ret} def ip6_interfaces(): ''' Provide a dict of the connected interfaces and their ip6 addresses The addresses will be passed as a list for each interface ''' # Provides: # ip_interfaces if salt.utils.platform.is_proxy(): return {} ret = {} ifaces = _get_interfaces() for face in ifaces: iface_ips = [] for inet in ifaces[face].get('inet6', []): if 'address' in inet: iface_ips.append(inet['address']) for secondary in ifaces[face].get('secondary', []): if 'address' in secondary: iface_ips.append(secondary['address']) ret[face] = iface_ips return {'ip6_interfaces': ret} def hwaddr_interfaces(): ''' Provide a dict of the connected interfaces and their hw addresses (Mac Address) ''' # Provides: # hwaddr_interfaces ret = {} ifaces = _get_interfaces() for face in ifaces: if 'hwaddr' in ifaces[face]: ret[face] = ifaces[face]['hwaddr'] return {'hwaddr_interfaces': ret} def dns(): ''' Parse the resolver configuration file .. versionadded:: 2016.3.0 ''' # Provides: # dns if salt.utils.platform.is_windows() or 'proxyminion' in __opts__: return {} resolv = salt.utils.dns.parse_resolv() for key in ('nameservers', 'ip4_nameservers', 'ip6_nameservers', 'sortlist'): if key in resolv: resolv[key] = [six.text_type(i) for i in resolv[key]] return {'dns': resolv} if resolv else {} def get_machine_id(): ''' Provide the machine-id for machine/virtualization combination ''' # Provides: # machine-id if platform.system() == 'AIX': return _aix_get_machine_id() locations = ['/etc/machine-id', '/var/lib/dbus/machine-id'] existing_locations = [loc for loc in locations if os.path.exists(loc)] if not existing_locations: return {} else: with salt.utils.files.fopen(existing_locations[0]) as machineid: return {'machine_id': machineid.read().strip()} def cwd(): ''' Current working directory ''' return {'cwd': os.getcwd()} def path(): ''' Return the path ''' # Provides: # path return {'path': os.environ.get('PATH', '').strip()} def pythonversion(): ''' Return the Python version ''' # Provides: # pythonversion return {'pythonversion': list(sys.version_info)} def pythonpath(): ''' Return the Python path ''' # Provides: # pythonpath return {'pythonpath': sys.path} def pythonexecutable(): ''' Return the python executable in use ''' # Provides: # pythonexecutable return {'pythonexecutable': sys.executable} def saltpath(): ''' Return the path of the salt module ''' # Provides: # saltpath salt_path = os.path.abspath(os.path.join(__file__, os.path.pardir)) return {'saltpath': os.path.dirname(salt_path)} def saltversion(): ''' Return the version of salt ''' # Provides: # saltversion from salt.version import __version__ return {'saltversion': __version__} def zmqversion(): ''' Return the zeromq version ''' # Provides: # zmqversion try: import zmq return {'zmqversion': zmq.zmq_version()} # pylint: disable=no-member except ImportError: return {} def saltversioninfo(): ''' Return the version_info of salt .. versionadded:: 0.17.0 ''' # Provides: # saltversioninfo from salt.version import __version_info__ return {'saltversioninfo': list(__version_info__)} def _hw_data(osdata): ''' Get system specific hardware data from dmidecode Provides biosversion productname manufacturer serialnumber biosreleasedate uuid .. versionadded:: 0.9.5 ''' if salt.utils.platform.is_proxy(): return {} grains = {} if osdata['kernel'] == 'Linux' and os.path.exists('/sys/class/dmi/id'): # On many Linux distributions basic firmware information is available via sysfs # requires CONFIG_DMIID to be enabled in the Linux kernel configuration sysfs_firmware_info = { 'biosversion': 'bios_version', 'productname': 'product_name', 'manufacturer': 'sys_vendor', 'biosreleasedate': 'bios_date', 'uuid': 'product_uuid', 'serialnumber': 'product_serial' } for key, fw_file in sysfs_firmware_info.items(): contents_file = os.path.join('/sys/class/dmi/id', fw_file) if os.path.exists(contents_file): try: with salt.utils.files.fopen(contents_file, 'r') as ifile: grains[key] = salt.utils.stringutils.to_unicode(ifile.read().strip(), errors='replace') if key == 'uuid': grains['uuid'] = grains['uuid'].lower() except (IOError, OSError) as err: # PermissionError is new to Python 3, but corresponds to the EACESS and # EPERM error numbers. Use those instead here for PY2 compatibility. if err.errno == EACCES or err.errno == EPERM: # Skip the grain if non-root user has no access to the file. pass elif salt.utils.path.which_bin(['dmidecode', 'smbios']) is not None and not ( salt.utils.platform.is_smartos() or ( # SunOS on SPARC - 'smbios: failed to load SMBIOS: System does not export an SMBIOS table' osdata['kernel'] == 'SunOS' and osdata['cpuarch'].startswith('sparc') )): # On SmartOS (possibly SunOS also) smbios only works in the global zone # smbios is also not compatible with linux's smbios (smbios -s = print summarized) grains = { 'biosversion': __salt__['smbios.get']('bios-version'), 'productname': __salt__['smbios.get']('system-product-name'), 'manufacturer': __salt__['smbios.get']('system-manufacturer'), 'biosreleasedate': __salt__['smbios.get']('bios-release-date'), 'uuid': __salt__['smbios.get']('system-uuid') } grains = dict([(key, val) for key, val in grains.items() if val is not None]) uuid = __salt__['smbios.get']('system-uuid') if uuid is not None: grains['uuid'] = uuid.lower() for serial in ('system-serial-number', 'chassis-serial-number', 'baseboard-serial-number'): serial = __salt__['smbios.get'](serial) if serial is not None: grains['serialnumber'] = serial break elif salt.utils.path.which_bin(['fw_printenv']) is not None: # ARM Linux devices expose UBOOT env variables via fw_printenv hwdata = { 'manufacturer': 'manufacturer', 'serialnumber': 'serial#', 'productname': 'DeviceDesc', } for grain_name, cmd_key in six.iteritems(hwdata): result = __salt__['cmd.run_all']('fw_printenv {0}'.format(cmd_key)) if result['retcode'] == 0: uboot_keyval = result['stdout'].split('=') grains[grain_name] = _clean_value(grain_name, uboot_keyval[1]) elif osdata['kernel'] == 'FreeBSD': # On FreeBSD /bin/kenv (already in base system) # can be used instead of dmidecode kenv = salt.utils.path.which('kenv') if kenv: # In theory, it will be easier to add new fields to this later fbsd_hwdata = { 'biosversion': 'smbios.bios.version', 'manufacturer': 'smbios.system.maker', 'serialnumber': 'smbios.system.serial', 'productname': 'smbios.system.product', 'biosreleasedate': 'smbios.bios.reldate', 'uuid': 'smbios.system.uuid', } for key, val in six.iteritems(fbsd_hwdata): value = __salt__['cmd.run']('{0} {1}'.format(kenv, val)) grains[key] = _clean_value(key, value) elif osdata['kernel'] == 'OpenBSD': sysctl = salt.utils.path.which('sysctl') hwdata = {'biosversion': 'hw.version', 'manufacturer': 'hw.vendor', 'productname': 'hw.product', 'serialnumber': 'hw.serialno', 'uuid': 'hw.uuid'} for key, oid in six.iteritems(hwdata): value = __salt__['cmd.run']('{0} -n {1}'.format(sysctl, oid)) if not value.endswith(' value is not available'): grains[key] = _clean_value(key, value) elif osdata['kernel'] == 'NetBSD': sysctl = salt.utils.path.which('sysctl') nbsd_hwdata = { 'biosversion': 'machdep.dmi.board-version', 'manufacturer': 'machdep.dmi.system-vendor', 'serialnumber': 'machdep.dmi.system-serial', 'productname': 'machdep.dmi.system-product', 'biosreleasedate': 'machdep.dmi.bios-date', 'uuid': 'machdep.dmi.system-uuid', } for key, oid in six.iteritems(nbsd_hwdata): result = __salt__['cmd.run_all']('{0} -n {1}'.format(sysctl, oid)) if result['retcode'] == 0: grains[key] = _clean_value(key, result['stdout']) elif osdata['kernel'] == 'Darwin': grains['manufacturer'] = 'Apple Inc.' sysctl = salt.utils.path.which('sysctl') hwdata = {'productname': 'hw.model'} for key, oid in hwdata.items(): value = __salt__['cmd.run']('{0} -b {1}'.format(sysctl, oid)) if not value.endswith(' is invalid'): grains[key] = _clean_value(key, value) elif osdata['kernel'] == 'SunOS' and osdata['cpuarch'].startswith('sparc'): # Depending on the hardware model, commands can report different bits # of information. With that said, consolidate the output from various # commands and attempt various lookups. data = "" for (cmd, args) in (('/usr/sbin/prtdiag', '-v'), ('/usr/sbin/prtconf', '-vp'), ('/usr/sbin/virtinfo', '-a')): if salt.utils.path.which(cmd): # Also verifies that cmd is executable data += __salt__['cmd.run']('{0} {1}'.format(cmd, args)) data += '\n' sn_regexes = [ re.compile(r) for r in [ r'(?im)^\s*Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag r'(?im)^\s*chassis-sn:\s*(\S+)', # prtconf r'(?im)^\s*Chassis\s+Serial#:\s*(\S+)', # virtinfo ] ] obp_regexes = [ re.compile(r) for r in [ r'(?im)^\s*System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag r'(?im)^\s*version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf ] ] fw_regexes = [ re.compile(r) for r in [ r'(?im)^\s*Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag ] ] uuid_regexes = [ re.compile(r) for r in [ r'(?im)^\s*Domain\s+UUID:\s*(\S+)', # virtinfo ] ] manufacture_regexes = [ re.compile(r) for r in [ r'(?im)^\s*System\s+Configuration:\s*(.*)(?=sun)', # prtdiag ] ] product_regexes = [ re.compile(r) for r in [ r'(?im)^\s*System\s+Configuration:\s*.*?sun\d\S+[^\S\r\n]*(.*)', # prtdiag r'(?im)^[^\S\r\n]*banner-name:[^\S\r\n]*(.*)', # prtconf r'(?im)^[^\S\r\n]*product-name:[^\S\r\n]*(.*)', # prtconf ] ] sn_regexes = [ re.compile(r) for r in [ r'(?im)Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag r'(?i)Chassis\s+Serial#:\s*(\S+)', # virtinfo r'(?i)chassis-sn:\s*(\S+)', # prtconf ] ] obp_regexes = [ re.compile(r) for r in [ r'(?im)System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag r'(?im)version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf ] ] fw_regexes = [ re.compile(r) for r in [ r'(?i)Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag ] ] uuid_regexes = [ re.compile(r) for r in [ r'(?i)Domain\s+UUID:\s+(\S+)', # virtinfo ] ] for regex in sn_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: grains['serialnumber'] = res.group(1).strip().replace("'", "") break for regex in obp_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: obp_rev, obp_date = res.groups()[0:2] # Limit the number in case we found the data in multiple places grains['biosversion'] = obp_rev.strip().replace("'", "") grains['biosreleasedate'] = obp_date.strip().replace("'", "") for regex in fw_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: fw_rev, fw_date = res.groups()[0:2] grains['systemfirmware'] = fw_rev.strip().replace("'", "") grains['systemfirmwaredate'] = fw_date.strip().replace("'", "") break for regex in uuid_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: grains['uuid'] = res.group(1).strip().replace("'", "") break for regex in manufacture_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: grains['manufacture'] = res.group(1).strip().replace("'", "") break for regex in product_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: t_productname = res.group(1).strip().replace("'", "") if t_productname: grains['product'] = t_productname grains['productname'] = t_productname break elif osdata['kernel'] == 'AIX': cmd = salt.utils.path.which('prtconf') if cmd: data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'), ('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')): for regex in [re.compile(r) for r in [regstring]]: res = regex.search(data) if res and len(res.groups()) >= 1: grains[dest] = res.group(1).strip().replace("'", '') product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')] for regex in product_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",") break else: log.error('The \'prtconf\' binary was not found in $PATH.') elif osdata['kernel'] == 'AIX': cmd = salt.utils.path.which('prtconf') if data: data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'), ('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')): for regex in [re.compile(r) for r in [regstring]]: res = regex.search(data) if res and len(res.groups()) >= 1: grains[dest] = res.group(1).strip().replace("'", '') product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')] for regex in product_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",") break else: log.error('The \'prtconf\' binary was not found in $PATH.') return grains def _get_hash_by_shell(): ''' Shell-out Python 3 for compute reliable hash :return: ''' id_ = __opts__.get('id', '') id_hash = None py_ver = sys.version_info[:2] if py_ver >= (3, 3): # Python 3.3 enabled hash randomization, so we need to shell out to get # a reliable hash. id_hash = __salt__['cmd.run']([sys.executable, '-c', 'print(hash("{0}"))'.format(id_)], env={'PYTHONHASHSEED': '0'}) try: id_hash = int(id_hash) except (TypeError, ValueError): log.debug('Failed to hash the ID to get the server_id grain. Result of hash command: %s', id_hash) id_hash = None if id_hash is None: # Python < 3.3 or error encountered above id_hash = hash(id_) return abs(id_hash % (2 ** 31)) def get_server_id(): ''' Provides an integer based on the FQDN of a machine. Useful as server-id in MySQL replication or anywhere else you'll need an ID like this. ''' # Provides: # server_id if salt.utils.platform.is_proxy(): server_id = {} else: use_crc = __opts__.get('server_id_use_crc') if bool(use_crc): id_hash = getattr(zlib, use_crc, zlib.adler32)(__opts__.get('id', '').encode()) & 0xffffffff else: log.debug('This server_id is computed not by Adler32 nor by CRC32. ' 'Please use "server_id_use_crc" option and define algorithm you ' 'prefer (default "Adler32"). Starting with Sodium, the ' 'server_id will be computed with Adler32 by default.') id_hash = _get_hash_by_shell() server_id = {'server_id': id_hash} return server_id def get_master(): ''' Provides the minion with the name of its master. This is useful in states to target other services running on the master. ''' # Provides: # master return {'master': __opts__.get('master', '')} def default_gateway(): ''' Populates grains which describe whether a server has a default gateway configured or not. Uses `ip -4 route show` and `ip -6 route show` and greps for a `default` at the beginning of any line. Assuming the standard `default via <ip>` format for default gateways, it will also parse out the ip address of the default gateway, and put it in ip4_gw or ip6_gw. If the `ip` command is unavailable, no grains will be populated. Currently does not support multiple default gateways. The grains will be set to the first default gateway found. List of grains: ip4_gw: True # ip/True/False if default ipv4 gateway ip6_gw: True # ip/True/False if default ipv6 gateway ip_gw: True # True if either of the above is True, False otherwise ''' grains = {} ip_bin = salt.utils.path.which('ip') if not ip_bin: return {} grains['ip_gw'] = False grains['ip4_gw'] = False grains['ip6_gw'] = False for ip_version in ('4', '6'): try: out = __salt__['cmd.run']([ip_bin, '-' + ip_version, 'route', 'show']) for line in out.splitlines(): if line.startswith('default'): grains['ip_gw'] = True grains['ip{0}_gw'.format(ip_version)] = True try: via, gw_ip = line.split()[1:3] except ValueError: pass else: if via == 'via': grains['ip{0}_gw'.format(ip_version)] = gw_ip break except Exception: continue return grains def kernelparams(): ''' Return the kernel boot parameters ''' if salt.utils.platform.is_windows(): # TODO: add grains using `bcdedit /enum {current}` return {} else: try: with salt.utils.files.fopen('/proc/cmdline', 'r') as fhr: cmdline = fhr.read() grains = {'kernelparams': []} for data in [item.split('=') for item in salt.utils.args.shlex_split(cmdline)]: value = None if len(data) == 2: value = data[1].strip('"') grains['kernelparams'] += [(data[0], value)] except IOError as exc: grains = {} log.debug('Failed to read /proc/cmdline: %s', exc) return grains
saltstack/salt
salt/grains/core.py
ip_interfaces
python
def ip_interfaces(): ''' Provide a dict of the connected interfaces and their ip addresses The addresses will be passed as a list for each interface ''' # Provides: # ip_interfaces if salt.utils.platform.is_proxy(): return {} ret = {} ifaces = _get_interfaces() for face in ifaces: iface_ips = [] for inet in ifaces[face].get('inet', []): if 'address' in inet: iface_ips.append(inet['address']) for inet in ifaces[face].get('inet6', []): if 'address' in inet: iface_ips.append(inet['address']) for secondary in ifaces[face].get('secondary', []): if 'address' in secondary: iface_ips.append(secondary['address']) ret[face] = iface_ips return {'ip_interfaces': ret}
Provide a dict of the connected interfaces and their ip addresses The addresses will be passed as a list for each interface
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/grains/core.py#L2229-L2254
[ "def _get_interfaces():\n '''\n Provide a dict of the connected interfaces and their ip addresses\n '''\n\n global _INTERFACES\n if not _INTERFACES:\n _INTERFACES = salt.utils.network.interfaces()\n return _INTERFACES\n" ]
# -*- coding: utf-8 -*- ''' The static grains, these are the core, or built in grains. When grains are loaded they are not loaded in the same way that modules are loaded, grain functions are detected and executed, the functions MUST return a dict which will be applied to the main grains dict. This module will always be executed first, so that any grains loaded here in the core module can be overwritten just by returning dict keys with the same value as those returned here ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import socket import sys import re import platform import logging import locale import uuid import zlib from errno import EACCES, EPERM import datetime import warnings # pylint: disable=import-error try: import dateutil.tz _DATEUTIL_TZ = True except ImportError: _DATEUTIL_TZ = False __proxyenabled__ = ['*'] __FQDN__ = None # Extend the default list of supported distros. This will be used for the # /etc/DISTRO-release checking that is part of linux_distribution() from platform import _supported_dists _supported_dists += ('arch', 'mageia', 'meego', 'vmware', 'bluewhite64', 'slamd64', 'ovs', 'system', 'mint', 'oracle', 'void') # linux_distribution deprecated in py3.7 try: from platform import linux_distribution as _deprecated_linux_distribution def linux_distribution(**kwargs): with warnings.catch_warnings(): warnings.simplefilter("ignore") return _deprecated_linux_distribution(**kwargs) except ImportError: from distro import linux_distribution # Import salt libs import salt.exceptions import salt.log import salt.utils.args import salt.utils.dns import salt.utils.files import salt.utils.network import salt.utils.path import salt.utils.pkg.rpm import salt.utils.platform import salt.utils.stringutils import salt.utils.versions from salt.ext import six from salt.ext.six.moves import range if salt.utils.platform.is_windows(): import salt.utils.win_osinfo # Solve the Chicken and egg problem where grains need to run before any # of the modules are loaded and are generally available for any usage. import salt.modules.cmdmod import salt.modules.smbios __salt__ = { 'cmd.run': salt.modules.cmdmod._run_quiet, 'cmd.retcode': salt.modules.cmdmod._retcode_quiet, 'cmd.run_all': salt.modules.cmdmod._run_all_quiet, 'smbios.records': salt.modules.smbios.records, 'smbios.get': salt.modules.smbios.get, } log = logging.getLogger(__name__) HAS_WMI = False if salt.utils.platform.is_windows(): # attempt to import the python wmi module # the Windows minion uses WMI for some of its grains try: import wmi # pylint: disable=import-error import salt.utils.winapi import win32api import salt.utils.win_reg HAS_WMI = True except ImportError: log.exception( 'Unable to import Python wmi module, some core grains ' 'will be missing' ) HAS_UNAME = True if not hasattr(os, 'uname'): HAS_UNAME = False _INTERFACES = {} def _windows_cpudata(): ''' Return some CPU information on Windows minions ''' # Provides: # num_cpus # cpu_model grains = {} if 'NUMBER_OF_PROCESSORS' in os.environ: # Cast to int so that the logic isn't broken when used as a # conditional in templating. Also follows _linux_cpudata() try: grains['num_cpus'] = int(os.environ['NUMBER_OF_PROCESSORS']) except ValueError: grains['num_cpus'] = 1 grains['cpu_model'] = salt.utils.win_reg.read_value( hive="HKEY_LOCAL_MACHINE", key="HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", vname="ProcessorNameString").get('vdata') return grains def _linux_cpudata(): ''' Return some CPU information for Linux minions ''' # Provides: # num_cpus # cpu_model # cpu_flags grains = {} cpuinfo = '/proc/cpuinfo' # Parse over the cpuinfo file if os.path.isfile(cpuinfo): with salt.utils.files.fopen(cpuinfo, 'r') as _fp: grains['num_cpus'] = 0 for line in _fp: comps = line.split(':') if not len(comps) > 1: continue key = comps[0].strip() val = comps[1].strip() if key == 'processor': grains['num_cpus'] += 1 elif key == 'model name': grains['cpu_model'] = val elif key == 'flags': grains['cpu_flags'] = val.split() elif key == 'Features': grains['cpu_flags'] = val.split() # ARM support - /proc/cpuinfo # # Processor : ARMv6-compatible processor rev 7 (v6l) # BogoMIPS : 697.95 # Features : swp half thumb fastmult vfp edsp java tls # CPU implementer : 0x41 # CPU architecture: 7 # CPU variant : 0x0 # CPU part : 0xb76 # CPU revision : 7 # # Hardware : BCM2708 # Revision : 0002 # Serial : 00000000 elif key == 'Processor': grains['cpu_model'] = val.split('-')[0] grains['num_cpus'] = 1 if 'num_cpus' not in grains: grains['num_cpus'] = 0 if 'cpu_model' not in grains: grains['cpu_model'] = 'Unknown' if 'cpu_flags' not in grains: grains['cpu_flags'] = [] return grains def _linux_gpu_data(): ''' num_gpus: int gpus: - vendor: nvidia|amd|ati|... model: string ''' if __opts__.get('enable_lspci', True) is False: return {} if __opts__.get('enable_gpu_grains', True) is False: return {} lspci = salt.utils.path.which('lspci') if not lspci: log.debug( 'The `lspci` binary is not available on the system. GPU grains ' 'will not be available.' ) return {} # dominant gpu vendors to search for (MUST be lowercase for matching below) known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed'] gpu_classes = ('vga compatible controller', '3d controller') devs = [] try: lspci_out = __salt__['cmd.run']('{0} -vmm'.format(lspci)) cur_dev = {} error = False # Add a blank element to the lspci_out.splitlines() list, # otherwise the last device is not evaluated as a cur_dev and ignored. lspci_list = lspci_out.splitlines() lspci_list.append('') for line in lspci_list: # check for record-separating empty lines if line == '': if cur_dev.get('Class', '').lower() in gpu_classes: devs.append(cur_dev) cur_dev = {} continue if re.match(r'^\w+:\s+.*', line): key, val = line.split(':', 1) cur_dev[key.strip()] = val.strip() else: error = True log.debug('Unexpected lspci output: \'%s\'', line) if error: log.warning( 'Error loading grains, unexpected linux_gpu_data output, ' 'check that you have a valid shell configured and ' 'permissions to run lspci command' ) except OSError: pass gpus = [] for gpu in devs: vendor_strings = re.split('[^A-Za-z0-9]', gpu['Vendor'].lower()) # default vendor to 'unknown', overwrite if we match a known one vendor = 'unknown' for name in known_vendors: # search for an 'expected' vendor name in the list of strings if name in vendor_strings: vendor = name break gpus.append({'vendor': vendor, 'model': gpu['Device']}) grains = {} grains['num_gpus'] = len(gpus) grains['gpus'] = gpus return grains def _netbsd_gpu_data(): ''' num_gpus: int gpus: - vendor: nvidia|amd|ati|... model: string ''' known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed'] gpus = [] try: pcictl_out = __salt__['cmd.run']('pcictl pci0 list') for line in pcictl_out.splitlines(): for vendor in known_vendors: vendor_match = re.match( r'[0-9:]+ ({0}) (.+) \(VGA .+\)'.format(vendor), line, re.IGNORECASE ) if vendor_match: gpus.append({'vendor': vendor_match.group(1), 'model': vendor_match.group(2)}) except OSError: pass grains = {} grains['num_gpus'] = len(gpus) grains['gpus'] = gpus return grains def _osx_gpudata(): ''' num_gpus: int gpus: - vendor: nvidia|amd|ati|... model: string ''' gpus = [] try: pcictl_out = __salt__['cmd.run']('system_profiler SPDisplaysDataType') for line in pcictl_out.splitlines(): fieldname, _, fieldval = line.partition(': ') if fieldname.strip() == "Chipset Model": vendor, _, model = fieldval.partition(' ') vendor = vendor.lower() gpus.append({'vendor': vendor, 'model': model}) except OSError: pass grains = {} grains['num_gpus'] = len(gpus) grains['gpus'] = gpus return grains def _bsd_cpudata(osdata): ''' Return CPU information for BSD-like systems ''' # Provides: # cpuarch # num_cpus # cpu_model # cpu_flags sysctl = salt.utils.path.which('sysctl') arch = salt.utils.path.which('arch') cmds = {} if sysctl: cmds.update({ 'num_cpus': '{0} -n hw.ncpu'.format(sysctl), 'cpuarch': '{0} -n hw.machine'.format(sysctl), 'cpu_model': '{0} -n hw.model'.format(sysctl), }) if arch and osdata['kernel'] == 'OpenBSD': cmds['cpuarch'] = '{0} -s'.format(arch) if osdata['kernel'] == 'Darwin': cmds['cpu_model'] = '{0} -n machdep.cpu.brand_string'.format(sysctl) cmds['cpu_flags'] = '{0} -n machdep.cpu.features'.format(sysctl) grains = dict([(k, __salt__['cmd.run'](v)) for k, v in six.iteritems(cmds)]) if 'cpu_flags' in grains and isinstance(grains['cpu_flags'], six.string_types): grains['cpu_flags'] = grains['cpu_flags'].split(' ') if osdata['kernel'] == 'NetBSD': grains['cpu_flags'] = [] for line in __salt__['cmd.run']('cpuctl identify 0').splitlines(): cpu_match = re.match(r'cpu[0-9]:\ features[0-9]?\ .+<(.+)>', line) if cpu_match: flag = cpu_match.group(1).split(',') grains['cpu_flags'].extend(flag) if osdata['kernel'] == 'FreeBSD' and os.path.isfile('/var/run/dmesg.boot'): grains['cpu_flags'] = [] # TODO: at least it needs to be tested for BSD other then FreeBSD with salt.utils.files.fopen('/var/run/dmesg.boot', 'r') as _fp: cpu_here = False for line in _fp: if line.startswith('CPU: '): cpu_here = True # starts CPU descr continue if cpu_here: if not line.startswith(' '): break # game over if 'Features' in line: start = line.find('<') end = line.find('>') if start > 0 and end > 0: flag = line[start + 1:end].split(',') grains['cpu_flags'].extend(flag) try: grains['num_cpus'] = int(grains['num_cpus']) except ValueError: grains['num_cpus'] = 1 return grains def _sunos_cpudata(): ''' Return the CPU information for Solaris-like systems ''' # Provides: # cpuarch # num_cpus # cpu_model # cpu_flags grains = {} grains['cpu_flags'] = [] grains['cpuarch'] = __salt__['cmd.run']('isainfo -k') psrinfo = '/usr/sbin/psrinfo 2>/dev/null' grains['num_cpus'] = len(__salt__['cmd.run'](psrinfo, python_shell=True).splitlines()) kstat_info = 'kstat -p cpu_info:*:*:brand' for line in __salt__['cmd.run'](kstat_info).splitlines(): match = re.match(r'(\w+:\d+:\w+\d+:\w+)\s+(.+)', line) if match: grains['cpu_model'] = match.group(2) isainfo = 'isainfo -n -v' for line in __salt__['cmd.run'](isainfo).splitlines(): match = re.match(r'^\s+(.+)', line) if match: cpu_flags = match.group(1).split() grains['cpu_flags'].extend(cpu_flags) return grains def _aix_cpudata(): ''' Return CPU information for AIX systems ''' # Provides: # cpuarch # num_cpus # cpu_model # cpu_flags grains = {} cmd = salt.utils.path.which('prtconf') if cmd: data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep for dest, regstring in (('cpuarch', r'(?im)^\s*Processor\s+Type:\s+(\S+)'), ('cpu_flags', r'(?im)^\s*Processor\s+Version:\s+(\S+)'), ('cpu_model', r'(?im)^\s*Processor\s+Implementation\s+Mode:\s+(.*)'), ('num_cpus', r'(?im)^\s*Number\s+Of\s+Processors:\s+(\S+)')): for regex in [re.compile(r) for r in [regstring]]: res = regex.search(data) if res and len(res.groups()) >= 1: grains[dest] = res.group(1).strip().replace("'", '') else: log.error('The \'prtconf\' binary was not found in $PATH.') return grains def _linux_memdata(): ''' Return the memory information for Linux-like systems ''' grains = {'mem_total': 0, 'swap_total': 0} meminfo = '/proc/meminfo' if os.path.isfile(meminfo): with salt.utils.files.fopen(meminfo, 'r') as ifile: for line in ifile: comps = line.rstrip('\n').split(':') if not len(comps) > 1: continue if comps[0].strip() == 'MemTotal': # Use floor division to force output to be an integer grains['mem_total'] = int(comps[1].split()[0]) // 1024 if comps[0].strip() == 'SwapTotal': # Use floor division to force output to be an integer grains['swap_total'] = int(comps[1].split()[0]) // 1024 return grains def _osx_memdata(): ''' Return the memory information for BSD-like systems ''' grains = {'mem_total': 0, 'swap_total': 0} sysctl = salt.utils.path.which('sysctl') if sysctl: mem = __salt__['cmd.run']('{0} -n hw.memsize'.format(sysctl)) swap_total = __salt__['cmd.run']('{0} -n vm.swapusage'.format(sysctl)).split()[2].replace(',', '.') if swap_total.endswith('K'): _power = 2**10 elif swap_total.endswith('M'): _power = 2**20 elif swap_total.endswith('G'): _power = 2**30 swap_total = float(swap_total[:-1]) * _power grains['mem_total'] = int(mem) // 1024 // 1024 grains['swap_total'] = int(swap_total) // 1024 // 1024 return grains def _bsd_memdata(osdata): ''' Return the memory information for BSD-like systems ''' grains = {'mem_total': 0, 'swap_total': 0} sysctl = salt.utils.path.which('sysctl') if sysctl: mem = __salt__['cmd.run']('{0} -n hw.physmem'.format(sysctl)) if osdata['kernel'] == 'NetBSD' and mem.startswith('-'): mem = __salt__['cmd.run']('{0} -n hw.physmem64'.format(sysctl)) grains['mem_total'] = int(mem) // 1024 // 1024 if osdata['kernel'] in ['OpenBSD', 'NetBSD']: swapctl = salt.utils.path.which('swapctl') swap_data = __salt__['cmd.run']('{0} -sk'.format(swapctl)) if swap_data == 'no swap devices configured': swap_total = 0 else: swap_total = swap_data.split(' ')[1] else: swap_total = __salt__['cmd.run']('{0} -n vm.swap_total'.format(sysctl)) grains['swap_total'] = int(swap_total) // 1024 // 1024 return grains def _sunos_memdata(): ''' Return the memory information for SunOS-like systems ''' grains = {'mem_total': 0, 'swap_total': 0} prtconf = '/usr/sbin/prtconf 2>/dev/null' for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines(): comps = line.split(' ') if comps[0].strip() == 'Memory' and comps[1].strip() == 'size:': grains['mem_total'] = int(comps[2].strip()) swap_cmd = salt.utils.path.which('swap') swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split() try: swap_avail = int(swap_data[-2][:-1]) swap_used = int(swap_data[-4][:-1]) swap_total = (swap_avail + swap_used) // 1024 except ValueError: swap_total = None grains['swap_total'] = swap_total return grains def _aix_memdata(): ''' Return the memory information for AIX systems ''' grains = {'mem_total': 0, 'swap_total': 0} prtconf = salt.utils.path.which('prtconf') if prtconf: for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines(): comps = [x for x in line.strip().split(' ') if x] if len(comps) > 2 and 'Memory' in comps[0] and 'Size' in comps[1]: grains['mem_total'] = int(comps[2]) break else: log.error('The \'prtconf\' binary was not found in $PATH.') swap_cmd = salt.utils.path.which('swap') if swap_cmd: swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split() try: swap_total = (int(swap_data[-2]) + int(swap_data[-6])) * 4 except ValueError: swap_total = None grains['swap_total'] = swap_total else: log.error('The \'swap\' binary was not found in $PATH.') return grains def _windows_memdata(): ''' Return the memory information for Windows systems ''' grains = {'mem_total': 0} # get the Total Physical memory as reported by msinfo32 tot_bytes = win32api.GlobalMemoryStatusEx()['TotalPhys'] # return memory info in gigabytes grains['mem_total'] = int(tot_bytes / (1024 ** 2)) return grains def _memdata(osdata): ''' Gather information about the system memory ''' # Provides: # mem_total # swap_total, for supported systems. grains = {'mem_total': 0} if osdata['kernel'] == 'Linux': grains.update(_linux_memdata()) elif osdata['kernel'] in ('FreeBSD', 'OpenBSD', 'NetBSD'): grains.update(_bsd_memdata(osdata)) elif osdata['kernel'] == 'Darwin': grains.update(_osx_memdata()) elif osdata['kernel'] == 'SunOS': grains.update(_sunos_memdata()) elif osdata['kernel'] == 'AIX': grains.update(_aix_memdata()) elif osdata['kernel'] == 'Windows' and HAS_WMI: grains.update(_windows_memdata()) return grains def _aix_get_machine_id(): ''' Parse the output of lsattr -El sys0 for os_uuid ''' grains = {} cmd = salt.utils.path.which('lsattr') if cmd: data = __salt__['cmd.run']('{0} -El sys0'.format(cmd)) + os.linesep uuid_regexes = [re.compile(r'(?im)^\s*os_uuid\s+(\S+)\s+(.*)')] for regex in uuid_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: grains['machine_id'] = res.group(1).strip() break else: log.error('The \'lsattr\' binary was not found in $PATH.') return grains def _windows_virtual(osdata): ''' Returns what type of virtual hardware is under the hood, kvm or physical ''' # Provides: # virtual # virtual_subtype grains = dict() if osdata['kernel'] != 'Windows': return grains grains['virtual'] = 'physical' # It is possible that the 'manufacturer' and/or 'productname' grains # exist but have a value of None. manufacturer = osdata.get('manufacturer', '') if manufacturer is None: manufacturer = '' productname = osdata.get('productname', '') if productname is None: productname = '' if 'QEMU' in manufacturer: # FIXME: Make this detect between kvm or qemu grains['virtual'] = 'kvm' if 'Bochs' in manufacturer: grains['virtual'] = 'kvm' # Product Name: (oVirt) www.ovirt.org # Red Hat Community virtualization Project based on kvm elif 'oVirt' in productname: grains['virtual'] = 'kvm' grains['virtual_subtype'] = 'oVirt' # Red Hat Enterprise Virtualization elif 'RHEV Hypervisor' in productname: grains['virtual'] = 'kvm' grains['virtual_subtype'] = 'rhev' # Product Name: VirtualBox elif 'VirtualBox' in productname: grains['virtual'] = 'VirtualBox' # Product Name: VMware Virtual Platform elif 'VMware Virtual Platform' in productname: grains['virtual'] = 'VMware' # Manufacturer: Microsoft Corporation # Product Name: Virtual Machine elif 'Microsoft' in manufacturer and \ 'Virtual Machine' in productname: grains['virtual'] = 'VirtualPC' # Manufacturer: Parallels Software International Inc. elif 'Parallels Software' in manufacturer: grains['virtual'] = 'Parallels' # Apache CloudStack elif 'CloudStack KVM Hypervisor' in productname: grains['virtual'] = 'kvm' grains['virtual_subtype'] = 'cloudstack' return grains def _virtual(osdata): ''' Returns what type of virtual hardware is under the hood, kvm or physical ''' # This is going to be a monster, if you are running a vm you can test this # grain with please submit patches! # Provides: # virtual # virtual_subtype grains = {'virtual': 'physical'} # Skip the below loop on platforms which have none of the desired cmds # This is a temporary measure until we can write proper virtual hardware # detection. skip_cmds = ('AIX',) # list of commands to be executed to determine the 'virtual' grain _cmds = ['systemd-detect-virt', 'virt-what', 'dmidecode'] # test first for virt-what, which covers most of the desired functionality # on most platforms if not salt.utils.platform.is_windows() and osdata['kernel'] not in skip_cmds: if salt.utils.path.which('virt-what'): _cmds = ['virt-what'] # Check if enable_lspci is True or False if __opts__.get('enable_lspci', True) is True: # /proc/bus/pci does not exists, lspci will fail if os.path.exists('/proc/bus/pci'): _cmds += ['lspci'] # Add additional last resort commands if osdata['kernel'] in skip_cmds: _cmds = () # Quick backout for BrandZ (Solaris LX Branded zones) # Don't waste time trying other commands to detect the virtual grain if HAS_UNAME and osdata['kernel'] == 'Linux' and 'BrandZ virtual linux' in os.uname(): grains['virtual'] = 'zone' return grains failed_commands = set() for command in _cmds: args = [] if osdata['kernel'] == 'Darwin': command = 'system_profiler' args = ['SPDisplaysDataType'] elif osdata['kernel'] == 'SunOS': virtinfo = salt.utils.path.which('virtinfo') if virtinfo: try: ret = __salt__['cmd.run_all']('{0} -a'.format(virtinfo)) except salt.exceptions.CommandExecutionError: if salt.log.is_logging_configured(): failed_commands.add(virtinfo) else: if ret['stdout'].endswith('not supported'): command = 'prtdiag' else: command = 'virtinfo' else: command = 'prtdiag' cmd = salt.utils.path.which(command) if not cmd: continue cmd = '{0} {1}'.format(cmd, ' '.join(args)) try: ret = __salt__['cmd.run_all'](cmd) if ret['retcode'] > 0: if salt.log.is_logging_configured(): # systemd-detect-virt always returns > 0 on non-virtualized # systems # prtdiag only works in the global zone, skip if it fails if salt.utils.platform.is_windows() or 'systemd-detect-virt' in cmd or 'prtdiag' in cmd: continue failed_commands.add(command) continue except salt.exceptions.CommandExecutionError: if salt.log.is_logging_configured(): if salt.utils.platform.is_windows(): continue failed_commands.add(command) continue output = ret['stdout'] if command == "system_profiler": macoutput = output.lower() if '0x1ab8' in macoutput: grains['virtual'] = 'Parallels' if 'parallels' in macoutput: grains['virtual'] = 'Parallels' if 'vmware' in macoutput: grains['virtual'] = 'VMware' if '0x15ad' in macoutput: grains['virtual'] = 'VMware' if 'virtualbox' in macoutput: grains['virtual'] = 'VirtualBox' # Break out of the loop so the next log message is not issued break elif command == 'systemd-detect-virt': if output in ('qemu', 'kvm', 'oracle', 'xen', 'bochs', 'chroot', 'uml', 'systemd-nspawn'): grains['virtual'] = output break elif 'vmware' in output: grains['virtual'] = 'VMware' break elif 'microsoft' in output: grains['virtual'] = 'VirtualPC' break elif 'lxc' in output: grains['virtual'] = 'LXC' break elif 'systemd-nspawn' in output: grains['virtual'] = 'LXC' break elif command == 'virt-what': try: output = output.splitlines()[-1] except IndexError: pass if output in ('kvm', 'qemu', 'uml', 'xen', 'lxc'): grains['virtual'] = output break elif 'vmware' in output: grains['virtual'] = 'VMware' break elif 'parallels' in output: grains['virtual'] = 'Parallels' break elif 'hyperv' in output: grains['virtual'] = 'HyperV' break elif command == 'dmidecode': # Product Name: VirtualBox if 'Vendor: QEMU' in output: # FIXME: Make this detect between kvm or qemu grains['virtual'] = 'kvm' if 'Manufacturer: QEMU' in output: grains['virtual'] = 'kvm' if 'Vendor: Bochs' in output: grains['virtual'] = 'kvm' if 'Manufacturer: Bochs' in output: grains['virtual'] = 'kvm' if 'BHYVE' in output: grains['virtual'] = 'bhyve' # Product Name: (oVirt) www.ovirt.org # Red Hat Community virtualization Project based on kvm elif 'Manufacturer: oVirt' in output: grains['virtual'] = 'kvm' grains['virtual_subtype'] = 'ovirt' # Red Hat Enterprise Virtualization elif 'Product Name: RHEV Hypervisor' in output: grains['virtual'] = 'kvm' grains['virtual_subtype'] = 'rhev' elif 'VirtualBox' in output: grains['virtual'] = 'VirtualBox' # Product Name: VMware Virtual Platform elif 'VMware' in output: grains['virtual'] = 'VMware' # Manufacturer: Microsoft Corporation # Product Name: Virtual Machine elif ': Microsoft' in output and 'Virtual Machine' in output: grains['virtual'] = 'VirtualPC' # Manufacturer: Parallels Software International Inc. elif 'Parallels Software' in output: grains['virtual'] = 'Parallels' elif 'Manufacturer: Google' in output: grains['virtual'] = 'kvm' # Proxmox KVM elif 'Vendor: SeaBIOS' in output: grains['virtual'] = 'kvm' # Break out of the loop, lspci parsing is not necessary break elif command == 'lspci': # dmidecode not available or the user does not have the necessary # permissions model = output.lower() if 'vmware' in model: grains['virtual'] = 'VMware' # 00:04.0 System peripheral: InnoTek Systemberatung GmbH # VirtualBox Guest Service elif 'virtualbox' in model: grains['virtual'] = 'VirtualBox' elif 'qemu' in model: grains['virtual'] = 'kvm' elif 'virtio' in model: grains['virtual'] = 'kvm' # Break out of the loop so the next log message is not issued break elif command == 'prtdiag': model = output.lower().split("\n")[0] if 'vmware' in model: grains['virtual'] = 'VMware' elif 'virtualbox' in model: grains['virtual'] = 'VirtualBox' elif 'qemu' in model: grains['virtual'] = 'kvm' elif 'joyent smartdc hvm' in model: grains['virtual'] = 'kvm' break elif command == 'virtinfo': grains['virtual'] = 'LDOM' break choices = ('Linux', 'HP-UX') isdir = os.path.isdir sysctl = salt.utils.path.which('sysctl') if osdata['kernel'] in choices: if os.path.isdir('/proc'): try: self_root = os.stat('/') init_root = os.stat('/proc/1/root/.') if self_root != init_root: grains['virtual_subtype'] = 'chroot' except (IOError, OSError): pass if isdir('/proc/vz'): if os.path.isfile('/proc/vz/version'): grains['virtual'] = 'openvzhn' elif os.path.isfile('/proc/vz/veinfo'): grains['virtual'] = 'openvzve' # a posteriori, it's expected for these to have failed: failed_commands.discard('lspci') failed_commands.discard('dmidecode') # Provide additional detection for OpenVZ if os.path.isfile('/proc/self/status'): with salt.utils.files.fopen('/proc/self/status') as status_file: vz_re = re.compile(r'^envID:\s+(\d+)$') for line in status_file: vz_match = vz_re.match(line.rstrip('\n')) if vz_match and int(vz_match.groups()[0]) != 0: grains['virtual'] = 'openvzve' elif vz_match and int(vz_match.groups()[0]) == 0: grains['virtual'] = 'openvzhn' if isdir('/proc/sys/xen') or \ isdir('/sys/bus/xen') or isdir('/proc/xen'): if os.path.isfile('/proc/xen/xsd_kva'): # Tested on CentOS 5.3 / 2.6.18-194.26.1.el5xen # Tested on CentOS 5.4 / 2.6.18-164.15.1.el5xen grains['virtual_subtype'] = 'Xen Dom0' else: if osdata.get('productname', '') == 'HVM domU': # Requires dmidecode! grains['virtual_subtype'] = 'Xen HVM DomU' elif os.path.isfile('/proc/xen/capabilities') and \ os.access('/proc/xen/capabilities', os.R_OK): with salt.utils.files.fopen('/proc/xen/capabilities') as fhr: if 'control_d' not in fhr.read(): # Tested on CentOS 5.5 / 2.6.18-194.3.1.el5xen grains['virtual_subtype'] = 'Xen PV DomU' else: # Shouldn't get to this, but just in case grains['virtual_subtype'] = 'Xen Dom0' # Tested on Fedora 10 / 2.6.27.30-170.2.82 with xen # Tested on Fedora 15 / 2.6.41.4-1 without running xen elif isdir('/sys/bus/xen'): if 'xen:' in __salt__['cmd.run']('dmesg').lower(): grains['virtual_subtype'] = 'Xen PV DomU' elif os.path.isfile('/sys/bus/xen/drivers/xenconsole'): # An actual DomU will have the xenconsole driver grains['virtual_subtype'] = 'Xen PV DomU' # If a Dom0 or DomU was detected, obviously this is xen if 'dom' in grains.get('virtual_subtype', '').lower(): grains['virtual'] = 'xen' # Check container type after hypervisors, to avoid variable overwrite on containers running in virtual environment. if os.path.isfile('/proc/1/cgroup'): try: with salt.utils.files.fopen('/proc/1/cgroup', 'r') as fhr: fhr_contents = fhr.read() if ':/lxc/' in fhr_contents: grains['virtual_subtype'] = 'LXC' elif ':/kubepods/' in fhr_contents: grains['virtual_subtype'] = 'kubernetes' elif ':/libpod_parent/' in fhr_contents: grains['virtual_subtype'] = 'libpod' else: if any(x in fhr_contents for x in (':/system.slice/docker', ':/docker/', ':/docker-ce/')): grains['virtual_subtype'] = 'Docker' except IOError: pass if os.path.isfile('/proc/cpuinfo'): with salt.utils.files.fopen('/proc/cpuinfo', 'r') as fhr: if 'QEMU Virtual CPU' in fhr.read(): grains['virtual'] = 'kvm' if os.path.isfile('/sys/devices/virtual/dmi/id/product_name'): try: with salt.utils.files.fopen('/sys/devices/virtual/dmi/id/product_name', 'r') as fhr: output = salt.utils.stringutils.to_unicode(fhr.read(), errors='replace') if 'VirtualBox' in output: grains['virtual'] = 'VirtualBox' elif 'RHEV Hypervisor' in output: grains['virtual'] = 'kvm' grains['virtual_subtype'] = 'rhev' elif 'oVirt Node' in output: grains['virtual'] = 'kvm' grains['virtual_subtype'] = 'ovirt' elif 'Google' in output: grains['virtual'] = 'gce' elif 'BHYVE' in output: grains['virtual'] = 'bhyve' except IOError: pass elif osdata['kernel'] == 'FreeBSD': kenv = salt.utils.path.which('kenv') if kenv: product = __salt__['cmd.run']( '{0} smbios.system.product'.format(kenv) ) maker = __salt__['cmd.run']( '{0} smbios.system.maker'.format(kenv) ) if product.startswith('VMware'): grains['virtual'] = 'VMware' if product.startswith('VirtualBox'): grains['virtual'] = 'VirtualBox' if maker.startswith('Xen'): grains['virtual_subtype'] = '{0} {1}'.format(maker, product) grains['virtual'] = 'xen' if maker.startswith('Microsoft') and product.startswith('Virtual'): grains['virtual'] = 'VirtualPC' if maker.startswith('OpenStack'): grains['virtual'] = 'OpenStack' if maker.startswith('Bochs'): grains['virtual'] = 'kvm' if sysctl: hv_vendor = __salt__['cmd.run']('{0} hw.hv_vendor'.format(sysctl)) model = __salt__['cmd.run']('{0} hw.model'.format(sysctl)) jail = __salt__['cmd.run']( '{0} -n security.jail.jailed'.format(sysctl) ) if 'bhyve' in hv_vendor: grains['virtual'] = 'bhyve' if jail == '1': grains['virtual_subtype'] = 'jail' if 'QEMU Virtual CPU' in model: grains['virtual'] = 'kvm' elif osdata['kernel'] == 'OpenBSD': if 'manufacturer' in osdata: if osdata['manufacturer'] in ['QEMU', 'Red Hat', 'Joyent']: grains['virtual'] = 'kvm' if osdata['manufacturer'] == 'OpenBSD': grains['virtual'] = 'vmm' elif osdata['kernel'] == 'SunOS': if grains['virtual'] == 'LDOM': roles = [] for role in ('control', 'io', 'root', 'service'): subtype_cmd = '{0} -c current get -H -o value {1}-role'.format(cmd, role) ret = __salt__['cmd.run_all']('{0}'.format(subtype_cmd)) if ret['stdout'] == 'true': roles.append(role) if roles: grains['virtual_subtype'] = roles else: # Check if it's a "regular" zone. (i.e. Solaris 10/11 zone) zonename = salt.utils.path.which('zonename') if zonename: zone = __salt__['cmd.run']('{0}'.format(zonename)) if zone != 'global': grains['virtual'] = 'zone' # Check if it's a branded zone (i.e. Solaris 8/9 zone) if isdir('/.SUNWnative'): grains['virtual'] = 'zone' elif osdata['kernel'] == 'NetBSD': if sysctl: if 'QEMU Virtual CPU' in __salt__['cmd.run']( '{0} -n machdep.cpu_brand'.format(sysctl)): grains['virtual'] = 'kvm' elif 'invalid' not in __salt__['cmd.run']( '{0} -n machdep.xen.suspend'.format(sysctl)): grains['virtual'] = 'Xen PV DomU' elif 'VMware' in __salt__['cmd.run']( '{0} -n machdep.dmi.system-vendor'.format(sysctl)): grains['virtual'] = 'VMware' # NetBSD has Xen dom0 support elif __salt__['cmd.run']( '{0} -n machdep.idle-mechanism'.format(sysctl)) == 'xen': if os.path.isfile('/var/run/xenconsoled.pid'): grains['virtual_subtype'] = 'Xen Dom0' for command in failed_commands: log.info( "Although '%s' was found in path, the current user " 'cannot execute it. Grains output might not be ' 'accurate.', command ) return grains def _virtual_hv(osdata): ''' Returns detailed hypervisor information from sysfs Currently this seems to be used only by Xen ''' grains = {} # Bail early if we're not running on Xen try: if 'xen' not in osdata['virtual']: return grains except KeyError: return grains # Try to get the exact hypervisor version from sysfs try: version = {} for fn in ('major', 'minor', 'extra'): with salt.utils.files.fopen('/sys/hypervisor/version/{}'.format(fn), 'r') as fhr: version[fn] = salt.utils.stringutils.to_unicode(fhr.read().strip()) grains['virtual_hv_version'] = '{}.{}{}'.format(version['major'], version['minor'], version['extra']) grains['virtual_hv_version_info'] = [version['major'], version['minor'], version['extra']] except (IOError, OSError, KeyError): pass # Try to read and decode the supported feature set of the hypervisor # Based on https://github.com/brendangregg/Misc/blob/master/xen/xen-features.py # Table data from include/xen/interface/features.h xen_feature_table = {0: 'writable_page_tables', 1: 'writable_descriptor_tables', 2: 'auto_translated_physmap', 3: 'supervisor_mode_kernel', 4: 'pae_pgdir_above_4gb', 5: 'mmu_pt_update_preserve_ad', 7: 'gnttab_map_avail_bits', 8: 'hvm_callback_vector', 9: 'hvm_safe_pvclock', 10: 'hvm_pirqs', 11: 'dom0', 12: 'grant_map_identity', 13: 'memory_op_vnode_supported', 14: 'ARM_SMCCC_supported'} try: with salt.utils.files.fopen('/sys/hypervisor/properties/features', 'r') as fhr: features = salt.utils.stringutils.to_unicode(fhr.read().strip()) enabled_features = [] for bit, feat in six.iteritems(xen_feature_table): if int(features, 16) & (1 << bit): enabled_features.append(feat) grains['virtual_hv_features'] = features grains['virtual_hv_features_list'] = enabled_features except (IOError, OSError, KeyError): pass return grains def _ps(osdata): ''' Return the ps grain ''' grains = {} bsd_choices = ('FreeBSD', 'NetBSD', 'OpenBSD', 'MacOS') if osdata['os'] in bsd_choices: grains['ps'] = 'ps auxwww' elif osdata['os_family'] == 'Solaris': grains['ps'] = '/usr/ucb/ps auxwww' elif osdata['os'] == 'Windows': grains['ps'] = 'tasklist.exe' elif osdata.get('virtual', '') == 'openvzhn': grains['ps'] = ( 'ps -fH -p $(grep -l \"^envID:[[:space:]]*0\\$\" ' '/proc/[0-9]*/status | sed -e \"s=/proc/\\([0-9]*\\)/.*=\\1=\") ' '| awk \'{ $7=\"\"; print }\'' ) elif osdata['os_family'] == 'AIX': grains['ps'] = '/usr/bin/ps auxww' elif osdata['os_family'] == 'NILinuxRT': grains['ps'] = 'ps -o user,pid,ppid,tty,time,comm' else: grains['ps'] = 'ps -efHww' return grains def _clean_value(key, val): ''' Clean out well-known bogus values. If it isn't clean (for example has value 'None'), return None. Otherwise, return the original value. NOTE: This logic also exists in the smbios module. This function is for use when not using smbios to retrieve the value. ''' if (val is None or not val or re.match('none', val, flags=re.IGNORECASE)): return None elif 'uuid' in key: # Try each version (1-5) of RFC4122 to check if it's actually a UUID for uuidver in range(1, 5): try: uuid.UUID(val, version=uuidver) return val except ValueError: continue log.trace('HW %s value %s is an invalid UUID', key, val.replace('\n', ' ')) return None elif re.search('serial|part|version', key): # 'To be filled by O.E.M. # 'Not applicable' etc. # 'Not specified' etc. # 0000000, 1234567 etc. # begone! if (re.match(r'^[0]+$', val) or re.match(r'[0]?1234567[8]?[9]?[0]?', val) or re.search(r'sernum|part[_-]?number|specified|filled|applicable', val, flags=re.IGNORECASE)): return None elif re.search('asset|manufacturer', key): # AssetTag0. Manufacturer04. Begone. if re.search(r'manufacturer|to be filled|available|asset|^no(ne|t)', val, flags=re.IGNORECASE): return None else: # map unspecified, undefined, unknown & whatever to None if (re.search(r'to be filled', val, flags=re.IGNORECASE) or re.search(r'un(known|specified)|no(t|ne)? (asset|provided|defined|available|present|specified)', val, flags=re.IGNORECASE)): return None return val def _windows_platform_data(): ''' Use the platform module for as much as we can. ''' # Provides: # kernelrelease # kernelversion # osversion # osrelease # osservicepack # osmanufacturer # manufacturer # productname # biosversion # serialnumber # osfullname # timezone # windowsdomain # windowsdomaintype # motherboard.productname # motherboard.serialnumber # virtual if not HAS_WMI: return {} with salt.utils.winapi.Com(): wmi_c = wmi.WMI() # http://msdn.microsoft.com/en-us/library/windows/desktop/aa394102%28v=vs.85%29.aspx systeminfo = wmi_c.Win32_ComputerSystem()[0] # https://msdn.microsoft.com/en-us/library/aa394239(v=vs.85).aspx osinfo = wmi_c.Win32_OperatingSystem()[0] # http://msdn.microsoft.com/en-us/library/windows/desktop/aa394077(v=vs.85).aspx biosinfo = wmi_c.Win32_BIOS()[0] # http://msdn.microsoft.com/en-us/library/windows/desktop/aa394498(v=vs.85).aspx timeinfo = wmi_c.Win32_TimeZone()[0] # http://msdn.microsoft.com/en-us/library/windows/desktop/aa394072(v=vs.85).aspx motherboard = {'product': None, 'serial': None} try: motherboardinfo = wmi_c.Win32_BaseBoard()[0] motherboard['product'] = motherboardinfo.Product motherboard['serial'] = motherboardinfo.SerialNumber except IndexError: log.debug('Motherboard info not available on this system') os_release = platform.release() kernel_version = platform.version() info = salt.utils.win_osinfo.get_os_version_info() net_info = salt.utils.win_osinfo.get_join_info() service_pack = None if info['ServicePackMajor'] > 0: service_pack = ''.join(['SP', six.text_type(info['ServicePackMajor'])]) # This creates the osrelease grain based on the Windows Operating # System Product Name. As long as Microsoft maintains a similar format # this should be future proof version = 'Unknown' release = '' if 'Server' in osinfo.Caption: for item in osinfo.Caption.split(' '): # If it's all digits, then it's version if re.match(r'\d+', item): version = item # If it starts with R and then numbers, it's the release # ie: R2 if re.match(r'^R\d+$', item): release = item os_release = '{0}Server{1}'.format(version, release) else: for item in osinfo.Caption.split(' '): # If it's a number, decimal number, Thin or Vista, then it's the # version if re.match(r'^(\d+(\.\d+)?)|Thin|Vista$', item): version = item os_release = version grains = { 'kernelrelease': _clean_value('kernelrelease', osinfo.Version), 'kernelversion': _clean_value('kernelversion', kernel_version), 'osversion': _clean_value('osversion', osinfo.Version), 'osrelease': _clean_value('osrelease', os_release), 'osservicepack': _clean_value('osservicepack', service_pack), 'osmanufacturer': _clean_value('osmanufacturer', osinfo.Manufacturer), 'manufacturer': _clean_value('manufacturer', systeminfo.Manufacturer), 'productname': _clean_value('productname', systeminfo.Model), # bios name had a bunch of whitespace appended to it in my testing # 'PhoenixBIOS 4.0 Release 6.0 ' 'biosversion': _clean_value('biosversion', biosinfo.Name.strip()), 'serialnumber': _clean_value('serialnumber', biosinfo.SerialNumber), 'osfullname': _clean_value('osfullname', osinfo.Caption), 'timezone': _clean_value('timezone', timeinfo.Description), 'windowsdomain': _clean_value('windowsdomain', net_info['Domain']), 'windowsdomaintype': _clean_value('windowsdomaintype', net_info['DomainType']), 'motherboard': { 'productname': _clean_value('motherboard.productname', motherboard['product']), 'serialnumber': _clean_value('motherboard.serialnumber', motherboard['serial']), } } # test for virtualized environments # I only had VMware available so the rest are unvalidated if 'VRTUAL' in biosinfo.Version: # (not a typo) grains['virtual'] = 'HyperV' elif 'A M I' in biosinfo.Version: grains['virtual'] = 'VirtualPC' elif 'VMware' in systeminfo.Model: grains['virtual'] = 'VMware' elif 'VirtualBox' in systeminfo.Model: grains['virtual'] = 'VirtualBox' elif 'Xen' in biosinfo.Version: grains['virtual'] = 'Xen' if 'HVM domU' in systeminfo.Model: grains['virtual_subtype'] = 'HVM domU' elif 'OpenStack' in systeminfo.Model: grains['virtual'] = 'OpenStack' return grains def _osx_platform_data(): ''' Additional data for macOS systems Returns: A dictionary containing values for the following: - model_name - boot_rom_version - smc_version - system_serialnumber ''' cmd = 'system_profiler SPHardwareDataType' hardware = __salt__['cmd.run'](cmd) grains = {} for line in hardware.splitlines(): field_name, _, field_val = line.partition(': ') if field_name.strip() == "Model Name": key = 'model_name' grains[key] = _clean_value(key, field_val) if field_name.strip() == "Boot ROM Version": key = 'boot_rom_version' grains[key] = _clean_value(key, field_val) if field_name.strip() == "SMC Version (system)": key = 'smc_version' grains[key] = _clean_value(key, field_val) if field_name.strip() == "Serial Number (system)": key = 'system_serialnumber' grains[key] = _clean_value(key, field_val) return grains def id_(): ''' Return the id ''' return {'id': __opts__.get('id', '')} _REPLACE_LINUX_RE = re.compile(r'\W(?:gnu/)?linux', re.IGNORECASE) # This maps (at most) the first ten characters (no spaces, lowercased) of # 'osfullname' to the 'os' grain that Salt traditionally uses. # Please see os_data() and _supported_dists. # If your system is not detecting properly it likely needs an entry here. _OS_NAME_MAP = { 'redhatente': 'RedHat', 'gentoobase': 'Gentoo', 'archarm': 'Arch ARM', 'arch': 'Arch', 'debian': 'Debian', 'raspbian': 'Raspbian', 'fedoraremi': 'Fedora', 'chapeau': 'Chapeau', 'korora': 'Korora', 'amazonami': 'Amazon', 'alt': 'ALT', 'enterprise': 'OEL', 'oracleserv': 'OEL', 'cloudserve': 'CloudLinux', 'cloudlinux': 'CloudLinux', 'pidora': 'Fedora', 'scientific': 'ScientificLinux', 'synology': 'Synology', 'nilrt': 'NILinuxRT', 'poky': 'Poky', 'manjaro': 'Manjaro', 'manjarolin': 'Manjaro', 'univention': 'Univention', 'antergos': 'Antergos', 'sles': 'SUSE', 'void': 'Void', 'slesexpand': 'RES', 'linuxmint': 'Mint', 'neon': 'KDE neon', } # Map the 'os' grain to the 'os_family' grain # These should always be capitalized entries as the lookup comes # post-_OS_NAME_MAP. If your system is having trouble with detection, please # make sure that the 'os' grain is capitalized and working correctly first. _OS_FAMILY_MAP = { 'Ubuntu': 'Debian', 'Fedora': 'RedHat', 'Chapeau': 'RedHat', 'Korora': 'RedHat', 'FedBerry': 'RedHat', 'CentOS': 'RedHat', 'GoOSe': 'RedHat', 'Scientific': 'RedHat', 'Amazon': 'RedHat', 'CloudLinux': 'RedHat', 'OVS': 'RedHat', 'OEL': 'RedHat', 'XCP': 'RedHat', 'XCP-ng': 'RedHat', 'XenServer': 'RedHat', 'RES': 'RedHat', 'Sangoma': 'RedHat', 'Mandrake': 'Mandriva', 'ESXi': 'VMware', 'Mint': 'Debian', 'VMwareESX': 'VMware', 'Bluewhite64': 'Bluewhite', 'Slamd64': 'Slackware', 'SLES': 'Suse', 'SUSE Enterprise Server': 'Suse', 'SUSE Enterprise Server': 'Suse', 'SLED': 'Suse', 'openSUSE': 'Suse', 'SUSE': 'Suse', 'openSUSE Leap': 'Suse', 'openSUSE Tumbleweed': 'Suse', 'SLES_SAP': 'Suse', 'Solaris': 'Solaris', 'SmartOS': 'Solaris', 'OmniOS': 'Solaris', 'OpenIndiana Development': 'Solaris', 'OpenIndiana': 'Solaris', 'OpenSolaris Development': 'Solaris', 'OpenSolaris': 'Solaris', 'Oracle Solaris': 'Solaris', 'Arch ARM': 'Arch', 'Manjaro': 'Arch', 'Antergos': 'Arch', 'ALT': 'RedHat', 'Trisquel': 'Debian', 'GCEL': 'Debian', 'Linaro': 'Debian', 'elementary OS': 'Debian', 'elementary': 'Debian', 'Univention': 'Debian', 'ScientificLinux': 'RedHat', 'Raspbian': 'Debian', 'Devuan': 'Debian', 'antiX': 'Debian', 'Kali': 'Debian', 'neon': 'Debian', 'Cumulus': 'Debian', 'Deepin': 'Debian', 'NILinuxRT': 'NILinuxRT', 'KDE neon': 'Debian', 'Void': 'Void', 'IDMS': 'Debian', 'Funtoo': 'Gentoo', 'AIX': 'AIX', 'TurnKey': 'Debian', } # Matches any possible format: # DISTRIB_ID="Ubuntu" # DISTRIB_ID='Mageia' # DISTRIB_ID=Fedora # DISTRIB_RELEASE='10.10' # DISTRIB_CODENAME='squeeze' # DISTRIB_DESCRIPTION='Ubuntu 10.10' _LSB_REGEX = re.compile(( '^(DISTRIB_(?:ID|RELEASE|CODENAME|DESCRIPTION))=(?:\'|")?' '([\\w\\s\\.\\-_]+)(?:\'|")?' )) def _linux_bin_exists(binary): ''' Does a binary exist in linux (depends on which, type, or whereis) ''' for search_cmd in ('which', 'type -ap'): try: return __salt__['cmd.retcode']( '{0} {1}'.format(search_cmd, binary) ) == 0 except salt.exceptions.CommandExecutionError: pass try: return len(__salt__['cmd.run_all']( 'whereis -b {0}'.format(binary) )['stdout'].split()) > 1 except salt.exceptions.CommandExecutionError: return False def _get_interfaces(): ''' Provide a dict of the connected interfaces and their ip addresses ''' global _INTERFACES if not _INTERFACES: _INTERFACES = salt.utils.network.interfaces() return _INTERFACES def _parse_lsb_release(): ret = {} try: log.trace('Attempting to parse /etc/lsb-release') with salt.utils.files.fopen('/etc/lsb-release') as ifile: for line in ifile: try: key, value = _LSB_REGEX.match(line.rstrip('\n')).groups()[:2] except AttributeError: pass else: # Adds lsb_distrib_{id,release,codename,description} ret['lsb_{0}'.format(key.lower())] = value.rstrip() except (IOError, OSError) as exc: log.trace('Failed to parse /etc/lsb-release: %s', exc) return ret def _parse_os_release(*os_release_files): ''' Parse os-release and return a parameter dictionary See http://www.freedesktop.org/software/systemd/man/os-release.html for specification of the file format. ''' ret = {} for filename in os_release_files: try: with salt.utils.files.fopen(filename) as ifile: regex = re.compile('^([\\w]+)=(?:\'|")?(.*?)(?:\'|")?$') for line in ifile: match = regex.match(line.strip()) if match: # Shell special characters ("$", quotes, backslash, # backtick) are escaped with backslashes ret[match.group(1)] = re.sub( r'\\([$"\'\\`])', r'\1', match.group(2) ) break except (IOError, OSError): pass return ret def _parse_cpe_name(cpe): ''' Parse CPE_NAME data from the os-release Info: https://csrc.nist.gov/projects/security-content-automation-protocol/scap-specifications/cpe :param cpe: :return: ''' part = { 'o': 'operating system', 'h': 'hardware', 'a': 'application', } ret = {} cpe = (cpe or '').split(':') if len(cpe) > 4 and cpe[0] == 'cpe': if cpe[1].startswith('/'): # WFN to URI ret['vendor'], ret['product'], ret['version'] = cpe[2:5] ret['phase'] = cpe[5] if len(cpe) > 5 else None ret['part'] = part.get(cpe[1][1:]) elif len(cpe) == 13 and cpe[1] == '2.3': # WFN to a string ret['vendor'], ret['product'], ret['version'], ret['phase'] = [x if x != '*' else None for x in cpe[3:7]] ret['part'] = part.get(cpe[2]) return ret def os_data(): ''' Return grains pertaining to the operating system ''' grains = { 'num_gpus': 0, 'gpus': [], } # Windows Server 2008 64-bit # ('Windows', 'MINIONNAME', '2008ServerR2', '6.1.7601', 'AMD64', # 'Intel64 Fam ily 6 Model 23 Stepping 6, GenuineIntel') # Ubuntu 10.04 # ('Linux', 'MINIONNAME', '2.6.32-38-server', # '#83-Ubuntu SMP Wed Jan 4 11:26:59 UTC 2012', 'x86_64', '') # pylint: disable=unpacking-non-sequence (grains['kernel'], grains['nodename'], grains['kernelrelease'], grains['kernelversion'], grains['cpuarch'], _) = platform.uname() # pylint: enable=unpacking-non-sequence if salt.utils.platform.is_proxy(): grains['kernel'] = 'proxy' grains['kernelrelease'] = 'proxy' grains['kernelversion'] = 'proxy' grains['osrelease'] = 'proxy' grains['os'] = 'proxy' grains['os_family'] = 'proxy' grains['osfullname'] = 'proxy' elif salt.utils.platform.is_windows(): grains['os'] = 'Windows' grains['os_family'] = 'Windows' grains.update(_memdata(grains)) grains.update(_windows_platform_data()) grains.update(_windows_cpudata()) grains.update(_windows_virtual(grains)) grains.update(_ps(grains)) if 'Server' in grains['osrelease']: osrelease_info = grains['osrelease'].split('Server', 1) osrelease_info[1] = osrelease_info[1].lstrip('R') else: osrelease_info = grains['osrelease'].split('.') for idx, value in enumerate(osrelease_info): if not value.isdigit(): continue osrelease_info[idx] = int(value) grains['osrelease_info'] = tuple(osrelease_info) grains['osfinger'] = '{os}-{ver}'.format( os=grains['os'], ver=grains['osrelease']) grains['init'] = 'Windows' return grains elif salt.utils.platform.is_linux(): # Add SELinux grain, if you have it if _linux_bin_exists('selinuxenabled'): log.trace('Adding selinux grains') grains['selinux'] = {} grains['selinux']['enabled'] = __salt__['cmd.retcode']( 'selinuxenabled' ) == 0 if _linux_bin_exists('getenforce'): grains['selinux']['enforced'] = __salt__['cmd.run']( 'getenforce' ).strip() # Add systemd grain, if you have it if _linux_bin_exists('systemctl') and _linux_bin_exists('localectl'): log.trace('Adding systemd grains') grains['systemd'] = {} systemd_info = __salt__['cmd.run']( 'systemctl --version' ).splitlines() grains['systemd']['version'] = systemd_info[0].split()[1] grains['systemd']['features'] = systemd_info[1] # Add init grain grains['init'] = 'unknown' log.trace('Adding init grain') try: os.stat('/run/systemd/system') grains['init'] = 'systemd' except (OSError, IOError): try: with salt.utils.files.fopen('/proc/1/cmdline') as fhr: init_cmdline = fhr.read().replace('\x00', ' ').split() except (IOError, OSError): pass else: try: init_bin = salt.utils.path.which(init_cmdline[0]) except IndexError: # Emtpy init_cmdline init_bin = None log.warning('Unable to fetch data from /proc/1/cmdline') if init_bin is not None and init_bin.endswith('bin/init'): supported_inits = (b'upstart', b'sysvinit', b'systemd') edge_len = max(len(x) for x in supported_inits) - 1 try: buf_size = __opts__['file_buffer_size'] except KeyError: # Default to the value of file_buffer_size for the minion buf_size = 262144 try: with salt.utils.files.fopen(init_bin, 'rb') as fp_: edge = b'' buf = fp_.read(buf_size).lower() while buf: buf = edge + buf for item in supported_inits: if item in buf: if six.PY3: item = item.decode('utf-8') grains['init'] = item buf = b'' break edge = buf[-edge_len:] buf = fp_.read(buf_size).lower() except (IOError, OSError) as exc: log.error( 'Unable to read from init_bin (%s): %s', init_bin, exc ) elif salt.utils.path.which('supervisord') in init_cmdline: grains['init'] = 'supervisord' elif salt.utils.path.which('dumb-init') in init_cmdline: # https://github.com/Yelp/dumb-init grains['init'] = 'dumb-init' elif salt.utils.path.which('tini') in init_cmdline: # https://github.com/krallin/tini grains['init'] = 'tini' elif init_cmdline == ['runit']: grains['init'] = 'runit' elif '/sbin/my_init' in init_cmdline: # Phusion Base docker container use runit for srv mgmt, but # my_init as pid1 grains['init'] = 'runit' else: log.debug( 'Could not determine init system from command line: (%s)', ' '.join(init_cmdline) ) # Add lsb grains on any distro with lsb-release. Note that this import # can fail on systems with lsb-release installed if the system package # does not install the python package for the python interpreter used by # Salt (i.e. python2 or python3) try: log.trace('Getting lsb_release distro information') import lsb_release # pylint: disable=import-error release = lsb_release.get_distro_information() for key, value in six.iteritems(release): key = key.lower() lsb_param = 'lsb_{0}{1}'.format( '' if key.startswith('distrib_') else 'distrib_', key ) grains[lsb_param] = value # Catch a NameError to workaround possible breakage in lsb_release # See https://github.com/saltstack/salt/issues/37867 except (ImportError, NameError): # if the python library isn't available, try to parse # /etc/lsb-release using regex log.trace('lsb_release python bindings not available') grains.update(_parse_lsb_release()) if grains.get('lsb_distrib_description', '').lower().startswith('antergos'): # Antergos incorrectly configures their /etc/lsb-release, # setting the DISTRIB_ID to "Arch". This causes the "os" grain # to be incorrectly set to "Arch". grains['osfullname'] = 'Antergos Linux' elif 'lsb_distrib_id' not in grains: log.trace( 'Failed to get lsb_distrib_id, trying to parse os-release' ) os_release = _parse_os_release('/etc/os-release', '/usr/lib/os-release') if os_release: if 'NAME' in os_release: grains['lsb_distrib_id'] = os_release['NAME'].strip() if 'VERSION_ID' in os_release: grains['lsb_distrib_release'] = os_release['VERSION_ID'] if 'VERSION_CODENAME' in os_release: grains['lsb_distrib_codename'] = os_release['VERSION_CODENAME'] elif 'PRETTY_NAME' in os_release: codename = os_release['PRETTY_NAME'] # https://github.com/saltstack/salt/issues/44108 if os_release['ID'] == 'debian': codename_match = re.search(r'\((\w+)\)$', codename) if codename_match: codename = codename_match.group(1) grains['lsb_distrib_codename'] = codename if 'CPE_NAME' in os_release: cpe = _parse_cpe_name(os_release['CPE_NAME']) if not cpe: log.error('Broken CPE_NAME format in /etc/os-release!') elif cpe.get('vendor', '').lower() in ['suse', 'opensuse']: grains['os'] = "SUSE" # openSUSE `osfullname` grain normalization if os_release.get("NAME") == "openSUSE Leap": grains['osfullname'] = "Leap" elif os_release.get("VERSION") == "Tumbleweed": grains['osfullname'] = os_release["VERSION"] # Override VERSION_ID, if CPE_NAME around if cpe.get('version') and cpe.get('vendor') == 'opensuse': # Keep VERSION_ID for SLES grains['lsb_distrib_release'] = cpe['version'] elif os.path.isfile('/etc/SuSE-release'): log.trace('Parsing distrib info from /etc/SuSE-release') grains['lsb_distrib_id'] = 'SUSE' version = '' patch = '' with salt.utils.files.fopen('/etc/SuSE-release') as fhr: for line in fhr: if 'enterprise' in line.lower(): grains['lsb_distrib_id'] = 'SLES' grains['lsb_distrib_codename'] = re.sub(r'\(.+\)', '', line).strip() elif 'version' in line.lower(): version = re.sub(r'[^0-9]', '', line) elif 'patchlevel' in line.lower(): patch = re.sub(r'[^0-9]', '', line) grains['lsb_distrib_release'] = version if patch: grains['lsb_distrib_release'] += '.' + patch patchstr = 'SP' + patch if grains['lsb_distrib_codename'] and patchstr not in grains['lsb_distrib_codename']: grains['lsb_distrib_codename'] += ' ' + patchstr if not grains.get('lsb_distrib_codename'): grains['lsb_distrib_codename'] = 'n.a' elif os.path.isfile('/etc/altlinux-release'): log.trace('Parsing distrib info from /etc/altlinux-release') # ALT Linux grains['lsb_distrib_id'] = 'altlinux' with salt.utils.files.fopen('/etc/altlinux-release') as ifile: # This file is symlinked to from: # /etc/fedora-release # /etc/redhat-release # /etc/system-release for line in ifile: # ALT Linux Sisyphus (unstable) comps = line.split() if comps[0] == 'ALT': grains['lsb_distrib_release'] = comps[2] grains['lsb_distrib_codename'] = \ comps[3].replace('(', '').replace(')', '') elif os.path.isfile('/etc/centos-release'): log.trace('Parsing distrib info from /etc/centos-release') # Maybe CentOS Linux; could also be SUSE Expanded Support. # SUSE ES has both, centos-release and redhat-release. if os.path.isfile('/etc/redhat-release'): with salt.utils.files.fopen('/etc/redhat-release') as ifile: for line in ifile: if "red hat enterprise linux server" in line.lower(): # This is a SUSE Expanded Support Rhel installation grains['lsb_distrib_id'] = 'RedHat' break grains.setdefault('lsb_distrib_id', 'CentOS') with salt.utils.files.fopen('/etc/centos-release') as ifile: for line in ifile: # Need to pull out the version and codename # in the case of custom content in /etc/centos-release find_release = re.compile(r'\d+\.\d+') find_codename = re.compile(r'(?<=\()(.*?)(?=\))') release = find_release.search(line) codename = find_codename.search(line) if release is not None: grains['lsb_distrib_release'] = release.group() if codename is not None: grains['lsb_distrib_codename'] = codename.group() elif os.path.isfile('/etc.defaults/VERSION') \ and os.path.isfile('/etc.defaults/synoinfo.conf'): grains['osfullname'] = 'Synology' log.trace( 'Parsing Synology distrib info from /etc/.defaults/VERSION' ) with salt.utils.files.fopen('/etc.defaults/VERSION', 'r') as fp_: synoinfo = {} for line in fp_: try: key, val = line.rstrip('\n').split('=') except ValueError: continue if key in ('majorversion', 'minorversion', 'buildnumber'): synoinfo[key] = val.strip('"') if len(synoinfo) != 3: log.warning( 'Unable to determine Synology version info. ' 'Please report this, as it is likely a bug.' ) else: grains['osrelease'] = ( '{majorversion}.{minorversion}-{buildnumber}' .format(**synoinfo) ) # Use the already intelligent platform module to get distro info # (though apparently it's not intelligent enough to strip quotes) log.trace( 'Getting OS name, release, and codename from ' 'distro.linux_distribution()' ) (osname, osrelease, oscodename) = \ [x.strip('"').strip("'") for x in linux_distribution(supported_dists=_supported_dists)] # Try to assign these three names based on the lsb info, they tend to # be more accurate than what python gets from /etc/DISTRO-release. # It's worth noting that Ubuntu has patched their Python distribution # so that linux_distribution() does the /etc/lsb-release parsing, but # we do it anyway here for the sake for full portability. if 'osfullname' not in grains: # If NI Linux RT distribution, set the grains['osfullname'] to 'nilrt' if grains.get('lsb_distrib_id', '').lower().startswith('nilrt'): grains['osfullname'] = 'nilrt' else: grains['osfullname'] = grains.get('lsb_distrib_id', osname).strip() if 'osrelease' not in grains: # NOTE: This is a workaround for CentOS 7 os-release bug # https://bugs.centos.org/view.php?id=8359 # /etc/os-release contains no minor distro release number so we fall back to parse # /etc/centos-release file instead. # Commit introducing this comment should be reverted after the upstream bug is released. if 'CentOS Linux 7' in grains.get('lsb_distrib_codename', ''): grains.pop('lsb_distrib_release', None) grains['osrelease'] = grains.get('lsb_distrib_release', osrelease).strip() grains['oscodename'] = grains.get('lsb_distrib_codename', '').strip() or oscodename if 'Red Hat' in grains['oscodename']: grains['oscodename'] = oscodename distroname = _REPLACE_LINUX_RE.sub('', grains['osfullname']).strip() # return the first ten characters with no spaces, lowercased shortname = distroname.replace(' ', '').lower()[:10] # this maps the long names from the /etc/DISTRO-release files to the # traditional short names that Salt has used. if 'os' not in grains: grains['os'] = _OS_NAME_MAP.get(shortname, distroname) grains.update(_linux_cpudata()) grains.update(_linux_gpu_data()) elif grains['kernel'] == 'SunOS': if salt.utils.platform.is_smartos(): # See https://github.com/joyent/smartos-live/issues/224 if HAS_UNAME: uname_v = os.uname()[3] # format: joyent_20161101T004406Z else: uname_v = os.name uname_v = uname_v[uname_v.index('_')+1:] grains['os'] = grains['osfullname'] = 'SmartOS' # store a parsed version of YYYY.MM.DD as osrelease grains['osrelease'] = ".".join([ uname_v.split('T')[0][0:4], uname_v.split('T')[0][4:6], uname_v.split('T')[0][6:8], ]) # store a untouched copy of the timestamp in osrelease_stamp grains['osrelease_stamp'] = uname_v elif os.path.isfile('/etc/release'): with salt.utils.files.fopen('/etc/release', 'r') as fp_: rel_data = fp_.read() try: release_re = re.compile( r'((?:Open|Oracle )?Solaris|OpenIndiana|OmniOS) (Development)?' r'\s*(\d+\.?\d*|v\d+)\s?[A-Z]*\s?(r\d+|\d+\/\d+|oi_\S+|snv_\S+)?' ) osname, development, osmajorrelease, osminorrelease = release_re.search(rel_data).groups() except AttributeError: # Set a blank osrelease grain and fallback to 'Solaris' # as the 'os' grain. grains['os'] = grains['osfullname'] = 'Solaris' grains['osrelease'] = '' else: if development is not None: osname = ' '.join((osname, development)) if HAS_UNAME: uname_v = os.uname()[3] else: uname_v = os.name grains['os'] = grains['osfullname'] = osname if osname in ['Oracle Solaris'] and uname_v.startswith(osmajorrelease): # Oracla Solars 11 and up have minor version in uname grains['osrelease'] = uname_v elif osname in ['OmniOS']: # OmniOS osrelease = [] osrelease.append(osmajorrelease[1:]) osrelease.append(osminorrelease[1:]) grains['osrelease'] = ".".join(osrelease) grains['osrelease_stamp'] = uname_v else: # Sun Solaris 10 and earlier/comparable osrelease = [] osrelease.append(osmajorrelease) if osminorrelease: osrelease.append(osminorrelease) grains['osrelease'] = ".".join(osrelease) grains['osrelease_stamp'] = uname_v grains.update(_sunos_cpudata()) elif grains['kernel'] == 'VMkernel': grains['os'] = 'ESXi' elif grains['kernel'] == 'Darwin': osrelease = __salt__['cmd.run']('sw_vers -productVersion') osname = __salt__['cmd.run']('sw_vers -productName') osbuild = __salt__['cmd.run']('sw_vers -buildVersion') grains['os'] = 'MacOS' grains['os_family'] = 'MacOS' grains['osfullname'] = "{0} {1}".format(osname, osrelease) grains['osrelease'] = osrelease grains['osbuild'] = osbuild grains['init'] = 'launchd' grains.update(_bsd_cpudata(grains)) grains.update(_osx_gpudata()) grains.update(_osx_platform_data()) elif grains['kernel'] == 'AIX': osrelease = __salt__['cmd.run']('oslevel') osrelease_techlevel = __salt__['cmd.run']('oslevel -r') osname = __salt__['cmd.run']('uname') grains['os'] = 'AIX' grains['osfullname'] = osname grains['osrelease'] = osrelease grains['osrelease_techlevel'] = osrelease_techlevel grains.update(_aix_cpudata()) else: grains['os'] = grains['kernel'] if grains['kernel'] == 'FreeBSD': try: grains['osrelease'] = __salt__['cmd.run']('freebsd-version -u').split('-')[0] except salt.exceptions.CommandExecutionError: # freebsd-version was introduced in 10.0. # derive osrelease from kernelversion prior to that grains['osrelease'] = grains['kernelrelease'].split('-')[0] grains.update(_bsd_cpudata(grains)) if grains['kernel'] in ('OpenBSD', 'NetBSD'): grains.update(_bsd_cpudata(grains)) grains['osrelease'] = grains['kernelrelease'].split('-')[0] if grains['kernel'] == 'NetBSD': grains.update(_netbsd_gpu_data()) if not grains['os']: grains['os'] = 'Unknown {0}'.format(grains['kernel']) grains['os_family'] = 'Unknown' else: # this assigns family names based on the os name # family defaults to the os name if not found grains['os_family'] = _OS_FAMILY_MAP.get(grains['os'], grains['os']) # Build the osarch grain. This grain will be used for platform-specific # considerations such as package management. Fall back to the CPU # architecture. if grains.get('os_family') == 'Debian': osarch = __salt__['cmd.run']('dpkg --print-architecture').strip() elif grains.get('os_family') in ['RedHat', 'Suse']: osarch = salt.utils.pkg.rpm.get_osarch() elif grains.get('os_family') in ('NILinuxRT', 'Poky'): archinfo = {} for line in __salt__['cmd.run']('opkg print-architecture').splitlines(): if line.startswith('arch'): _, arch, priority = line.split() archinfo[arch.strip()] = int(priority.strip()) # Return osarch in priority order (higher to lower) osarch = sorted(archinfo, key=archinfo.get, reverse=True) else: osarch = grains['cpuarch'] grains['osarch'] = osarch grains.update(_memdata(grains)) # Get the hardware and bios data grains.update(_hw_data(grains)) # Load the virtual machine info grains.update(_virtual(grains)) grains.update(_virtual_hv(grains)) grains.update(_ps(grains)) if grains.get('osrelease', ''): osrelease_info = grains['osrelease'].split('.') for idx, value in enumerate(osrelease_info): if not value.isdigit(): continue osrelease_info[idx] = int(value) grains['osrelease_info'] = tuple(osrelease_info) try: grains['osmajorrelease'] = int(grains['osrelease_info'][0]) except (IndexError, TypeError, ValueError): log.debug( 'Unable to derive osmajorrelease from osrelease_info \'%s\'. ' 'The osmajorrelease grain will not be set.', grains['osrelease_info'] ) os_name = grains['os' if grains.get('os') in ( 'Debian', 'FreeBSD', 'OpenBSD', 'NetBSD', 'Mac', 'Raspbian') else 'osfullname'] grains['osfinger'] = '{0}-{1}'.format( os_name, grains['osrelease'] if os_name in ('Ubuntu',) else grains['osrelease_info'][0]) return grains def locale_info(): ''' Provides defaultlanguage defaultencoding ''' grains = {} grains['locale_info'] = {} if salt.utils.platform.is_proxy(): return grains try: ( grains['locale_info']['defaultlanguage'], grains['locale_info']['defaultencoding'] ) = locale.getdefaultlocale() except Exception: # locale.getdefaultlocale can ValueError!! Catch anything else it # might do, per #2205 grains['locale_info']['defaultlanguage'] = 'unknown' grains['locale_info']['defaultencoding'] = 'unknown' grains['locale_info']['detectedencoding'] = __salt_system_encoding__ if _DATEUTIL_TZ: grains['locale_info']['timezone'] = datetime.datetime.now(dateutil.tz.tzlocal()).tzname() return grains def hostname(): ''' Return fqdn, hostname, domainname ''' # This is going to need some work # Provides: # fqdn # host # localhost # domain global __FQDN__ grains = {} if salt.utils.platform.is_proxy(): return grains grains['localhost'] = socket.gethostname() if __FQDN__ is None: __FQDN__ = salt.utils.network.get_fqhostname() # On some distros (notably FreeBSD) if there is no hostname set # salt.utils.network.get_fqhostname() will return None. # In this case we punt and log a message at error level, but force the # hostname and domain to be localhost.localdomain # Otherwise we would stacktrace below if __FQDN__ is None: # still! log.error('Having trouble getting a hostname. Does this machine have its hostname and domain set properly?') __FQDN__ = 'localhost.localdomain' grains['fqdn'] = __FQDN__ (grains['host'], grains['domain']) = grains['fqdn'].partition('.')[::2] return grains def append_domain(): ''' Return append_domain if set ''' grain = {} if salt.utils.platform.is_proxy(): return grain if 'append_domain' in __opts__: grain['append_domain'] = __opts__['append_domain'] return grain def fqdns(): ''' Return all known FQDNs for the system by enumerating all interfaces and then trying to reverse resolve them (excluding 'lo' interface). ''' # Provides: # fqdns grains = {} fqdns = set() addresses = salt.utils.network.ip_addrs(include_loopback=False, interface_data=_get_interfaces()) addresses.extend(salt.utils.network.ip_addrs6(include_loopback=False, interface_data=_get_interfaces())) err_message = 'Exception during resolving address: %s' for ip in addresses: try: name, aliaslist, addresslist = socket.gethostbyaddr(ip) fqdns.update([socket.getfqdn(name)] + [als for als in aliaslist if salt.utils.network.is_fqdn(als)]) except socket.herror as err: if err.errno == 0: # No FQDN for this IP address, so we don't need to know this all the time. log.debug("Unable to resolve address %s: %s", ip, err) else: log.error(err_message, err) except (socket.error, socket.gaierror, socket.timeout) as err: log.error(err_message, err) return {"fqdns": sorted(list(fqdns))} def ip_fqdn(): ''' Return ip address and FQDN grains ''' if salt.utils.platform.is_proxy(): return {} ret = {} ret['ipv4'] = salt.utils.network.ip_addrs(include_loopback=True) ret['ipv6'] = salt.utils.network.ip_addrs6(include_loopback=True) _fqdn = hostname()['fqdn'] for socket_type, ipv_num in ((socket.AF_INET, '4'), (socket.AF_INET6, '6')): key = 'fqdn_ip' + ipv_num if not ret['ipv' + ipv_num]: ret[key] = [] else: try: start_time = datetime.datetime.utcnow() info = socket.getaddrinfo(_fqdn, None, socket_type) ret[key] = list(set(item[4][0] for item in info)) except socket.error: timediff = datetime.datetime.utcnow() - start_time if timediff.seconds > 5 and __opts__['__role'] == 'master': log.warning( 'Unable to find IPv%s record for "%s" causing a %s ' 'second timeout when rendering grains. Set the dns or ' '/etc/hosts for IPv%s to clear this.', ipv_num, _fqdn, timediff, ipv_num ) ret[key] = [] return ret def ip4_interfaces(): ''' Provide a dict of the connected interfaces and their ip4 addresses The addresses will be passed as a list for each interface ''' # Provides: # ip_interfaces if salt.utils.platform.is_proxy(): return {} ret = {} ifaces = _get_interfaces() for face in ifaces: iface_ips = [] for inet in ifaces[face].get('inet', []): if 'address' in inet: iface_ips.append(inet['address']) for secondary in ifaces[face].get('secondary', []): if 'address' in secondary: iface_ips.append(secondary['address']) ret[face] = iface_ips return {'ip4_interfaces': ret} def ip6_interfaces(): ''' Provide a dict of the connected interfaces and their ip6 addresses The addresses will be passed as a list for each interface ''' # Provides: # ip_interfaces if salt.utils.platform.is_proxy(): return {} ret = {} ifaces = _get_interfaces() for face in ifaces: iface_ips = [] for inet in ifaces[face].get('inet6', []): if 'address' in inet: iface_ips.append(inet['address']) for secondary in ifaces[face].get('secondary', []): if 'address' in secondary: iface_ips.append(secondary['address']) ret[face] = iface_ips return {'ip6_interfaces': ret} def hwaddr_interfaces(): ''' Provide a dict of the connected interfaces and their hw addresses (Mac Address) ''' # Provides: # hwaddr_interfaces ret = {} ifaces = _get_interfaces() for face in ifaces: if 'hwaddr' in ifaces[face]: ret[face] = ifaces[face]['hwaddr'] return {'hwaddr_interfaces': ret} def dns(): ''' Parse the resolver configuration file .. versionadded:: 2016.3.0 ''' # Provides: # dns if salt.utils.platform.is_windows() or 'proxyminion' in __opts__: return {} resolv = salt.utils.dns.parse_resolv() for key in ('nameservers', 'ip4_nameservers', 'ip6_nameservers', 'sortlist'): if key in resolv: resolv[key] = [six.text_type(i) for i in resolv[key]] return {'dns': resolv} if resolv else {} def get_machine_id(): ''' Provide the machine-id for machine/virtualization combination ''' # Provides: # machine-id if platform.system() == 'AIX': return _aix_get_machine_id() locations = ['/etc/machine-id', '/var/lib/dbus/machine-id'] existing_locations = [loc for loc in locations if os.path.exists(loc)] if not existing_locations: return {} else: with salt.utils.files.fopen(existing_locations[0]) as machineid: return {'machine_id': machineid.read().strip()} def cwd(): ''' Current working directory ''' return {'cwd': os.getcwd()} def path(): ''' Return the path ''' # Provides: # path return {'path': os.environ.get('PATH', '').strip()} def pythonversion(): ''' Return the Python version ''' # Provides: # pythonversion return {'pythonversion': list(sys.version_info)} def pythonpath(): ''' Return the Python path ''' # Provides: # pythonpath return {'pythonpath': sys.path} def pythonexecutable(): ''' Return the python executable in use ''' # Provides: # pythonexecutable return {'pythonexecutable': sys.executable} def saltpath(): ''' Return the path of the salt module ''' # Provides: # saltpath salt_path = os.path.abspath(os.path.join(__file__, os.path.pardir)) return {'saltpath': os.path.dirname(salt_path)} def saltversion(): ''' Return the version of salt ''' # Provides: # saltversion from salt.version import __version__ return {'saltversion': __version__} def zmqversion(): ''' Return the zeromq version ''' # Provides: # zmqversion try: import zmq return {'zmqversion': zmq.zmq_version()} # pylint: disable=no-member except ImportError: return {} def saltversioninfo(): ''' Return the version_info of salt .. versionadded:: 0.17.0 ''' # Provides: # saltversioninfo from salt.version import __version_info__ return {'saltversioninfo': list(__version_info__)} def _hw_data(osdata): ''' Get system specific hardware data from dmidecode Provides biosversion productname manufacturer serialnumber biosreleasedate uuid .. versionadded:: 0.9.5 ''' if salt.utils.platform.is_proxy(): return {} grains = {} if osdata['kernel'] == 'Linux' and os.path.exists('/sys/class/dmi/id'): # On many Linux distributions basic firmware information is available via sysfs # requires CONFIG_DMIID to be enabled in the Linux kernel configuration sysfs_firmware_info = { 'biosversion': 'bios_version', 'productname': 'product_name', 'manufacturer': 'sys_vendor', 'biosreleasedate': 'bios_date', 'uuid': 'product_uuid', 'serialnumber': 'product_serial' } for key, fw_file in sysfs_firmware_info.items(): contents_file = os.path.join('/sys/class/dmi/id', fw_file) if os.path.exists(contents_file): try: with salt.utils.files.fopen(contents_file, 'r') as ifile: grains[key] = salt.utils.stringutils.to_unicode(ifile.read().strip(), errors='replace') if key == 'uuid': grains['uuid'] = grains['uuid'].lower() except (IOError, OSError) as err: # PermissionError is new to Python 3, but corresponds to the EACESS and # EPERM error numbers. Use those instead here for PY2 compatibility. if err.errno == EACCES or err.errno == EPERM: # Skip the grain if non-root user has no access to the file. pass elif salt.utils.path.which_bin(['dmidecode', 'smbios']) is not None and not ( salt.utils.platform.is_smartos() or ( # SunOS on SPARC - 'smbios: failed to load SMBIOS: System does not export an SMBIOS table' osdata['kernel'] == 'SunOS' and osdata['cpuarch'].startswith('sparc') )): # On SmartOS (possibly SunOS also) smbios only works in the global zone # smbios is also not compatible with linux's smbios (smbios -s = print summarized) grains = { 'biosversion': __salt__['smbios.get']('bios-version'), 'productname': __salt__['smbios.get']('system-product-name'), 'manufacturer': __salt__['smbios.get']('system-manufacturer'), 'biosreleasedate': __salt__['smbios.get']('bios-release-date'), 'uuid': __salt__['smbios.get']('system-uuid') } grains = dict([(key, val) for key, val in grains.items() if val is not None]) uuid = __salt__['smbios.get']('system-uuid') if uuid is not None: grains['uuid'] = uuid.lower() for serial in ('system-serial-number', 'chassis-serial-number', 'baseboard-serial-number'): serial = __salt__['smbios.get'](serial) if serial is not None: grains['serialnumber'] = serial break elif salt.utils.path.which_bin(['fw_printenv']) is not None: # ARM Linux devices expose UBOOT env variables via fw_printenv hwdata = { 'manufacturer': 'manufacturer', 'serialnumber': 'serial#', 'productname': 'DeviceDesc', } for grain_name, cmd_key in six.iteritems(hwdata): result = __salt__['cmd.run_all']('fw_printenv {0}'.format(cmd_key)) if result['retcode'] == 0: uboot_keyval = result['stdout'].split('=') grains[grain_name] = _clean_value(grain_name, uboot_keyval[1]) elif osdata['kernel'] == 'FreeBSD': # On FreeBSD /bin/kenv (already in base system) # can be used instead of dmidecode kenv = salt.utils.path.which('kenv') if kenv: # In theory, it will be easier to add new fields to this later fbsd_hwdata = { 'biosversion': 'smbios.bios.version', 'manufacturer': 'smbios.system.maker', 'serialnumber': 'smbios.system.serial', 'productname': 'smbios.system.product', 'biosreleasedate': 'smbios.bios.reldate', 'uuid': 'smbios.system.uuid', } for key, val in six.iteritems(fbsd_hwdata): value = __salt__['cmd.run']('{0} {1}'.format(kenv, val)) grains[key] = _clean_value(key, value) elif osdata['kernel'] == 'OpenBSD': sysctl = salt.utils.path.which('sysctl') hwdata = {'biosversion': 'hw.version', 'manufacturer': 'hw.vendor', 'productname': 'hw.product', 'serialnumber': 'hw.serialno', 'uuid': 'hw.uuid'} for key, oid in six.iteritems(hwdata): value = __salt__['cmd.run']('{0} -n {1}'.format(sysctl, oid)) if not value.endswith(' value is not available'): grains[key] = _clean_value(key, value) elif osdata['kernel'] == 'NetBSD': sysctl = salt.utils.path.which('sysctl') nbsd_hwdata = { 'biosversion': 'machdep.dmi.board-version', 'manufacturer': 'machdep.dmi.system-vendor', 'serialnumber': 'machdep.dmi.system-serial', 'productname': 'machdep.dmi.system-product', 'biosreleasedate': 'machdep.dmi.bios-date', 'uuid': 'machdep.dmi.system-uuid', } for key, oid in six.iteritems(nbsd_hwdata): result = __salt__['cmd.run_all']('{0} -n {1}'.format(sysctl, oid)) if result['retcode'] == 0: grains[key] = _clean_value(key, result['stdout']) elif osdata['kernel'] == 'Darwin': grains['manufacturer'] = 'Apple Inc.' sysctl = salt.utils.path.which('sysctl') hwdata = {'productname': 'hw.model'} for key, oid in hwdata.items(): value = __salt__['cmd.run']('{0} -b {1}'.format(sysctl, oid)) if not value.endswith(' is invalid'): grains[key] = _clean_value(key, value) elif osdata['kernel'] == 'SunOS' and osdata['cpuarch'].startswith('sparc'): # Depending on the hardware model, commands can report different bits # of information. With that said, consolidate the output from various # commands and attempt various lookups. data = "" for (cmd, args) in (('/usr/sbin/prtdiag', '-v'), ('/usr/sbin/prtconf', '-vp'), ('/usr/sbin/virtinfo', '-a')): if salt.utils.path.which(cmd): # Also verifies that cmd is executable data += __salt__['cmd.run']('{0} {1}'.format(cmd, args)) data += '\n' sn_regexes = [ re.compile(r) for r in [ r'(?im)^\s*Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag r'(?im)^\s*chassis-sn:\s*(\S+)', # prtconf r'(?im)^\s*Chassis\s+Serial#:\s*(\S+)', # virtinfo ] ] obp_regexes = [ re.compile(r) for r in [ r'(?im)^\s*System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag r'(?im)^\s*version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf ] ] fw_regexes = [ re.compile(r) for r in [ r'(?im)^\s*Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag ] ] uuid_regexes = [ re.compile(r) for r in [ r'(?im)^\s*Domain\s+UUID:\s*(\S+)', # virtinfo ] ] manufacture_regexes = [ re.compile(r) for r in [ r'(?im)^\s*System\s+Configuration:\s*(.*)(?=sun)', # prtdiag ] ] product_regexes = [ re.compile(r) for r in [ r'(?im)^\s*System\s+Configuration:\s*.*?sun\d\S+[^\S\r\n]*(.*)', # prtdiag r'(?im)^[^\S\r\n]*banner-name:[^\S\r\n]*(.*)', # prtconf r'(?im)^[^\S\r\n]*product-name:[^\S\r\n]*(.*)', # prtconf ] ] sn_regexes = [ re.compile(r) for r in [ r'(?im)Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag r'(?i)Chassis\s+Serial#:\s*(\S+)', # virtinfo r'(?i)chassis-sn:\s*(\S+)', # prtconf ] ] obp_regexes = [ re.compile(r) for r in [ r'(?im)System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag r'(?im)version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf ] ] fw_regexes = [ re.compile(r) for r in [ r'(?i)Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag ] ] uuid_regexes = [ re.compile(r) for r in [ r'(?i)Domain\s+UUID:\s+(\S+)', # virtinfo ] ] for regex in sn_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: grains['serialnumber'] = res.group(1).strip().replace("'", "") break for regex in obp_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: obp_rev, obp_date = res.groups()[0:2] # Limit the number in case we found the data in multiple places grains['biosversion'] = obp_rev.strip().replace("'", "") grains['biosreleasedate'] = obp_date.strip().replace("'", "") for regex in fw_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: fw_rev, fw_date = res.groups()[0:2] grains['systemfirmware'] = fw_rev.strip().replace("'", "") grains['systemfirmwaredate'] = fw_date.strip().replace("'", "") break for regex in uuid_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: grains['uuid'] = res.group(1).strip().replace("'", "") break for regex in manufacture_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: grains['manufacture'] = res.group(1).strip().replace("'", "") break for regex in product_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: t_productname = res.group(1).strip().replace("'", "") if t_productname: grains['product'] = t_productname grains['productname'] = t_productname break elif osdata['kernel'] == 'AIX': cmd = salt.utils.path.which('prtconf') if cmd: data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'), ('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')): for regex in [re.compile(r) for r in [regstring]]: res = regex.search(data) if res and len(res.groups()) >= 1: grains[dest] = res.group(1).strip().replace("'", '') product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')] for regex in product_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",") break else: log.error('The \'prtconf\' binary was not found in $PATH.') elif osdata['kernel'] == 'AIX': cmd = salt.utils.path.which('prtconf') if data: data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'), ('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')): for regex in [re.compile(r) for r in [regstring]]: res = regex.search(data) if res and len(res.groups()) >= 1: grains[dest] = res.group(1).strip().replace("'", '') product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')] for regex in product_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",") break else: log.error('The \'prtconf\' binary was not found in $PATH.') return grains def _get_hash_by_shell(): ''' Shell-out Python 3 for compute reliable hash :return: ''' id_ = __opts__.get('id', '') id_hash = None py_ver = sys.version_info[:2] if py_ver >= (3, 3): # Python 3.3 enabled hash randomization, so we need to shell out to get # a reliable hash. id_hash = __salt__['cmd.run']([sys.executable, '-c', 'print(hash("{0}"))'.format(id_)], env={'PYTHONHASHSEED': '0'}) try: id_hash = int(id_hash) except (TypeError, ValueError): log.debug('Failed to hash the ID to get the server_id grain. Result of hash command: %s', id_hash) id_hash = None if id_hash is None: # Python < 3.3 or error encountered above id_hash = hash(id_) return abs(id_hash % (2 ** 31)) def get_server_id(): ''' Provides an integer based on the FQDN of a machine. Useful as server-id in MySQL replication or anywhere else you'll need an ID like this. ''' # Provides: # server_id if salt.utils.platform.is_proxy(): server_id = {} else: use_crc = __opts__.get('server_id_use_crc') if bool(use_crc): id_hash = getattr(zlib, use_crc, zlib.adler32)(__opts__.get('id', '').encode()) & 0xffffffff else: log.debug('This server_id is computed not by Adler32 nor by CRC32. ' 'Please use "server_id_use_crc" option and define algorithm you ' 'prefer (default "Adler32"). Starting with Sodium, the ' 'server_id will be computed with Adler32 by default.') id_hash = _get_hash_by_shell() server_id = {'server_id': id_hash} return server_id def get_master(): ''' Provides the minion with the name of its master. This is useful in states to target other services running on the master. ''' # Provides: # master return {'master': __opts__.get('master', '')} def default_gateway(): ''' Populates grains which describe whether a server has a default gateway configured or not. Uses `ip -4 route show` and `ip -6 route show` and greps for a `default` at the beginning of any line. Assuming the standard `default via <ip>` format for default gateways, it will also parse out the ip address of the default gateway, and put it in ip4_gw or ip6_gw. If the `ip` command is unavailable, no grains will be populated. Currently does not support multiple default gateways. The grains will be set to the first default gateway found. List of grains: ip4_gw: True # ip/True/False if default ipv4 gateway ip6_gw: True # ip/True/False if default ipv6 gateway ip_gw: True # True if either of the above is True, False otherwise ''' grains = {} ip_bin = salt.utils.path.which('ip') if not ip_bin: return {} grains['ip_gw'] = False grains['ip4_gw'] = False grains['ip6_gw'] = False for ip_version in ('4', '6'): try: out = __salt__['cmd.run']([ip_bin, '-' + ip_version, 'route', 'show']) for line in out.splitlines(): if line.startswith('default'): grains['ip_gw'] = True grains['ip{0}_gw'.format(ip_version)] = True try: via, gw_ip = line.split()[1:3] except ValueError: pass else: if via == 'via': grains['ip{0}_gw'.format(ip_version)] = gw_ip break except Exception: continue return grains def kernelparams(): ''' Return the kernel boot parameters ''' if salt.utils.platform.is_windows(): # TODO: add grains using `bcdedit /enum {current}` return {} else: try: with salt.utils.files.fopen('/proc/cmdline', 'r') as fhr: cmdline = fhr.read() grains = {'kernelparams': []} for data in [item.split('=') for item in salt.utils.args.shlex_split(cmdline)]: value = None if len(data) == 2: value = data[1].strip('"') grains['kernelparams'] += [(data[0], value)] except IOError as exc: grains = {} log.debug('Failed to read /proc/cmdline: %s', exc) return grains
saltstack/salt
salt/grains/core.py
hwaddr_interfaces
python
def hwaddr_interfaces(): ''' Provide a dict of the connected interfaces and their hw addresses (Mac Address) ''' # Provides: # hwaddr_interfaces ret = {} ifaces = _get_interfaces() for face in ifaces: if 'hwaddr' in ifaces[face]: ret[face] = ifaces[face]['hwaddr'] return {'hwaddr_interfaces': ret}
Provide a dict of the connected interfaces and their hw addresses (Mac Address)
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/grains/core.py#L2307-L2319
[ "def _get_interfaces():\n '''\n Provide a dict of the connected interfaces and their ip addresses\n '''\n\n global _INTERFACES\n if not _INTERFACES:\n _INTERFACES = salt.utils.network.interfaces()\n return _INTERFACES\n" ]
# -*- coding: utf-8 -*- ''' The static grains, these are the core, or built in grains. When grains are loaded they are not loaded in the same way that modules are loaded, grain functions are detected and executed, the functions MUST return a dict which will be applied to the main grains dict. This module will always be executed first, so that any grains loaded here in the core module can be overwritten just by returning dict keys with the same value as those returned here ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import socket import sys import re import platform import logging import locale import uuid import zlib from errno import EACCES, EPERM import datetime import warnings # pylint: disable=import-error try: import dateutil.tz _DATEUTIL_TZ = True except ImportError: _DATEUTIL_TZ = False __proxyenabled__ = ['*'] __FQDN__ = None # Extend the default list of supported distros. This will be used for the # /etc/DISTRO-release checking that is part of linux_distribution() from platform import _supported_dists _supported_dists += ('arch', 'mageia', 'meego', 'vmware', 'bluewhite64', 'slamd64', 'ovs', 'system', 'mint', 'oracle', 'void') # linux_distribution deprecated in py3.7 try: from platform import linux_distribution as _deprecated_linux_distribution def linux_distribution(**kwargs): with warnings.catch_warnings(): warnings.simplefilter("ignore") return _deprecated_linux_distribution(**kwargs) except ImportError: from distro import linux_distribution # Import salt libs import salt.exceptions import salt.log import salt.utils.args import salt.utils.dns import salt.utils.files import salt.utils.network import salt.utils.path import salt.utils.pkg.rpm import salt.utils.platform import salt.utils.stringutils import salt.utils.versions from salt.ext import six from salt.ext.six.moves import range if salt.utils.platform.is_windows(): import salt.utils.win_osinfo # Solve the Chicken and egg problem where grains need to run before any # of the modules are loaded and are generally available for any usage. import salt.modules.cmdmod import salt.modules.smbios __salt__ = { 'cmd.run': salt.modules.cmdmod._run_quiet, 'cmd.retcode': salt.modules.cmdmod._retcode_quiet, 'cmd.run_all': salt.modules.cmdmod._run_all_quiet, 'smbios.records': salt.modules.smbios.records, 'smbios.get': salt.modules.smbios.get, } log = logging.getLogger(__name__) HAS_WMI = False if salt.utils.platform.is_windows(): # attempt to import the python wmi module # the Windows minion uses WMI for some of its grains try: import wmi # pylint: disable=import-error import salt.utils.winapi import win32api import salt.utils.win_reg HAS_WMI = True except ImportError: log.exception( 'Unable to import Python wmi module, some core grains ' 'will be missing' ) HAS_UNAME = True if not hasattr(os, 'uname'): HAS_UNAME = False _INTERFACES = {} def _windows_cpudata(): ''' Return some CPU information on Windows minions ''' # Provides: # num_cpus # cpu_model grains = {} if 'NUMBER_OF_PROCESSORS' in os.environ: # Cast to int so that the logic isn't broken when used as a # conditional in templating. Also follows _linux_cpudata() try: grains['num_cpus'] = int(os.environ['NUMBER_OF_PROCESSORS']) except ValueError: grains['num_cpus'] = 1 grains['cpu_model'] = salt.utils.win_reg.read_value( hive="HKEY_LOCAL_MACHINE", key="HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", vname="ProcessorNameString").get('vdata') return grains def _linux_cpudata(): ''' Return some CPU information for Linux minions ''' # Provides: # num_cpus # cpu_model # cpu_flags grains = {} cpuinfo = '/proc/cpuinfo' # Parse over the cpuinfo file if os.path.isfile(cpuinfo): with salt.utils.files.fopen(cpuinfo, 'r') as _fp: grains['num_cpus'] = 0 for line in _fp: comps = line.split(':') if not len(comps) > 1: continue key = comps[0].strip() val = comps[1].strip() if key == 'processor': grains['num_cpus'] += 1 elif key == 'model name': grains['cpu_model'] = val elif key == 'flags': grains['cpu_flags'] = val.split() elif key == 'Features': grains['cpu_flags'] = val.split() # ARM support - /proc/cpuinfo # # Processor : ARMv6-compatible processor rev 7 (v6l) # BogoMIPS : 697.95 # Features : swp half thumb fastmult vfp edsp java tls # CPU implementer : 0x41 # CPU architecture: 7 # CPU variant : 0x0 # CPU part : 0xb76 # CPU revision : 7 # # Hardware : BCM2708 # Revision : 0002 # Serial : 00000000 elif key == 'Processor': grains['cpu_model'] = val.split('-')[0] grains['num_cpus'] = 1 if 'num_cpus' not in grains: grains['num_cpus'] = 0 if 'cpu_model' not in grains: grains['cpu_model'] = 'Unknown' if 'cpu_flags' not in grains: grains['cpu_flags'] = [] return grains def _linux_gpu_data(): ''' num_gpus: int gpus: - vendor: nvidia|amd|ati|... model: string ''' if __opts__.get('enable_lspci', True) is False: return {} if __opts__.get('enable_gpu_grains', True) is False: return {} lspci = salt.utils.path.which('lspci') if not lspci: log.debug( 'The `lspci` binary is not available on the system. GPU grains ' 'will not be available.' ) return {} # dominant gpu vendors to search for (MUST be lowercase for matching below) known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed'] gpu_classes = ('vga compatible controller', '3d controller') devs = [] try: lspci_out = __salt__['cmd.run']('{0} -vmm'.format(lspci)) cur_dev = {} error = False # Add a blank element to the lspci_out.splitlines() list, # otherwise the last device is not evaluated as a cur_dev and ignored. lspci_list = lspci_out.splitlines() lspci_list.append('') for line in lspci_list: # check for record-separating empty lines if line == '': if cur_dev.get('Class', '').lower() in gpu_classes: devs.append(cur_dev) cur_dev = {} continue if re.match(r'^\w+:\s+.*', line): key, val = line.split(':', 1) cur_dev[key.strip()] = val.strip() else: error = True log.debug('Unexpected lspci output: \'%s\'', line) if error: log.warning( 'Error loading grains, unexpected linux_gpu_data output, ' 'check that you have a valid shell configured and ' 'permissions to run lspci command' ) except OSError: pass gpus = [] for gpu in devs: vendor_strings = re.split('[^A-Za-z0-9]', gpu['Vendor'].lower()) # default vendor to 'unknown', overwrite if we match a known one vendor = 'unknown' for name in known_vendors: # search for an 'expected' vendor name in the list of strings if name in vendor_strings: vendor = name break gpus.append({'vendor': vendor, 'model': gpu['Device']}) grains = {} grains['num_gpus'] = len(gpus) grains['gpus'] = gpus return grains def _netbsd_gpu_data(): ''' num_gpus: int gpus: - vendor: nvidia|amd|ati|... model: string ''' known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed'] gpus = [] try: pcictl_out = __salt__['cmd.run']('pcictl pci0 list') for line in pcictl_out.splitlines(): for vendor in known_vendors: vendor_match = re.match( r'[0-9:]+ ({0}) (.+) \(VGA .+\)'.format(vendor), line, re.IGNORECASE ) if vendor_match: gpus.append({'vendor': vendor_match.group(1), 'model': vendor_match.group(2)}) except OSError: pass grains = {} grains['num_gpus'] = len(gpus) grains['gpus'] = gpus return grains def _osx_gpudata(): ''' num_gpus: int gpus: - vendor: nvidia|amd|ati|... model: string ''' gpus = [] try: pcictl_out = __salt__['cmd.run']('system_profiler SPDisplaysDataType') for line in pcictl_out.splitlines(): fieldname, _, fieldval = line.partition(': ') if fieldname.strip() == "Chipset Model": vendor, _, model = fieldval.partition(' ') vendor = vendor.lower() gpus.append({'vendor': vendor, 'model': model}) except OSError: pass grains = {} grains['num_gpus'] = len(gpus) grains['gpus'] = gpus return grains def _bsd_cpudata(osdata): ''' Return CPU information for BSD-like systems ''' # Provides: # cpuarch # num_cpus # cpu_model # cpu_flags sysctl = salt.utils.path.which('sysctl') arch = salt.utils.path.which('arch') cmds = {} if sysctl: cmds.update({ 'num_cpus': '{0} -n hw.ncpu'.format(sysctl), 'cpuarch': '{0} -n hw.machine'.format(sysctl), 'cpu_model': '{0} -n hw.model'.format(sysctl), }) if arch and osdata['kernel'] == 'OpenBSD': cmds['cpuarch'] = '{0} -s'.format(arch) if osdata['kernel'] == 'Darwin': cmds['cpu_model'] = '{0} -n machdep.cpu.brand_string'.format(sysctl) cmds['cpu_flags'] = '{0} -n machdep.cpu.features'.format(sysctl) grains = dict([(k, __salt__['cmd.run'](v)) for k, v in six.iteritems(cmds)]) if 'cpu_flags' in grains and isinstance(grains['cpu_flags'], six.string_types): grains['cpu_flags'] = grains['cpu_flags'].split(' ') if osdata['kernel'] == 'NetBSD': grains['cpu_flags'] = [] for line in __salt__['cmd.run']('cpuctl identify 0').splitlines(): cpu_match = re.match(r'cpu[0-9]:\ features[0-9]?\ .+<(.+)>', line) if cpu_match: flag = cpu_match.group(1).split(',') grains['cpu_flags'].extend(flag) if osdata['kernel'] == 'FreeBSD' and os.path.isfile('/var/run/dmesg.boot'): grains['cpu_flags'] = [] # TODO: at least it needs to be tested for BSD other then FreeBSD with salt.utils.files.fopen('/var/run/dmesg.boot', 'r') as _fp: cpu_here = False for line in _fp: if line.startswith('CPU: '): cpu_here = True # starts CPU descr continue if cpu_here: if not line.startswith(' '): break # game over if 'Features' in line: start = line.find('<') end = line.find('>') if start > 0 and end > 0: flag = line[start + 1:end].split(',') grains['cpu_flags'].extend(flag) try: grains['num_cpus'] = int(grains['num_cpus']) except ValueError: grains['num_cpus'] = 1 return grains def _sunos_cpudata(): ''' Return the CPU information for Solaris-like systems ''' # Provides: # cpuarch # num_cpus # cpu_model # cpu_flags grains = {} grains['cpu_flags'] = [] grains['cpuarch'] = __salt__['cmd.run']('isainfo -k') psrinfo = '/usr/sbin/psrinfo 2>/dev/null' grains['num_cpus'] = len(__salt__['cmd.run'](psrinfo, python_shell=True).splitlines()) kstat_info = 'kstat -p cpu_info:*:*:brand' for line in __salt__['cmd.run'](kstat_info).splitlines(): match = re.match(r'(\w+:\d+:\w+\d+:\w+)\s+(.+)', line) if match: grains['cpu_model'] = match.group(2) isainfo = 'isainfo -n -v' for line in __salt__['cmd.run'](isainfo).splitlines(): match = re.match(r'^\s+(.+)', line) if match: cpu_flags = match.group(1).split() grains['cpu_flags'].extend(cpu_flags) return grains def _aix_cpudata(): ''' Return CPU information for AIX systems ''' # Provides: # cpuarch # num_cpus # cpu_model # cpu_flags grains = {} cmd = salt.utils.path.which('prtconf') if cmd: data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep for dest, regstring in (('cpuarch', r'(?im)^\s*Processor\s+Type:\s+(\S+)'), ('cpu_flags', r'(?im)^\s*Processor\s+Version:\s+(\S+)'), ('cpu_model', r'(?im)^\s*Processor\s+Implementation\s+Mode:\s+(.*)'), ('num_cpus', r'(?im)^\s*Number\s+Of\s+Processors:\s+(\S+)')): for regex in [re.compile(r) for r in [regstring]]: res = regex.search(data) if res and len(res.groups()) >= 1: grains[dest] = res.group(1).strip().replace("'", '') else: log.error('The \'prtconf\' binary was not found in $PATH.') return grains def _linux_memdata(): ''' Return the memory information for Linux-like systems ''' grains = {'mem_total': 0, 'swap_total': 0} meminfo = '/proc/meminfo' if os.path.isfile(meminfo): with salt.utils.files.fopen(meminfo, 'r') as ifile: for line in ifile: comps = line.rstrip('\n').split(':') if not len(comps) > 1: continue if comps[0].strip() == 'MemTotal': # Use floor division to force output to be an integer grains['mem_total'] = int(comps[1].split()[0]) // 1024 if comps[0].strip() == 'SwapTotal': # Use floor division to force output to be an integer grains['swap_total'] = int(comps[1].split()[0]) // 1024 return grains def _osx_memdata(): ''' Return the memory information for BSD-like systems ''' grains = {'mem_total': 0, 'swap_total': 0} sysctl = salt.utils.path.which('sysctl') if sysctl: mem = __salt__['cmd.run']('{0} -n hw.memsize'.format(sysctl)) swap_total = __salt__['cmd.run']('{0} -n vm.swapusage'.format(sysctl)).split()[2].replace(',', '.') if swap_total.endswith('K'): _power = 2**10 elif swap_total.endswith('M'): _power = 2**20 elif swap_total.endswith('G'): _power = 2**30 swap_total = float(swap_total[:-1]) * _power grains['mem_total'] = int(mem) // 1024 // 1024 grains['swap_total'] = int(swap_total) // 1024 // 1024 return grains def _bsd_memdata(osdata): ''' Return the memory information for BSD-like systems ''' grains = {'mem_total': 0, 'swap_total': 0} sysctl = salt.utils.path.which('sysctl') if sysctl: mem = __salt__['cmd.run']('{0} -n hw.physmem'.format(sysctl)) if osdata['kernel'] == 'NetBSD' and mem.startswith('-'): mem = __salt__['cmd.run']('{0} -n hw.physmem64'.format(sysctl)) grains['mem_total'] = int(mem) // 1024 // 1024 if osdata['kernel'] in ['OpenBSD', 'NetBSD']: swapctl = salt.utils.path.which('swapctl') swap_data = __salt__['cmd.run']('{0} -sk'.format(swapctl)) if swap_data == 'no swap devices configured': swap_total = 0 else: swap_total = swap_data.split(' ')[1] else: swap_total = __salt__['cmd.run']('{0} -n vm.swap_total'.format(sysctl)) grains['swap_total'] = int(swap_total) // 1024 // 1024 return grains def _sunos_memdata(): ''' Return the memory information for SunOS-like systems ''' grains = {'mem_total': 0, 'swap_total': 0} prtconf = '/usr/sbin/prtconf 2>/dev/null' for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines(): comps = line.split(' ') if comps[0].strip() == 'Memory' and comps[1].strip() == 'size:': grains['mem_total'] = int(comps[2].strip()) swap_cmd = salt.utils.path.which('swap') swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split() try: swap_avail = int(swap_data[-2][:-1]) swap_used = int(swap_data[-4][:-1]) swap_total = (swap_avail + swap_used) // 1024 except ValueError: swap_total = None grains['swap_total'] = swap_total return grains def _aix_memdata(): ''' Return the memory information for AIX systems ''' grains = {'mem_total': 0, 'swap_total': 0} prtconf = salt.utils.path.which('prtconf') if prtconf: for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines(): comps = [x for x in line.strip().split(' ') if x] if len(comps) > 2 and 'Memory' in comps[0] and 'Size' in comps[1]: grains['mem_total'] = int(comps[2]) break else: log.error('The \'prtconf\' binary was not found in $PATH.') swap_cmd = salt.utils.path.which('swap') if swap_cmd: swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split() try: swap_total = (int(swap_data[-2]) + int(swap_data[-6])) * 4 except ValueError: swap_total = None grains['swap_total'] = swap_total else: log.error('The \'swap\' binary was not found in $PATH.') return grains def _windows_memdata(): ''' Return the memory information for Windows systems ''' grains = {'mem_total': 0} # get the Total Physical memory as reported by msinfo32 tot_bytes = win32api.GlobalMemoryStatusEx()['TotalPhys'] # return memory info in gigabytes grains['mem_total'] = int(tot_bytes / (1024 ** 2)) return grains def _memdata(osdata): ''' Gather information about the system memory ''' # Provides: # mem_total # swap_total, for supported systems. grains = {'mem_total': 0} if osdata['kernel'] == 'Linux': grains.update(_linux_memdata()) elif osdata['kernel'] in ('FreeBSD', 'OpenBSD', 'NetBSD'): grains.update(_bsd_memdata(osdata)) elif osdata['kernel'] == 'Darwin': grains.update(_osx_memdata()) elif osdata['kernel'] == 'SunOS': grains.update(_sunos_memdata()) elif osdata['kernel'] == 'AIX': grains.update(_aix_memdata()) elif osdata['kernel'] == 'Windows' and HAS_WMI: grains.update(_windows_memdata()) return grains def _aix_get_machine_id(): ''' Parse the output of lsattr -El sys0 for os_uuid ''' grains = {} cmd = salt.utils.path.which('lsattr') if cmd: data = __salt__['cmd.run']('{0} -El sys0'.format(cmd)) + os.linesep uuid_regexes = [re.compile(r'(?im)^\s*os_uuid\s+(\S+)\s+(.*)')] for regex in uuid_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: grains['machine_id'] = res.group(1).strip() break else: log.error('The \'lsattr\' binary was not found in $PATH.') return grains def _windows_virtual(osdata): ''' Returns what type of virtual hardware is under the hood, kvm or physical ''' # Provides: # virtual # virtual_subtype grains = dict() if osdata['kernel'] != 'Windows': return grains grains['virtual'] = 'physical' # It is possible that the 'manufacturer' and/or 'productname' grains # exist but have a value of None. manufacturer = osdata.get('manufacturer', '') if manufacturer is None: manufacturer = '' productname = osdata.get('productname', '') if productname is None: productname = '' if 'QEMU' in manufacturer: # FIXME: Make this detect between kvm or qemu grains['virtual'] = 'kvm' if 'Bochs' in manufacturer: grains['virtual'] = 'kvm' # Product Name: (oVirt) www.ovirt.org # Red Hat Community virtualization Project based on kvm elif 'oVirt' in productname: grains['virtual'] = 'kvm' grains['virtual_subtype'] = 'oVirt' # Red Hat Enterprise Virtualization elif 'RHEV Hypervisor' in productname: grains['virtual'] = 'kvm' grains['virtual_subtype'] = 'rhev' # Product Name: VirtualBox elif 'VirtualBox' in productname: grains['virtual'] = 'VirtualBox' # Product Name: VMware Virtual Platform elif 'VMware Virtual Platform' in productname: grains['virtual'] = 'VMware' # Manufacturer: Microsoft Corporation # Product Name: Virtual Machine elif 'Microsoft' in manufacturer and \ 'Virtual Machine' in productname: grains['virtual'] = 'VirtualPC' # Manufacturer: Parallels Software International Inc. elif 'Parallels Software' in manufacturer: grains['virtual'] = 'Parallels' # Apache CloudStack elif 'CloudStack KVM Hypervisor' in productname: grains['virtual'] = 'kvm' grains['virtual_subtype'] = 'cloudstack' return grains def _virtual(osdata): ''' Returns what type of virtual hardware is under the hood, kvm or physical ''' # This is going to be a monster, if you are running a vm you can test this # grain with please submit patches! # Provides: # virtual # virtual_subtype grains = {'virtual': 'physical'} # Skip the below loop on platforms which have none of the desired cmds # This is a temporary measure until we can write proper virtual hardware # detection. skip_cmds = ('AIX',) # list of commands to be executed to determine the 'virtual' grain _cmds = ['systemd-detect-virt', 'virt-what', 'dmidecode'] # test first for virt-what, which covers most of the desired functionality # on most platforms if not salt.utils.platform.is_windows() and osdata['kernel'] not in skip_cmds: if salt.utils.path.which('virt-what'): _cmds = ['virt-what'] # Check if enable_lspci is True or False if __opts__.get('enable_lspci', True) is True: # /proc/bus/pci does not exists, lspci will fail if os.path.exists('/proc/bus/pci'): _cmds += ['lspci'] # Add additional last resort commands if osdata['kernel'] in skip_cmds: _cmds = () # Quick backout for BrandZ (Solaris LX Branded zones) # Don't waste time trying other commands to detect the virtual grain if HAS_UNAME and osdata['kernel'] == 'Linux' and 'BrandZ virtual linux' in os.uname(): grains['virtual'] = 'zone' return grains failed_commands = set() for command in _cmds: args = [] if osdata['kernel'] == 'Darwin': command = 'system_profiler' args = ['SPDisplaysDataType'] elif osdata['kernel'] == 'SunOS': virtinfo = salt.utils.path.which('virtinfo') if virtinfo: try: ret = __salt__['cmd.run_all']('{0} -a'.format(virtinfo)) except salt.exceptions.CommandExecutionError: if salt.log.is_logging_configured(): failed_commands.add(virtinfo) else: if ret['stdout'].endswith('not supported'): command = 'prtdiag' else: command = 'virtinfo' else: command = 'prtdiag' cmd = salt.utils.path.which(command) if not cmd: continue cmd = '{0} {1}'.format(cmd, ' '.join(args)) try: ret = __salt__['cmd.run_all'](cmd) if ret['retcode'] > 0: if salt.log.is_logging_configured(): # systemd-detect-virt always returns > 0 on non-virtualized # systems # prtdiag only works in the global zone, skip if it fails if salt.utils.platform.is_windows() or 'systemd-detect-virt' in cmd or 'prtdiag' in cmd: continue failed_commands.add(command) continue except salt.exceptions.CommandExecutionError: if salt.log.is_logging_configured(): if salt.utils.platform.is_windows(): continue failed_commands.add(command) continue output = ret['stdout'] if command == "system_profiler": macoutput = output.lower() if '0x1ab8' in macoutput: grains['virtual'] = 'Parallels' if 'parallels' in macoutput: grains['virtual'] = 'Parallels' if 'vmware' in macoutput: grains['virtual'] = 'VMware' if '0x15ad' in macoutput: grains['virtual'] = 'VMware' if 'virtualbox' in macoutput: grains['virtual'] = 'VirtualBox' # Break out of the loop so the next log message is not issued break elif command == 'systemd-detect-virt': if output in ('qemu', 'kvm', 'oracle', 'xen', 'bochs', 'chroot', 'uml', 'systemd-nspawn'): grains['virtual'] = output break elif 'vmware' in output: grains['virtual'] = 'VMware' break elif 'microsoft' in output: grains['virtual'] = 'VirtualPC' break elif 'lxc' in output: grains['virtual'] = 'LXC' break elif 'systemd-nspawn' in output: grains['virtual'] = 'LXC' break elif command == 'virt-what': try: output = output.splitlines()[-1] except IndexError: pass if output in ('kvm', 'qemu', 'uml', 'xen', 'lxc'): grains['virtual'] = output break elif 'vmware' in output: grains['virtual'] = 'VMware' break elif 'parallels' in output: grains['virtual'] = 'Parallels' break elif 'hyperv' in output: grains['virtual'] = 'HyperV' break elif command == 'dmidecode': # Product Name: VirtualBox if 'Vendor: QEMU' in output: # FIXME: Make this detect between kvm or qemu grains['virtual'] = 'kvm' if 'Manufacturer: QEMU' in output: grains['virtual'] = 'kvm' if 'Vendor: Bochs' in output: grains['virtual'] = 'kvm' if 'Manufacturer: Bochs' in output: grains['virtual'] = 'kvm' if 'BHYVE' in output: grains['virtual'] = 'bhyve' # Product Name: (oVirt) www.ovirt.org # Red Hat Community virtualization Project based on kvm elif 'Manufacturer: oVirt' in output: grains['virtual'] = 'kvm' grains['virtual_subtype'] = 'ovirt' # Red Hat Enterprise Virtualization elif 'Product Name: RHEV Hypervisor' in output: grains['virtual'] = 'kvm' grains['virtual_subtype'] = 'rhev' elif 'VirtualBox' in output: grains['virtual'] = 'VirtualBox' # Product Name: VMware Virtual Platform elif 'VMware' in output: grains['virtual'] = 'VMware' # Manufacturer: Microsoft Corporation # Product Name: Virtual Machine elif ': Microsoft' in output and 'Virtual Machine' in output: grains['virtual'] = 'VirtualPC' # Manufacturer: Parallels Software International Inc. elif 'Parallels Software' in output: grains['virtual'] = 'Parallels' elif 'Manufacturer: Google' in output: grains['virtual'] = 'kvm' # Proxmox KVM elif 'Vendor: SeaBIOS' in output: grains['virtual'] = 'kvm' # Break out of the loop, lspci parsing is not necessary break elif command == 'lspci': # dmidecode not available or the user does not have the necessary # permissions model = output.lower() if 'vmware' in model: grains['virtual'] = 'VMware' # 00:04.0 System peripheral: InnoTek Systemberatung GmbH # VirtualBox Guest Service elif 'virtualbox' in model: grains['virtual'] = 'VirtualBox' elif 'qemu' in model: grains['virtual'] = 'kvm' elif 'virtio' in model: grains['virtual'] = 'kvm' # Break out of the loop so the next log message is not issued break elif command == 'prtdiag': model = output.lower().split("\n")[0] if 'vmware' in model: grains['virtual'] = 'VMware' elif 'virtualbox' in model: grains['virtual'] = 'VirtualBox' elif 'qemu' in model: grains['virtual'] = 'kvm' elif 'joyent smartdc hvm' in model: grains['virtual'] = 'kvm' break elif command == 'virtinfo': grains['virtual'] = 'LDOM' break choices = ('Linux', 'HP-UX') isdir = os.path.isdir sysctl = salt.utils.path.which('sysctl') if osdata['kernel'] in choices: if os.path.isdir('/proc'): try: self_root = os.stat('/') init_root = os.stat('/proc/1/root/.') if self_root != init_root: grains['virtual_subtype'] = 'chroot' except (IOError, OSError): pass if isdir('/proc/vz'): if os.path.isfile('/proc/vz/version'): grains['virtual'] = 'openvzhn' elif os.path.isfile('/proc/vz/veinfo'): grains['virtual'] = 'openvzve' # a posteriori, it's expected for these to have failed: failed_commands.discard('lspci') failed_commands.discard('dmidecode') # Provide additional detection for OpenVZ if os.path.isfile('/proc/self/status'): with salt.utils.files.fopen('/proc/self/status') as status_file: vz_re = re.compile(r'^envID:\s+(\d+)$') for line in status_file: vz_match = vz_re.match(line.rstrip('\n')) if vz_match and int(vz_match.groups()[0]) != 0: grains['virtual'] = 'openvzve' elif vz_match and int(vz_match.groups()[0]) == 0: grains['virtual'] = 'openvzhn' if isdir('/proc/sys/xen') or \ isdir('/sys/bus/xen') or isdir('/proc/xen'): if os.path.isfile('/proc/xen/xsd_kva'): # Tested on CentOS 5.3 / 2.6.18-194.26.1.el5xen # Tested on CentOS 5.4 / 2.6.18-164.15.1.el5xen grains['virtual_subtype'] = 'Xen Dom0' else: if osdata.get('productname', '') == 'HVM domU': # Requires dmidecode! grains['virtual_subtype'] = 'Xen HVM DomU' elif os.path.isfile('/proc/xen/capabilities') and \ os.access('/proc/xen/capabilities', os.R_OK): with salt.utils.files.fopen('/proc/xen/capabilities') as fhr: if 'control_d' not in fhr.read(): # Tested on CentOS 5.5 / 2.6.18-194.3.1.el5xen grains['virtual_subtype'] = 'Xen PV DomU' else: # Shouldn't get to this, but just in case grains['virtual_subtype'] = 'Xen Dom0' # Tested on Fedora 10 / 2.6.27.30-170.2.82 with xen # Tested on Fedora 15 / 2.6.41.4-1 without running xen elif isdir('/sys/bus/xen'): if 'xen:' in __salt__['cmd.run']('dmesg').lower(): grains['virtual_subtype'] = 'Xen PV DomU' elif os.path.isfile('/sys/bus/xen/drivers/xenconsole'): # An actual DomU will have the xenconsole driver grains['virtual_subtype'] = 'Xen PV DomU' # If a Dom0 or DomU was detected, obviously this is xen if 'dom' in grains.get('virtual_subtype', '').lower(): grains['virtual'] = 'xen' # Check container type after hypervisors, to avoid variable overwrite on containers running in virtual environment. if os.path.isfile('/proc/1/cgroup'): try: with salt.utils.files.fopen('/proc/1/cgroup', 'r') as fhr: fhr_contents = fhr.read() if ':/lxc/' in fhr_contents: grains['virtual_subtype'] = 'LXC' elif ':/kubepods/' in fhr_contents: grains['virtual_subtype'] = 'kubernetes' elif ':/libpod_parent/' in fhr_contents: grains['virtual_subtype'] = 'libpod' else: if any(x in fhr_contents for x in (':/system.slice/docker', ':/docker/', ':/docker-ce/')): grains['virtual_subtype'] = 'Docker' except IOError: pass if os.path.isfile('/proc/cpuinfo'): with salt.utils.files.fopen('/proc/cpuinfo', 'r') as fhr: if 'QEMU Virtual CPU' in fhr.read(): grains['virtual'] = 'kvm' if os.path.isfile('/sys/devices/virtual/dmi/id/product_name'): try: with salt.utils.files.fopen('/sys/devices/virtual/dmi/id/product_name', 'r') as fhr: output = salt.utils.stringutils.to_unicode(fhr.read(), errors='replace') if 'VirtualBox' in output: grains['virtual'] = 'VirtualBox' elif 'RHEV Hypervisor' in output: grains['virtual'] = 'kvm' grains['virtual_subtype'] = 'rhev' elif 'oVirt Node' in output: grains['virtual'] = 'kvm' grains['virtual_subtype'] = 'ovirt' elif 'Google' in output: grains['virtual'] = 'gce' elif 'BHYVE' in output: grains['virtual'] = 'bhyve' except IOError: pass elif osdata['kernel'] == 'FreeBSD': kenv = salt.utils.path.which('kenv') if kenv: product = __salt__['cmd.run']( '{0} smbios.system.product'.format(kenv) ) maker = __salt__['cmd.run']( '{0} smbios.system.maker'.format(kenv) ) if product.startswith('VMware'): grains['virtual'] = 'VMware' if product.startswith('VirtualBox'): grains['virtual'] = 'VirtualBox' if maker.startswith('Xen'): grains['virtual_subtype'] = '{0} {1}'.format(maker, product) grains['virtual'] = 'xen' if maker.startswith('Microsoft') and product.startswith('Virtual'): grains['virtual'] = 'VirtualPC' if maker.startswith('OpenStack'): grains['virtual'] = 'OpenStack' if maker.startswith('Bochs'): grains['virtual'] = 'kvm' if sysctl: hv_vendor = __salt__['cmd.run']('{0} hw.hv_vendor'.format(sysctl)) model = __salt__['cmd.run']('{0} hw.model'.format(sysctl)) jail = __salt__['cmd.run']( '{0} -n security.jail.jailed'.format(sysctl) ) if 'bhyve' in hv_vendor: grains['virtual'] = 'bhyve' if jail == '1': grains['virtual_subtype'] = 'jail' if 'QEMU Virtual CPU' in model: grains['virtual'] = 'kvm' elif osdata['kernel'] == 'OpenBSD': if 'manufacturer' in osdata: if osdata['manufacturer'] in ['QEMU', 'Red Hat', 'Joyent']: grains['virtual'] = 'kvm' if osdata['manufacturer'] == 'OpenBSD': grains['virtual'] = 'vmm' elif osdata['kernel'] == 'SunOS': if grains['virtual'] == 'LDOM': roles = [] for role in ('control', 'io', 'root', 'service'): subtype_cmd = '{0} -c current get -H -o value {1}-role'.format(cmd, role) ret = __salt__['cmd.run_all']('{0}'.format(subtype_cmd)) if ret['stdout'] == 'true': roles.append(role) if roles: grains['virtual_subtype'] = roles else: # Check if it's a "regular" zone. (i.e. Solaris 10/11 zone) zonename = salt.utils.path.which('zonename') if zonename: zone = __salt__['cmd.run']('{0}'.format(zonename)) if zone != 'global': grains['virtual'] = 'zone' # Check if it's a branded zone (i.e. Solaris 8/9 zone) if isdir('/.SUNWnative'): grains['virtual'] = 'zone' elif osdata['kernel'] == 'NetBSD': if sysctl: if 'QEMU Virtual CPU' in __salt__['cmd.run']( '{0} -n machdep.cpu_brand'.format(sysctl)): grains['virtual'] = 'kvm' elif 'invalid' not in __salt__['cmd.run']( '{0} -n machdep.xen.suspend'.format(sysctl)): grains['virtual'] = 'Xen PV DomU' elif 'VMware' in __salt__['cmd.run']( '{0} -n machdep.dmi.system-vendor'.format(sysctl)): grains['virtual'] = 'VMware' # NetBSD has Xen dom0 support elif __salt__['cmd.run']( '{0} -n machdep.idle-mechanism'.format(sysctl)) == 'xen': if os.path.isfile('/var/run/xenconsoled.pid'): grains['virtual_subtype'] = 'Xen Dom0' for command in failed_commands: log.info( "Although '%s' was found in path, the current user " 'cannot execute it. Grains output might not be ' 'accurate.', command ) return grains def _virtual_hv(osdata): ''' Returns detailed hypervisor information from sysfs Currently this seems to be used only by Xen ''' grains = {} # Bail early if we're not running on Xen try: if 'xen' not in osdata['virtual']: return grains except KeyError: return grains # Try to get the exact hypervisor version from sysfs try: version = {} for fn in ('major', 'minor', 'extra'): with salt.utils.files.fopen('/sys/hypervisor/version/{}'.format(fn), 'r') as fhr: version[fn] = salt.utils.stringutils.to_unicode(fhr.read().strip()) grains['virtual_hv_version'] = '{}.{}{}'.format(version['major'], version['minor'], version['extra']) grains['virtual_hv_version_info'] = [version['major'], version['minor'], version['extra']] except (IOError, OSError, KeyError): pass # Try to read and decode the supported feature set of the hypervisor # Based on https://github.com/brendangregg/Misc/blob/master/xen/xen-features.py # Table data from include/xen/interface/features.h xen_feature_table = {0: 'writable_page_tables', 1: 'writable_descriptor_tables', 2: 'auto_translated_physmap', 3: 'supervisor_mode_kernel', 4: 'pae_pgdir_above_4gb', 5: 'mmu_pt_update_preserve_ad', 7: 'gnttab_map_avail_bits', 8: 'hvm_callback_vector', 9: 'hvm_safe_pvclock', 10: 'hvm_pirqs', 11: 'dom0', 12: 'grant_map_identity', 13: 'memory_op_vnode_supported', 14: 'ARM_SMCCC_supported'} try: with salt.utils.files.fopen('/sys/hypervisor/properties/features', 'r') as fhr: features = salt.utils.stringutils.to_unicode(fhr.read().strip()) enabled_features = [] for bit, feat in six.iteritems(xen_feature_table): if int(features, 16) & (1 << bit): enabled_features.append(feat) grains['virtual_hv_features'] = features grains['virtual_hv_features_list'] = enabled_features except (IOError, OSError, KeyError): pass return grains def _ps(osdata): ''' Return the ps grain ''' grains = {} bsd_choices = ('FreeBSD', 'NetBSD', 'OpenBSD', 'MacOS') if osdata['os'] in bsd_choices: grains['ps'] = 'ps auxwww' elif osdata['os_family'] == 'Solaris': grains['ps'] = '/usr/ucb/ps auxwww' elif osdata['os'] == 'Windows': grains['ps'] = 'tasklist.exe' elif osdata.get('virtual', '') == 'openvzhn': grains['ps'] = ( 'ps -fH -p $(grep -l \"^envID:[[:space:]]*0\\$\" ' '/proc/[0-9]*/status | sed -e \"s=/proc/\\([0-9]*\\)/.*=\\1=\") ' '| awk \'{ $7=\"\"; print }\'' ) elif osdata['os_family'] == 'AIX': grains['ps'] = '/usr/bin/ps auxww' elif osdata['os_family'] == 'NILinuxRT': grains['ps'] = 'ps -o user,pid,ppid,tty,time,comm' else: grains['ps'] = 'ps -efHww' return grains def _clean_value(key, val): ''' Clean out well-known bogus values. If it isn't clean (for example has value 'None'), return None. Otherwise, return the original value. NOTE: This logic also exists in the smbios module. This function is for use when not using smbios to retrieve the value. ''' if (val is None or not val or re.match('none', val, flags=re.IGNORECASE)): return None elif 'uuid' in key: # Try each version (1-5) of RFC4122 to check if it's actually a UUID for uuidver in range(1, 5): try: uuid.UUID(val, version=uuidver) return val except ValueError: continue log.trace('HW %s value %s is an invalid UUID', key, val.replace('\n', ' ')) return None elif re.search('serial|part|version', key): # 'To be filled by O.E.M. # 'Not applicable' etc. # 'Not specified' etc. # 0000000, 1234567 etc. # begone! if (re.match(r'^[0]+$', val) or re.match(r'[0]?1234567[8]?[9]?[0]?', val) or re.search(r'sernum|part[_-]?number|specified|filled|applicable', val, flags=re.IGNORECASE)): return None elif re.search('asset|manufacturer', key): # AssetTag0. Manufacturer04. Begone. if re.search(r'manufacturer|to be filled|available|asset|^no(ne|t)', val, flags=re.IGNORECASE): return None else: # map unspecified, undefined, unknown & whatever to None if (re.search(r'to be filled', val, flags=re.IGNORECASE) or re.search(r'un(known|specified)|no(t|ne)? (asset|provided|defined|available|present|specified)', val, flags=re.IGNORECASE)): return None return val def _windows_platform_data(): ''' Use the platform module for as much as we can. ''' # Provides: # kernelrelease # kernelversion # osversion # osrelease # osservicepack # osmanufacturer # manufacturer # productname # biosversion # serialnumber # osfullname # timezone # windowsdomain # windowsdomaintype # motherboard.productname # motherboard.serialnumber # virtual if not HAS_WMI: return {} with salt.utils.winapi.Com(): wmi_c = wmi.WMI() # http://msdn.microsoft.com/en-us/library/windows/desktop/aa394102%28v=vs.85%29.aspx systeminfo = wmi_c.Win32_ComputerSystem()[0] # https://msdn.microsoft.com/en-us/library/aa394239(v=vs.85).aspx osinfo = wmi_c.Win32_OperatingSystem()[0] # http://msdn.microsoft.com/en-us/library/windows/desktop/aa394077(v=vs.85).aspx biosinfo = wmi_c.Win32_BIOS()[0] # http://msdn.microsoft.com/en-us/library/windows/desktop/aa394498(v=vs.85).aspx timeinfo = wmi_c.Win32_TimeZone()[0] # http://msdn.microsoft.com/en-us/library/windows/desktop/aa394072(v=vs.85).aspx motherboard = {'product': None, 'serial': None} try: motherboardinfo = wmi_c.Win32_BaseBoard()[0] motherboard['product'] = motherboardinfo.Product motherboard['serial'] = motherboardinfo.SerialNumber except IndexError: log.debug('Motherboard info not available on this system') os_release = platform.release() kernel_version = platform.version() info = salt.utils.win_osinfo.get_os_version_info() net_info = salt.utils.win_osinfo.get_join_info() service_pack = None if info['ServicePackMajor'] > 0: service_pack = ''.join(['SP', six.text_type(info['ServicePackMajor'])]) # This creates the osrelease grain based on the Windows Operating # System Product Name. As long as Microsoft maintains a similar format # this should be future proof version = 'Unknown' release = '' if 'Server' in osinfo.Caption: for item in osinfo.Caption.split(' '): # If it's all digits, then it's version if re.match(r'\d+', item): version = item # If it starts with R and then numbers, it's the release # ie: R2 if re.match(r'^R\d+$', item): release = item os_release = '{0}Server{1}'.format(version, release) else: for item in osinfo.Caption.split(' '): # If it's a number, decimal number, Thin or Vista, then it's the # version if re.match(r'^(\d+(\.\d+)?)|Thin|Vista$', item): version = item os_release = version grains = { 'kernelrelease': _clean_value('kernelrelease', osinfo.Version), 'kernelversion': _clean_value('kernelversion', kernel_version), 'osversion': _clean_value('osversion', osinfo.Version), 'osrelease': _clean_value('osrelease', os_release), 'osservicepack': _clean_value('osservicepack', service_pack), 'osmanufacturer': _clean_value('osmanufacturer', osinfo.Manufacturer), 'manufacturer': _clean_value('manufacturer', systeminfo.Manufacturer), 'productname': _clean_value('productname', systeminfo.Model), # bios name had a bunch of whitespace appended to it in my testing # 'PhoenixBIOS 4.0 Release 6.0 ' 'biosversion': _clean_value('biosversion', biosinfo.Name.strip()), 'serialnumber': _clean_value('serialnumber', biosinfo.SerialNumber), 'osfullname': _clean_value('osfullname', osinfo.Caption), 'timezone': _clean_value('timezone', timeinfo.Description), 'windowsdomain': _clean_value('windowsdomain', net_info['Domain']), 'windowsdomaintype': _clean_value('windowsdomaintype', net_info['DomainType']), 'motherboard': { 'productname': _clean_value('motherboard.productname', motherboard['product']), 'serialnumber': _clean_value('motherboard.serialnumber', motherboard['serial']), } } # test for virtualized environments # I only had VMware available so the rest are unvalidated if 'VRTUAL' in biosinfo.Version: # (not a typo) grains['virtual'] = 'HyperV' elif 'A M I' in biosinfo.Version: grains['virtual'] = 'VirtualPC' elif 'VMware' in systeminfo.Model: grains['virtual'] = 'VMware' elif 'VirtualBox' in systeminfo.Model: grains['virtual'] = 'VirtualBox' elif 'Xen' in biosinfo.Version: grains['virtual'] = 'Xen' if 'HVM domU' in systeminfo.Model: grains['virtual_subtype'] = 'HVM domU' elif 'OpenStack' in systeminfo.Model: grains['virtual'] = 'OpenStack' return grains def _osx_platform_data(): ''' Additional data for macOS systems Returns: A dictionary containing values for the following: - model_name - boot_rom_version - smc_version - system_serialnumber ''' cmd = 'system_profiler SPHardwareDataType' hardware = __salt__['cmd.run'](cmd) grains = {} for line in hardware.splitlines(): field_name, _, field_val = line.partition(': ') if field_name.strip() == "Model Name": key = 'model_name' grains[key] = _clean_value(key, field_val) if field_name.strip() == "Boot ROM Version": key = 'boot_rom_version' grains[key] = _clean_value(key, field_val) if field_name.strip() == "SMC Version (system)": key = 'smc_version' grains[key] = _clean_value(key, field_val) if field_name.strip() == "Serial Number (system)": key = 'system_serialnumber' grains[key] = _clean_value(key, field_val) return grains def id_(): ''' Return the id ''' return {'id': __opts__.get('id', '')} _REPLACE_LINUX_RE = re.compile(r'\W(?:gnu/)?linux', re.IGNORECASE) # This maps (at most) the first ten characters (no spaces, lowercased) of # 'osfullname' to the 'os' grain that Salt traditionally uses. # Please see os_data() and _supported_dists. # If your system is not detecting properly it likely needs an entry here. _OS_NAME_MAP = { 'redhatente': 'RedHat', 'gentoobase': 'Gentoo', 'archarm': 'Arch ARM', 'arch': 'Arch', 'debian': 'Debian', 'raspbian': 'Raspbian', 'fedoraremi': 'Fedora', 'chapeau': 'Chapeau', 'korora': 'Korora', 'amazonami': 'Amazon', 'alt': 'ALT', 'enterprise': 'OEL', 'oracleserv': 'OEL', 'cloudserve': 'CloudLinux', 'cloudlinux': 'CloudLinux', 'pidora': 'Fedora', 'scientific': 'ScientificLinux', 'synology': 'Synology', 'nilrt': 'NILinuxRT', 'poky': 'Poky', 'manjaro': 'Manjaro', 'manjarolin': 'Manjaro', 'univention': 'Univention', 'antergos': 'Antergos', 'sles': 'SUSE', 'void': 'Void', 'slesexpand': 'RES', 'linuxmint': 'Mint', 'neon': 'KDE neon', } # Map the 'os' grain to the 'os_family' grain # These should always be capitalized entries as the lookup comes # post-_OS_NAME_MAP. If your system is having trouble with detection, please # make sure that the 'os' grain is capitalized and working correctly first. _OS_FAMILY_MAP = { 'Ubuntu': 'Debian', 'Fedora': 'RedHat', 'Chapeau': 'RedHat', 'Korora': 'RedHat', 'FedBerry': 'RedHat', 'CentOS': 'RedHat', 'GoOSe': 'RedHat', 'Scientific': 'RedHat', 'Amazon': 'RedHat', 'CloudLinux': 'RedHat', 'OVS': 'RedHat', 'OEL': 'RedHat', 'XCP': 'RedHat', 'XCP-ng': 'RedHat', 'XenServer': 'RedHat', 'RES': 'RedHat', 'Sangoma': 'RedHat', 'Mandrake': 'Mandriva', 'ESXi': 'VMware', 'Mint': 'Debian', 'VMwareESX': 'VMware', 'Bluewhite64': 'Bluewhite', 'Slamd64': 'Slackware', 'SLES': 'Suse', 'SUSE Enterprise Server': 'Suse', 'SUSE Enterprise Server': 'Suse', 'SLED': 'Suse', 'openSUSE': 'Suse', 'SUSE': 'Suse', 'openSUSE Leap': 'Suse', 'openSUSE Tumbleweed': 'Suse', 'SLES_SAP': 'Suse', 'Solaris': 'Solaris', 'SmartOS': 'Solaris', 'OmniOS': 'Solaris', 'OpenIndiana Development': 'Solaris', 'OpenIndiana': 'Solaris', 'OpenSolaris Development': 'Solaris', 'OpenSolaris': 'Solaris', 'Oracle Solaris': 'Solaris', 'Arch ARM': 'Arch', 'Manjaro': 'Arch', 'Antergos': 'Arch', 'ALT': 'RedHat', 'Trisquel': 'Debian', 'GCEL': 'Debian', 'Linaro': 'Debian', 'elementary OS': 'Debian', 'elementary': 'Debian', 'Univention': 'Debian', 'ScientificLinux': 'RedHat', 'Raspbian': 'Debian', 'Devuan': 'Debian', 'antiX': 'Debian', 'Kali': 'Debian', 'neon': 'Debian', 'Cumulus': 'Debian', 'Deepin': 'Debian', 'NILinuxRT': 'NILinuxRT', 'KDE neon': 'Debian', 'Void': 'Void', 'IDMS': 'Debian', 'Funtoo': 'Gentoo', 'AIX': 'AIX', 'TurnKey': 'Debian', } # Matches any possible format: # DISTRIB_ID="Ubuntu" # DISTRIB_ID='Mageia' # DISTRIB_ID=Fedora # DISTRIB_RELEASE='10.10' # DISTRIB_CODENAME='squeeze' # DISTRIB_DESCRIPTION='Ubuntu 10.10' _LSB_REGEX = re.compile(( '^(DISTRIB_(?:ID|RELEASE|CODENAME|DESCRIPTION))=(?:\'|")?' '([\\w\\s\\.\\-_]+)(?:\'|")?' )) def _linux_bin_exists(binary): ''' Does a binary exist in linux (depends on which, type, or whereis) ''' for search_cmd in ('which', 'type -ap'): try: return __salt__['cmd.retcode']( '{0} {1}'.format(search_cmd, binary) ) == 0 except salt.exceptions.CommandExecutionError: pass try: return len(__salt__['cmd.run_all']( 'whereis -b {0}'.format(binary) )['stdout'].split()) > 1 except salt.exceptions.CommandExecutionError: return False def _get_interfaces(): ''' Provide a dict of the connected interfaces and their ip addresses ''' global _INTERFACES if not _INTERFACES: _INTERFACES = salt.utils.network.interfaces() return _INTERFACES def _parse_lsb_release(): ret = {} try: log.trace('Attempting to parse /etc/lsb-release') with salt.utils.files.fopen('/etc/lsb-release') as ifile: for line in ifile: try: key, value = _LSB_REGEX.match(line.rstrip('\n')).groups()[:2] except AttributeError: pass else: # Adds lsb_distrib_{id,release,codename,description} ret['lsb_{0}'.format(key.lower())] = value.rstrip() except (IOError, OSError) as exc: log.trace('Failed to parse /etc/lsb-release: %s', exc) return ret def _parse_os_release(*os_release_files): ''' Parse os-release and return a parameter dictionary See http://www.freedesktop.org/software/systemd/man/os-release.html for specification of the file format. ''' ret = {} for filename in os_release_files: try: with salt.utils.files.fopen(filename) as ifile: regex = re.compile('^([\\w]+)=(?:\'|")?(.*?)(?:\'|")?$') for line in ifile: match = regex.match(line.strip()) if match: # Shell special characters ("$", quotes, backslash, # backtick) are escaped with backslashes ret[match.group(1)] = re.sub( r'\\([$"\'\\`])', r'\1', match.group(2) ) break except (IOError, OSError): pass return ret def _parse_cpe_name(cpe): ''' Parse CPE_NAME data from the os-release Info: https://csrc.nist.gov/projects/security-content-automation-protocol/scap-specifications/cpe :param cpe: :return: ''' part = { 'o': 'operating system', 'h': 'hardware', 'a': 'application', } ret = {} cpe = (cpe or '').split(':') if len(cpe) > 4 and cpe[0] == 'cpe': if cpe[1].startswith('/'): # WFN to URI ret['vendor'], ret['product'], ret['version'] = cpe[2:5] ret['phase'] = cpe[5] if len(cpe) > 5 else None ret['part'] = part.get(cpe[1][1:]) elif len(cpe) == 13 and cpe[1] == '2.3': # WFN to a string ret['vendor'], ret['product'], ret['version'], ret['phase'] = [x if x != '*' else None for x in cpe[3:7]] ret['part'] = part.get(cpe[2]) return ret def os_data(): ''' Return grains pertaining to the operating system ''' grains = { 'num_gpus': 0, 'gpus': [], } # Windows Server 2008 64-bit # ('Windows', 'MINIONNAME', '2008ServerR2', '6.1.7601', 'AMD64', # 'Intel64 Fam ily 6 Model 23 Stepping 6, GenuineIntel') # Ubuntu 10.04 # ('Linux', 'MINIONNAME', '2.6.32-38-server', # '#83-Ubuntu SMP Wed Jan 4 11:26:59 UTC 2012', 'x86_64', '') # pylint: disable=unpacking-non-sequence (grains['kernel'], grains['nodename'], grains['kernelrelease'], grains['kernelversion'], grains['cpuarch'], _) = platform.uname() # pylint: enable=unpacking-non-sequence if salt.utils.platform.is_proxy(): grains['kernel'] = 'proxy' grains['kernelrelease'] = 'proxy' grains['kernelversion'] = 'proxy' grains['osrelease'] = 'proxy' grains['os'] = 'proxy' grains['os_family'] = 'proxy' grains['osfullname'] = 'proxy' elif salt.utils.platform.is_windows(): grains['os'] = 'Windows' grains['os_family'] = 'Windows' grains.update(_memdata(grains)) grains.update(_windows_platform_data()) grains.update(_windows_cpudata()) grains.update(_windows_virtual(grains)) grains.update(_ps(grains)) if 'Server' in grains['osrelease']: osrelease_info = grains['osrelease'].split('Server', 1) osrelease_info[1] = osrelease_info[1].lstrip('R') else: osrelease_info = grains['osrelease'].split('.') for idx, value in enumerate(osrelease_info): if not value.isdigit(): continue osrelease_info[idx] = int(value) grains['osrelease_info'] = tuple(osrelease_info) grains['osfinger'] = '{os}-{ver}'.format( os=grains['os'], ver=grains['osrelease']) grains['init'] = 'Windows' return grains elif salt.utils.platform.is_linux(): # Add SELinux grain, if you have it if _linux_bin_exists('selinuxenabled'): log.trace('Adding selinux grains') grains['selinux'] = {} grains['selinux']['enabled'] = __salt__['cmd.retcode']( 'selinuxenabled' ) == 0 if _linux_bin_exists('getenforce'): grains['selinux']['enforced'] = __salt__['cmd.run']( 'getenforce' ).strip() # Add systemd grain, if you have it if _linux_bin_exists('systemctl') and _linux_bin_exists('localectl'): log.trace('Adding systemd grains') grains['systemd'] = {} systemd_info = __salt__['cmd.run']( 'systemctl --version' ).splitlines() grains['systemd']['version'] = systemd_info[0].split()[1] grains['systemd']['features'] = systemd_info[1] # Add init grain grains['init'] = 'unknown' log.trace('Adding init grain') try: os.stat('/run/systemd/system') grains['init'] = 'systemd' except (OSError, IOError): try: with salt.utils.files.fopen('/proc/1/cmdline') as fhr: init_cmdline = fhr.read().replace('\x00', ' ').split() except (IOError, OSError): pass else: try: init_bin = salt.utils.path.which(init_cmdline[0]) except IndexError: # Emtpy init_cmdline init_bin = None log.warning('Unable to fetch data from /proc/1/cmdline') if init_bin is not None and init_bin.endswith('bin/init'): supported_inits = (b'upstart', b'sysvinit', b'systemd') edge_len = max(len(x) for x in supported_inits) - 1 try: buf_size = __opts__['file_buffer_size'] except KeyError: # Default to the value of file_buffer_size for the minion buf_size = 262144 try: with salt.utils.files.fopen(init_bin, 'rb') as fp_: edge = b'' buf = fp_.read(buf_size).lower() while buf: buf = edge + buf for item in supported_inits: if item in buf: if six.PY3: item = item.decode('utf-8') grains['init'] = item buf = b'' break edge = buf[-edge_len:] buf = fp_.read(buf_size).lower() except (IOError, OSError) as exc: log.error( 'Unable to read from init_bin (%s): %s', init_bin, exc ) elif salt.utils.path.which('supervisord') in init_cmdline: grains['init'] = 'supervisord' elif salt.utils.path.which('dumb-init') in init_cmdline: # https://github.com/Yelp/dumb-init grains['init'] = 'dumb-init' elif salt.utils.path.which('tini') in init_cmdline: # https://github.com/krallin/tini grains['init'] = 'tini' elif init_cmdline == ['runit']: grains['init'] = 'runit' elif '/sbin/my_init' in init_cmdline: # Phusion Base docker container use runit for srv mgmt, but # my_init as pid1 grains['init'] = 'runit' else: log.debug( 'Could not determine init system from command line: (%s)', ' '.join(init_cmdline) ) # Add lsb grains on any distro with lsb-release. Note that this import # can fail on systems with lsb-release installed if the system package # does not install the python package for the python interpreter used by # Salt (i.e. python2 or python3) try: log.trace('Getting lsb_release distro information') import lsb_release # pylint: disable=import-error release = lsb_release.get_distro_information() for key, value in six.iteritems(release): key = key.lower() lsb_param = 'lsb_{0}{1}'.format( '' if key.startswith('distrib_') else 'distrib_', key ) grains[lsb_param] = value # Catch a NameError to workaround possible breakage in lsb_release # See https://github.com/saltstack/salt/issues/37867 except (ImportError, NameError): # if the python library isn't available, try to parse # /etc/lsb-release using regex log.trace('lsb_release python bindings not available') grains.update(_parse_lsb_release()) if grains.get('lsb_distrib_description', '').lower().startswith('antergos'): # Antergos incorrectly configures their /etc/lsb-release, # setting the DISTRIB_ID to "Arch". This causes the "os" grain # to be incorrectly set to "Arch". grains['osfullname'] = 'Antergos Linux' elif 'lsb_distrib_id' not in grains: log.trace( 'Failed to get lsb_distrib_id, trying to parse os-release' ) os_release = _parse_os_release('/etc/os-release', '/usr/lib/os-release') if os_release: if 'NAME' in os_release: grains['lsb_distrib_id'] = os_release['NAME'].strip() if 'VERSION_ID' in os_release: grains['lsb_distrib_release'] = os_release['VERSION_ID'] if 'VERSION_CODENAME' in os_release: grains['lsb_distrib_codename'] = os_release['VERSION_CODENAME'] elif 'PRETTY_NAME' in os_release: codename = os_release['PRETTY_NAME'] # https://github.com/saltstack/salt/issues/44108 if os_release['ID'] == 'debian': codename_match = re.search(r'\((\w+)\)$', codename) if codename_match: codename = codename_match.group(1) grains['lsb_distrib_codename'] = codename if 'CPE_NAME' in os_release: cpe = _parse_cpe_name(os_release['CPE_NAME']) if not cpe: log.error('Broken CPE_NAME format in /etc/os-release!') elif cpe.get('vendor', '').lower() in ['suse', 'opensuse']: grains['os'] = "SUSE" # openSUSE `osfullname` grain normalization if os_release.get("NAME") == "openSUSE Leap": grains['osfullname'] = "Leap" elif os_release.get("VERSION") == "Tumbleweed": grains['osfullname'] = os_release["VERSION"] # Override VERSION_ID, if CPE_NAME around if cpe.get('version') and cpe.get('vendor') == 'opensuse': # Keep VERSION_ID for SLES grains['lsb_distrib_release'] = cpe['version'] elif os.path.isfile('/etc/SuSE-release'): log.trace('Parsing distrib info from /etc/SuSE-release') grains['lsb_distrib_id'] = 'SUSE' version = '' patch = '' with salt.utils.files.fopen('/etc/SuSE-release') as fhr: for line in fhr: if 'enterprise' in line.lower(): grains['lsb_distrib_id'] = 'SLES' grains['lsb_distrib_codename'] = re.sub(r'\(.+\)', '', line).strip() elif 'version' in line.lower(): version = re.sub(r'[^0-9]', '', line) elif 'patchlevel' in line.lower(): patch = re.sub(r'[^0-9]', '', line) grains['lsb_distrib_release'] = version if patch: grains['lsb_distrib_release'] += '.' + patch patchstr = 'SP' + patch if grains['lsb_distrib_codename'] and patchstr not in grains['lsb_distrib_codename']: grains['lsb_distrib_codename'] += ' ' + patchstr if not grains.get('lsb_distrib_codename'): grains['lsb_distrib_codename'] = 'n.a' elif os.path.isfile('/etc/altlinux-release'): log.trace('Parsing distrib info from /etc/altlinux-release') # ALT Linux grains['lsb_distrib_id'] = 'altlinux' with salt.utils.files.fopen('/etc/altlinux-release') as ifile: # This file is symlinked to from: # /etc/fedora-release # /etc/redhat-release # /etc/system-release for line in ifile: # ALT Linux Sisyphus (unstable) comps = line.split() if comps[0] == 'ALT': grains['lsb_distrib_release'] = comps[2] grains['lsb_distrib_codename'] = \ comps[3].replace('(', '').replace(')', '') elif os.path.isfile('/etc/centos-release'): log.trace('Parsing distrib info from /etc/centos-release') # Maybe CentOS Linux; could also be SUSE Expanded Support. # SUSE ES has both, centos-release and redhat-release. if os.path.isfile('/etc/redhat-release'): with salt.utils.files.fopen('/etc/redhat-release') as ifile: for line in ifile: if "red hat enterprise linux server" in line.lower(): # This is a SUSE Expanded Support Rhel installation grains['lsb_distrib_id'] = 'RedHat' break grains.setdefault('lsb_distrib_id', 'CentOS') with salt.utils.files.fopen('/etc/centos-release') as ifile: for line in ifile: # Need to pull out the version and codename # in the case of custom content in /etc/centos-release find_release = re.compile(r'\d+\.\d+') find_codename = re.compile(r'(?<=\()(.*?)(?=\))') release = find_release.search(line) codename = find_codename.search(line) if release is not None: grains['lsb_distrib_release'] = release.group() if codename is not None: grains['lsb_distrib_codename'] = codename.group() elif os.path.isfile('/etc.defaults/VERSION') \ and os.path.isfile('/etc.defaults/synoinfo.conf'): grains['osfullname'] = 'Synology' log.trace( 'Parsing Synology distrib info from /etc/.defaults/VERSION' ) with salt.utils.files.fopen('/etc.defaults/VERSION', 'r') as fp_: synoinfo = {} for line in fp_: try: key, val = line.rstrip('\n').split('=') except ValueError: continue if key in ('majorversion', 'minorversion', 'buildnumber'): synoinfo[key] = val.strip('"') if len(synoinfo) != 3: log.warning( 'Unable to determine Synology version info. ' 'Please report this, as it is likely a bug.' ) else: grains['osrelease'] = ( '{majorversion}.{minorversion}-{buildnumber}' .format(**synoinfo) ) # Use the already intelligent platform module to get distro info # (though apparently it's not intelligent enough to strip quotes) log.trace( 'Getting OS name, release, and codename from ' 'distro.linux_distribution()' ) (osname, osrelease, oscodename) = \ [x.strip('"').strip("'") for x in linux_distribution(supported_dists=_supported_dists)] # Try to assign these three names based on the lsb info, they tend to # be more accurate than what python gets from /etc/DISTRO-release. # It's worth noting that Ubuntu has patched their Python distribution # so that linux_distribution() does the /etc/lsb-release parsing, but # we do it anyway here for the sake for full portability. if 'osfullname' not in grains: # If NI Linux RT distribution, set the grains['osfullname'] to 'nilrt' if grains.get('lsb_distrib_id', '').lower().startswith('nilrt'): grains['osfullname'] = 'nilrt' else: grains['osfullname'] = grains.get('lsb_distrib_id', osname).strip() if 'osrelease' not in grains: # NOTE: This is a workaround for CentOS 7 os-release bug # https://bugs.centos.org/view.php?id=8359 # /etc/os-release contains no minor distro release number so we fall back to parse # /etc/centos-release file instead. # Commit introducing this comment should be reverted after the upstream bug is released. if 'CentOS Linux 7' in grains.get('lsb_distrib_codename', ''): grains.pop('lsb_distrib_release', None) grains['osrelease'] = grains.get('lsb_distrib_release', osrelease).strip() grains['oscodename'] = grains.get('lsb_distrib_codename', '').strip() or oscodename if 'Red Hat' in grains['oscodename']: grains['oscodename'] = oscodename distroname = _REPLACE_LINUX_RE.sub('', grains['osfullname']).strip() # return the first ten characters with no spaces, lowercased shortname = distroname.replace(' ', '').lower()[:10] # this maps the long names from the /etc/DISTRO-release files to the # traditional short names that Salt has used. if 'os' not in grains: grains['os'] = _OS_NAME_MAP.get(shortname, distroname) grains.update(_linux_cpudata()) grains.update(_linux_gpu_data()) elif grains['kernel'] == 'SunOS': if salt.utils.platform.is_smartos(): # See https://github.com/joyent/smartos-live/issues/224 if HAS_UNAME: uname_v = os.uname()[3] # format: joyent_20161101T004406Z else: uname_v = os.name uname_v = uname_v[uname_v.index('_')+1:] grains['os'] = grains['osfullname'] = 'SmartOS' # store a parsed version of YYYY.MM.DD as osrelease grains['osrelease'] = ".".join([ uname_v.split('T')[0][0:4], uname_v.split('T')[0][4:6], uname_v.split('T')[0][6:8], ]) # store a untouched copy of the timestamp in osrelease_stamp grains['osrelease_stamp'] = uname_v elif os.path.isfile('/etc/release'): with salt.utils.files.fopen('/etc/release', 'r') as fp_: rel_data = fp_.read() try: release_re = re.compile( r'((?:Open|Oracle )?Solaris|OpenIndiana|OmniOS) (Development)?' r'\s*(\d+\.?\d*|v\d+)\s?[A-Z]*\s?(r\d+|\d+\/\d+|oi_\S+|snv_\S+)?' ) osname, development, osmajorrelease, osminorrelease = release_re.search(rel_data).groups() except AttributeError: # Set a blank osrelease grain and fallback to 'Solaris' # as the 'os' grain. grains['os'] = grains['osfullname'] = 'Solaris' grains['osrelease'] = '' else: if development is not None: osname = ' '.join((osname, development)) if HAS_UNAME: uname_v = os.uname()[3] else: uname_v = os.name grains['os'] = grains['osfullname'] = osname if osname in ['Oracle Solaris'] and uname_v.startswith(osmajorrelease): # Oracla Solars 11 and up have minor version in uname grains['osrelease'] = uname_v elif osname in ['OmniOS']: # OmniOS osrelease = [] osrelease.append(osmajorrelease[1:]) osrelease.append(osminorrelease[1:]) grains['osrelease'] = ".".join(osrelease) grains['osrelease_stamp'] = uname_v else: # Sun Solaris 10 and earlier/comparable osrelease = [] osrelease.append(osmajorrelease) if osminorrelease: osrelease.append(osminorrelease) grains['osrelease'] = ".".join(osrelease) grains['osrelease_stamp'] = uname_v grains.update(_sunos_cpudata()) elif grains['kernel'] == 'VMkernel': grains['os'] = 'ESXi' elif grains['kernel'] == 'Darwin': osrelease = __salt__['cmd.run']('sw_vers -productVersion') osname = __salt__['cmd.run']('sw_vers -productName') osbuild = __salt__['cmd.run']('sw_vers -buildVersion') grains['os'] = 'MacOS' grains['os_family'] = 'MacOS' grains['osfullname'] = "{0} {1}".format(osname, osrelease) grains['osrelease'] = osrelease grains['osbuild'] = osbuild grains['init'] = 'launchd' grains.update(_bsd_cpudata(grains)) grains.update(_osx_gpudata()) grains.update(_osx_platform_data()) elif grains['kernel'] == 'AIX': osrelease = __salt__['cmd.run']('oslevel') osrelease_techlevel = __salt__['cmd.run']('oslevel -r') osname = __salt__['cmd.run']('uname') grains['os'] = 'AIX' grains['osfullname'] = osname grains['osrelease'] = osrelease grains['osrelease_techlevel'] = osrelease_techlevel grains.update(_aix_cpudata()) else: grains['os'] = grains['kernel'] if grains['kernel'] == 'FreeBSD': try: grains['osrelease'] = __salt__['cmd.run']('freebsd-version -u').split('-')[0] except salt.exceptions.CommandExecutionError: # freebsd-version was introduced in 10.0. # derive osrelease from kernelversion prior to that grains['osrelease'] = grains['kernelrelease'].split('-')[0] grains.update(_bsd_cpudata(grains)) if grains['kernel'] in ('OpenBSD', 'NetBSD'): grains.update(_bsd_cpudata(grains)) grains['osrelease'] = grains['kernelrelease'].split('-')[0] if grains['kernel'] == 'NetBSD': grains.update(_netbsd_gpu_data()) if not grains['os']: grains['os'] = 'Unknown {0}'.format(grains['kernel']) grains['os_family'] = 'Unknown' else: # this assigns family names based on the os name # family defaults to the os name if not found grains['os_family'] = _OS_FAMILY_MAP.get(grains['os'], grains['os']) # Build the osarch grain. This grain will be used for platform-specific # considerations such as package management. Fall back to the CPU # architecture. if grains.get('os_family') == 'Debian': osarch = __salt__['cmd.run']('dpkg --print-architecture').strip() elif grains.get('os_family') in ['RedHat', 'Suse']: osarch = salt.utils.pkg.rpm.get_osarch() elif grains.get('os_family') in ('NILinuxRT', 'Poky'): archinfo = {} for line in __salt__['cmd.run']('opkg print-architecture').splitlines(): if line.startswith('arch'): _, arch, priority = line.split() archinfo[arch.strip()] = int(priority.strip()) # Return osarch in priority order (higher to lower) osarch = sorted(archinfo, key=archinfo.get, reverse=True) else: osarch = grains['cpuarch'] grains['osarch'] = osarch grains.update(_memdata(grains)) # Get the hardware and bios data grains.update(_hw_data(grains)) # Load the virtual machine info grains.update(_virtual(grains)) grains.update(_virtual_hv(grains)) grains.update(_ps(grains)) if grains.get('osrelease', ''): osrelease_info = grains['osrelease'].split('.') for idx, value in enumerate(osrelease_info): if not value.isdigit(): continue osrelease_info[idx] = int(value) grains['osrelease_info'] = tuple(osrelease_info) try: grains['osmajorrelease'] = int(grains['osrelease_info'][0]) except (IndexError, TypeError, ValueError): log.debug( 'Unable to derive osmajorrelease from osrelease_info \'%s\'. ' 'The osmajorrelease grain will not be set.', grains['osrelease_info'] ) os_name = grains['os' if grains.get('os') in ( 'Debian', 'FreeBSD', 'OpenBSD', 'NetBSD', 'Mac', 'Raspbian') else 'osfullname'] grains['osfinger'] = '{0}-{1}'.format( os_name, grains['osrelease'] if os_name in ('Ubuntu',) else grains['osrelease_info'][0]) return grains def locale_info(): ''' Provides defaultlanguage defaultencoding ''' grains = {} grains['locale_info'] = {} if salt.utils.platform.is_proxy(): return grains try: ( grains['locale_info']['defaultlanguage'], grains['locale_info']['defaultencoding'] ) = locale.getdefaultlocale() except Exception: # locale.getdefaultlocale can ValueError!! Catch anything else it # might do, per #2205 grains['locale_info']['defaultlanguage'] = 'unknown' grains['locale_info']['defaultencoding'] = 'unknown' grains['locale_info']['detectedencoding'] = __salt_system_encoding__ if _DATEUTIL_TZ: grains['locale_info']['timezone'] = datetime.datetime.now(dateutil.tz.tzlocal()).tzname() return grains def hostname(): ''' Return fqdn, hostname, domainname ''' # This is going to need some work # Provides: # fqdn # host # localhost # domain global __FQDN__ grains = {} if salt.utils.platform.is_proxy(): return grains grains['localhost'] = socket.gethostname() if __FQDN__ is None: __FQDN__ = salt.utils.network.get_fqhostname() # On some distros (notably FreeBSD) if there is no hostname set # salt.utils.network.get_fqhostname() will return None. # In this case we punt and log a message at error level, but force the # hostname and domain to be localhost.localdomain # Otherwise we would stacktrace below if __FQDN__ is None: # still! log.error('Having trouble getting a hostname. Does this machine have its hostname and domain set properly?') __FQDN__ = 'localhost.localdomain' grains['fqdn'] = __FQDN__ (grains['host'], grains['domain']) = grains['fqdn'].partition('.')[::2] return grains def append_domain(): ''' Return append_domain if set ''' grain = {} if salt.utils.platform.is_proxy(): return grain if 'append_domain' in __opts__: grain['append_domain'] = __opts__['append_domain'] return grain def fqdns(): ''' Return all known FQDNs for the system by enumerating all interfaces and then trying to reverse resolve them (excluding 'lo' interface). ''' # Provides: # fqdns grains = {} fqdns = set() addresses = salt.utils.network.ip_addrs(include_loopback=False, interface_data=_get_interfaces()) addresses.extend(salt.utils.network.ip_addrs6(include_loopback=False, interface_data=_get_interfaces())) err_message = 'Exception during resolving address: %s' for ip in addresses: try: name, aliaslist, addresslist = socket.gethostbyaddr(ip) fqdns.update([socket.getfqdn(name)] + [als for als in aliaslist if salt.utils.network.is_fqdn(als)]) except socket.herror as err: if err.errno == 0: # No FQDN for this IP address, so we don't need to know this all the time. log.debug("Unable to resolve address %s: %s", ip, err) else: log.error(err_message, err) except (socket.error, socket.gaierror, socket.timeout) as err: log.error(err_message, err) return {"fqdns": sorted(list(fqdns))} def ip_fqdn(): ''' Return ip address and FQDN grains ''' if salt.utils.platform.is_proxy(): return {} ret = {} ret['ipv4'] = salt.utils.network.ip_addrs(include_loopback=True) ret['ipv6'] = salt.utils.network.ip_addrs6(include_loopback=True) _fqdn = hostname()['fqdn'] for socket_type, ipv_num in ((socket.AF_INET, '4'), (socket.AF_INET6, '6')): key = 'fqdn_ip' + ipv_num if not ret['ipv' + ipv_num]: ret[key] = [] else: try: start_time = datetime.datetime.utcnow() info = socket.getaddrinfo(_fqdn, None, socket_type) ret[key] = list(set(item[4][0] for item in info)) except socket.error: timediff = datetime.datetime.utcnow() - start_time if timediff.seconds > 5 and __opts__['__role'] == 'master': log.warning( 'Unable to find IPv%s record for "%s" causing a %s ' 'second timeout when rendering grains. Set the dns or ' '/etc/hosts for IPv%s to clear this.', ipv_num, _fqdn, timediff, ipv_num ) ret[key] = [] return ret def ip_interfaces(): ''' Provide a dict of the connected interfaces and their ip addresses The addresses will be passed as a list for each interface ''' # Provides: # ip_interfaces if salt.utils.platform.is_proxy(): return {} ret = {} ifaces = _get_interfaces() for face in ifaces: iface_ips = [] for inet in ifaces[face].get('inet', []): if 'address' in inet: iface_ips.append(inet['address']) for inet in ifaces[face].get('inet6', []): if 'address' in inet: iface_ips.append(inet['address']) for secondary in ifaces[face].get('secondary', []): if 'address' in secondary: iface_ips.append(secondary['address']) ret[face] = iface_ips return {'ip_interfaces': ret} def ip4_interfaces(): ''' Provide a dict of the connected interfaces and their ip4 addresses The addresses will be passed as a list for each interface ''' # Provides: # ip_interfaces if salt.utils.platform.is_proxy(): return {} ret = {} ifaces = _get_interfaces() for face in ifaces: iface_ips = [] for inet in ifaces[face].get('inet', []): if 'address' in inet: iface_ips.append(inet['address']) for secondary in ifaces[face].get('secondary', []): if 'address' in secondary: iface_ips.append(secondary['address']) ret[face] = iface_ips return {'ip4_interfaces': ret} def ip6_interfaces(): ''' Provide a dict of the connected interfaces and their ip6 addresses The addresses will be passed as a list for each interface ''' # Provides: # ip_interfaces if salt.utils.platform.is_proxy(): return {} ret = {} ifaces = _get_interfaces() for face in ifaces: iface_ips = [] for inet in ifaces[face].get('inet6', []): if 'address' in inet: iface_ips.append(inet['address']) for secondary in ifaces[face].get('secondary', []): if 'address' in secondary: iface_ips.append(secondary['address']) ret[face] = iface_ips return {'ip6_interfaces': ret} def dns(): ''' Parse the resolver configuration file .. versionadded:: 2016.3.0 ''' # Provides: # dns if salt.utils.platform.is_windows() or 'proxyminion' in __opts__: return {} resolv = salt.utils.dns.parse_resolv() for key in ('nameservers', 'ip4_nameservers', 'ip6_nameservers', 'sortlist'): if key in resolv: resolv[key] = [six.text_type(i) for i in resolv[key]] return {'dns': resolv} if resolv else {} def get_machine_id(): ''' Provide the machine-id for machine/virtualization combination ''' # Provides: # machine-id if platform.system() == 'AIX': return _aix_get_machine_id() locations = ['/etc/machine-id', '/var/lib/dbus/machine-id'] existing_locations = [loc for loc in locations if os.path.exists(loc)] if not existing_locations: return {} else: with salt.utils.files.fopen(existing_locations[0]) as machineid: return {'machine_id': machineid.read().strip()} def cwd(): ''' Current working directory ''' return {'cwd': os.getcwd()} def path(): ''' Return the path ''' # Provides: # path return {'path': os.environ.get('PATH', '').strip()} def pythonversion(): ''' Return the Python version ''' # Provides: # pythonversion return {'pythonversion': list(sys.version_info)} def pythonpath(): ''' Return the Python path ''' # Provides: # pythonpath return {'pythonpath': sys.path} def pythonexecutable(): ''' Return the python executable in use ''' # Provides: # pythonexecutable return {'pythonexecutable': sys.executable} def saltpath(): ''' Return the path of the salt module ''' # Provides: # saltpath salt_path = os.path.abspath(os.path.join(__file__, os.path.pardir)) return {'saltpath': os.path.dirname(salt_path)} def saltversion(): ''' Return the version of salt ''' # Provides: # saltversion from salt.version import __version__ return {'saltversion': __version__} def zmqversion(): ''' Return the zeromq version ''' # Provides: # zmqversion try: import zmq return {'zmqversion': zmq.zmq_version()} # pylint: disable=no-member except ImportError: return {} def saltversioninfo(): ''' Return the version_info of salt .. versionadded:: 0.17.0 ''' # Provides: # saltversioninfo from salt.version import __version_info__ return {'saltversioninfo': list(__version_info__)} def _hw_data(osdata): ''' Get system specific hardware data from dmidecode Provides biosversion productname manufacturer serialnumber biosreleasedate uuid .. versionadded:: 0.9.5 ''' if salt.utils.platform.is_proxy(): return {} grains = {} if osdata['kernel'] == 'Linux' and os.path.exists('/sys/class/dmi/id'): # On many Linux distributions basic firmware information is available via sysfs # requires CONFIG_DMIID to be enabled in the Linux kernel configuration sysfs_firmware_info = { 'biosversion': 'bios_version', 'productname': 'product_name', 'manufacturer': 'sys_vendor', 'biosreleasedate': 'bios_date', 'uuid': 'product_uuid', 'serialnumber': 'product_serial' } for key, fw_file in sysfs_firmware_info.items(): contents_file = os.path.join('/sys/class/dmi/id', fw_file) if os.path.exists(contents_file): try: with salt.utils.files.fopen(contents_file, 'r') as ifile: grains[key] = salt.utils.stringutils.to_unicode(ifile.read().strip(), errors='replace') if key == 'uuid': grains['uuid'] = grains['uuid'].lower() except (IOError, OSError) as err: # PermissionError is new to Python 3, but corresponds to the EACESS and # EPERM error numbers. Use those instead here for PY2 compatibility. if err.errno == EACCES or err.errno == EPERM: # Skip the grain if non-root user has no access to the file. pass elif salt.utils.path.which_bin(['dmidecode', 'smbios']) is not None and not ( salt.utils.platform.is_smartos() or ( # SunOS on SPARC - 'smbios: failed to load SMBIOS: System does not export an SMBIOS table' osdata['kernel'] == 'SunOS' and osdata['cpuarch'].startswith('sparc') )): # On SmartOS (possibly SunOS also) smbios only works in the global zone # smbios is also not compatible with linux's smbios (smbios -s = print summarized) grains = { 'biosversion': __salt__['smbios.get']('bios-version'), 'productname': __salt__['smbios.get']('system-product-name'), 'manufacturer': __salt__['smbios.get']('system-manufacturer'), 'biosreleasedate': __salt__['smbios.get']('bios-release-date'), 'uuid': __salt__['smbios.get']('system-uuid') } grains = dict([(key, val) for key, val in grains.items() if val is not None]) uuid = __salt__['smbios.get']('system-uuid') if uuid is not None: grains['uuid'] = uuid.lower() for serial in ('system-serial-number', 'chassis-serial-number', 'baseboard-serial-number'): serial = __salt__['smbios.get'](serial) if serial is not None: grains['serialnumber'] = serial break elif salt.utils.path.which_bin(['fw_printenv']) is not None: # ARM Linux devices expose UBOOT env variables via fw_printenv hwdata = { 'manufacturer': 'manufacturer', 'serialnumber': 'serial#', 'productname': 'DeviceDesc', } for grain_name, cmd_key in six.iteritems(hwdata): result = __salt__['cmd.run_all']('fw_printenv {0}'.format(cmd_key)) if result['retcode'] == 0: uboot_keyval = result['stdout'].split('=') grains[grain_name] = _clean_value(grain_name, uboot_keyval[1]) elif osdata['kernel'] == 'FreeBSD': # On FreeBSD /bin/kenv (already in base system) # can be used instead of dmidecode kenv = salt.utils.path.which('kenv') if kenv: # In theory, it will be easier to add new fields to this later fbsd_hwdata = { 'biosversion': 'smbios.bios.version', 'manufacturer': 'smbios.system.maker', 'serialnumber': 'smbios.system.serial', 'productname': 'smbios.system.product', 'biosreleasedate': 'smbios.bios.reldate', 'uuid': 'smbios.system.uuid', } for key, val in six.iteritems(fbsd_hwdata): value = __salt__['cmd.run']('{0} {1}'.format(kenv, val)) grains[key] = _clean_value(key, value) elif osdata['kernel'] == 'OpenBSD': sysctl = salt.utils.path.which('sysctl') hwdata = {'biosversion': 'hw.version', 'manufacturer': 'hw.vendor', 'productname': 'hw.product', 'serialnumber': 'hw.serialno', 'uuid': 'hw.uuid'} for key, oid in six.iteritems(hwdata): value = __salt__['cmd.run']('{0} -n {1}'.format(sysctl, oid)) if not value.endswith(' value is not available'): grains[key] = _clean_value(key, value) elif osdata['kernel'] == 'NetBSD': sysctl = salt.utils.path.which('sysctl') nbsd_hwdata = { 'biosversion': 'machdep.dmi.board-version', 'manufacturer': 'machdep.dmi.system-vendor', 'serialnumber': 'machdep.dmi.system-serial', 'productname': 'machdep.dmi.system-product', 'biosreleasedate': 'machdep.dmi.bios-date', 'uuid': 'machdep.dmi.system-uuid', } for key, oid in six.iteritems(nbsd_hwdata): result = __salt__['cmd.run_all']('{0} -n {1}'.format(sysctl, oid)) if result['retcode'] == 0: grains[key] = _clean_value(key, result['stdout']) elif osdata['kernel'] == 'Darwin': grains['manufacturer'] = 'Apple Inc.' sysctl = salt.utils.path.which('sysctl') hwdata = {'productname': 'hw.model'} for key, oid in hwdata.items(): value = __salt__['cmd.run']('{0} -b {1}'.format(sysctl, oid)) if not value.endswith(' is invalid'): grains[key] = _clean_value(key, value) elif osdata['kernel'] == 'SunOS' and osdata['cpuarch'].startswith('sparc'): # Depending on the hardware model, commands can report different bits # of information. With that said, consolidate the output from various # commands and attempt various lookups. data = "" for (cmd, args) in (('/usr/sbin/prtdiag', '-v'), ('/usr/sbin/prtconf', '-vp'), ('/usr/sbin/virtinfo', '-a')): if salt.utils.path.which(cmd): # Also verifies that cmd is executable data += __salt__['cmd.run']('{0} {1}'.format(cmd, args)) data += '\n' sn_regexes = [ re.compile(r) for r in [ r'(?im)^\s*Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag r'(?im)^\s*chassis-sn:\s*(\S+)', # prtconf r'(?im)^\s*Chassis\s+Serial#:\s*(\S+)', # virtinfo ] ] obp_regexes = [ re.compile(r) for r in [ r'(?im)^\s*System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag r'(?im)^\s*version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf ] ] fw_regexes = [ re.compile(r) for r in [ r'(?im)^\s*Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag ] ] uuid_regexes = [ re.compile(r) for r in [ r'(?im)^\s*Domain\s+UUID:\s*(\S+)', # virtinfo ] ] manufacture_regexes = [ re.compile(r) for r in [ r'(?im)^\s*System\s+Configuration:\s*(.*)(?=sun)', # prtdiag ] ] product_regexes = [ re.compile(r) for r in [ r'(?im)^\s*System\s+Configuration:\s*.*?sun\d\S+[^\S\r\n]*(.*)', # prtdiag r'(?im)^[^\S\r\n]*banner-name:[^\S\r\n]*(.*)', # prtconf r'(?im)^[^\S\r\n]*product-name:[^\S\r\n]*(.*)', # prtconf ] ] sn_regexes = [ re.compile(r) for r in [ r'(?im)Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag r'(?i)Chassis\s+Serial#:\s*(\S+)', # virtinfo r'(?i)chassis-sn:\s*(\S+)', # prtconf ] ] obp_regexes = [ re.compile(r) for r in [ r'(?im)System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag r'(?im)version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf ] ] fw_regexes = [ re.compile(r) for r in [ r'(?i)Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag ] ] uuid_regexes = [ re.compile(r) for r in [ r'(?i)Domain\s+UUID:\s+(\S+)', # virtinfo ] ] for regex in sn_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: grains['serialnumber'] = res.group(1).strip().replace("'", "") break for regex in obp_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: obp_rev, obp_date = res.groups()[0:2] # Limit the number in case we found the data in multiple places grains['biosversion'] = obp_rev.strip().replace("'", "") grains['biosreleasedate'] = obp_date.strip().replace("'", "") for regex in fw_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: fw_rev, fw_date = res.groups()[0:2] grains['systemfirmware'] = fw_rev.strip().replace("'", "") grains['systemfirmwaredate'] = fw_date.strip().replace("'", "") break for regex in uuid_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: grains['uuid'] = res.group(1).strip().replace("'", "") break for regex in manufacture_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: grains['manufacture'] = res.group(1).strip().replace("'", "") break for regex in product_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: t_productname = res.group(1).strip().replace("'", "") if t_productname: grains['product'] = t_productname grains['productname'] = t_productname break elif osdata['kernel'] == 'AIX': cmd = salt.utils.path.which('prtconf') if cmd: data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'), ('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')): for regex in [re.compile(r) for r in [regstring]]: res = regex.search(data) if res and len(res.groups()) >= 1: grains[dest] = res.group(1).strip().replace("'", '') product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')] for regex in product_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",") break else: log.error('The \'prtconf\' binary was not found in $PATH.') elif osdata['kernel'] == 'AIX': cmd = salt.utils.path.which('prtconf') if data: data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'), ('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')): for regex in [re.compile(r) for r in [regstring]]: res = regex.search(data) if res and len(res.groups()) >= 1: grains[dest] = res.group(1).strip().replace("'", '') product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')] for regex in product_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",") break else: log.error('The \'prtconf\' binary was not found in $PATH.') return grains def _get_hash_by_shell(): ''' Shell-out Python 3 for compute reliable hash :return: ''' id_ = __opts__.get('id', '') id_hash = None py_ver = sys.version_info[:2] if py_ver >= (3, 3): # Python 3.3 enabled hash randomization, so we need to shell out to get # a reliable hash. id_hash = __salt__['cmd.run']([sys.executable, '-c', 'print(hash("{0}"))'.format(id_)], env={'PYTHONHASHSEED': '0'}) try: id_hash = int(id_hash) except (TypeError, ValueError): log.debug('Failed to hash the ID to get the server_id grain. Result of hash command: %s', id_hash) id_hash = None if id_hash is None: # Python < 3.3 or error encountered above id_hash = hash(id_) return abs(id_hash % (2 ** 31)) def get_server_id(): ''' Provides an integer based on the FQDN of a machine. Useful as server-id in MySQL replication or anywhere else you'll need an ID like this. ''' # Provides: # server_id if salt.utils.platform.is_proxy(): server_id = {} else: use_crc = __opts__.get('server_id_use_crc') if bool(use_crc): id_hash = getattr(zlib, use_crc, zlib.adler32)(__opts__.get('id', '').encode()) & 0xffffffff else: log.debug('This server_id is computed not by Adler32 nor by CRC32. ' 'Please use "server_id_use_crc" option and define algorithm you ' 'prefer (default "Adler32"). Starting with Sodium, the ' 'server_id will be computed with Adler32 by default.') id_hash = _get_hash_by_shell() server_id = {'server_id': id_hash} return server_id def get_master(): ''' Provides the minion with the name of its master. This is useful in states to target other services running on the master. ''' # Provides: # master return {'master': __opts__.get('master', '')} def default_gateway(): ''' Populates grains which describe whether a server has a default gateway configured or not. Uses `ip -4 route show` and `ip -6 route show` and greps for a `default` at the beginning of any line. Assuming the standard `default via <ip>` format for default gateways, it will also parse out the ip address of the default gateway, and put it in ip4_gw or ip6_gw. If the `ip` command is unavailable, no grains will be populated. Currently does not support multiple default gateways. The grains will be set to the first default gateway found. List of grains: ip4_gw: True # ip/True/False if default ipv4 gateway ip6_gw: True # ip/True/False if default ipv6 gateway ip_gw: True # True if either of the above is True, False otherwise ''' grains = {} ip_bin = salt.utils.path.which('ip') if not ip_bin: return {} grains['ip_gw'] = False grains['ip4_gw'] = False grains['ip6_gw'] = False for ip_version in ('4', '6'): try: out = __salt__['cmd.run']([ip_bin, '-' + ip_version, 'route', 'show']) for line in out.splitlines(): if line.startswith('default'): grains['ip_gw'] = True grains['ip{0}_gw'.format(ip_version)] = True try: via, gw_ip = line.split()[1:3] except ValueError: pass else: if via == 'via': grains['ip{0}_gw'.format(ip_version)] = gw_ip break except Exception: continue return grains def kernelparams(): ''' Return the kernel boot parameters ''' if salt.utils.platform.is_windows(): # TODO: add grains using `bcdedit /enum {current}` return {} else: try: with salt.utils.files.fopen('/proc/cmdline', 'r') as fhr: cmdline = fhr.read() grains = {'kernelparams': []} for data in [item.split('=') for item in salt.utils.args.shlex_split(cmdline)]: value = None if len(data) == 2: value = data[1].strip('"') grains['kernelparams'] += [(data[0], value)] except IOError as exc: grains = {} log.debug('Failed to read /proc/cmdline: %s', exc) return grains
saltstack/salt
salt/grains/core.py
dns
python
def dns(): ''' Parse the resolver configuration file .. versionadded:: 2016.3.0 ''' # Provides: # dns if salt.utils.platform.is_windows() or 'proxyminion' in __opts__: return {} resolv = salt.utils.dns.parse_resolv() for key in ('nameservers', 'ip4_nameservers', 'ip6_nameservers', 'sortlist'): if key in resolv: resolv[key] = [six.text_type(i) for i in resolv[key]] return {'dns': resolv} if resolv else {}
Parse the resolver configuration file .. versionadded:: 2016.3.0
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/grains/core.py#L2322-L2339
null
# -*- coding: utf-8 -*- ''' The static grains, these are the core, or built in grains. When grains are loaded they are not loaded in the same way that modules are loaded, grain functions are detected and executed, the functions MUST return a dict which will be applied to the main grains dict. This module will always be executed first, so that any grains loaded here in the core module can be overwritten just by returning dict keys with the same value as those returned here ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import socket import sys import re import platform import logging import locale import uuid import zlib from errno import EACCES, EPERM import datetime import warnings # pylint: disable=import-error try: import dateutil.tz _DATEUTIL_TZ = True except ImportError: _DATEUTIL_TZ = False __proxyenabled__ = ['*'] __FQDN__ = None # Extend the default list of supported distros. This will be used for the # /etc/DISTRO-release checking that is part of linux_distribution() from platform import _supported_dists _supported_dists += ('arch', 'mageia', 'meego', 'vmware', 'bluewhite64', 'slamd64', 'ovs', 'system', 'mint', 'oracle', 'void') # linux_distribution deprecated in py3.7 try: from platform import linux_distribution as _deprecated_linux_distribution def linux_distribution(**kwargs): with warnings.catch_warnings(): warnings.simplefilter("ignore") return _deprecated_linux_distribution(**kwargs) except ImportError: from distro import linux_distribution # Import salt libs import salt.exceptions import salt.log import salt.utils.args import salt.utils.dns import salt.utils.files import salt.utils.network import salt.utils.path import salt.utils.pkg.rpm import salt.utils.platform import salt.utils.stringutils import salt.utils.versions from salt.ext import six from salt.ext.six.moves import range if salt.utils.platform.is_windows(): import salt.utils.win_osinfo # Solve the Chicken and egg problem where grains need to run before any # of the modules are loaded and are generally available for any usage. import salt.modules.cmdmod import salt.modules.smbios __salt__ = { 'cmd.run': salt.modules.cmdmod._run_quiet, 'cmd.retcode': salt.modules.cmdmod._retcode_quiet, 'cmd.run_all': salt.modules.cmdmod._run_all_quiet, 'smbios.records': salt.modules.smbios.records, 'smbios.get': salt.modules.smbios.get, } log = logging.getLogger(__name__) HAS_WMI = False if salt.utils.platform.is_windows(): # attempt to import the python wmi module # the Windows minion uses WMI for some of its grains try: import wmi # pylint: disable=import-error import salt.utils.winapi import win32api import salt.utils.win_reg HAS_WMI = True except ImportError: log.exception( 'Unable to import Python wmi module, some core grains ' 'will be missing' ) HAS_UNAME = True if not hasattr(os, 'uname'): HAS_UNAME = False _INTERFACES = {} def _windows_cpudata(): ''' Return some CPU information on Windows minions ''' # Provides: # num_cpus # cpu_model grains = {} if 'NUMBER_OF_PROCESSORS' in os.environ: # Cast to int so that the logic isn't broken when used as a # conditional in templating. Also follows _linux_cpudata() try: grains['num_cpus'] = int(os.environ['NUMBER_OF_PROCESSORS']) except ValueError: grains['num_cpus'] = 1 grains['cpu_model'] = salt.utils.win_reg.read_value( hive="HKEY_LOCAL_MACHINE", key="HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", vname="ProcessorNameString").get('vdata') return grains def _linux_cpudata(): ''' Return some CPU information for Linux minions ''' # Provides: # num_cpus # cpu_model # cpu_flags grains = {} cpuinfo = '/proc/cpuinfo' # Parse over the cpuinfo file if os.path.isfile(cpuinfo): with salt.utils.files.fopen(cpuinfo, 'r') as _fp: grains['num_cpus'] = 0 for line in _fp: comps = line.split(':') if not len(comps) > 1: continue key = comps[0].strip() val = comps[1].strip() if key == 'processor': grains['num_cpus'] += 1 elif key == 'model name': grains['cpu_model'] = val elif key == 'flags': grains['cpu_flags'] = val.split() elif key == 'Features': grains['cpu_flags'] = val.split() # ARM support - /proc/cpuinfo # # Processor : ARMv6-compatible processor rev 7 (v6l) # BogoMIPS : 697.95 # Features : swp half thumb fastmult vfp edsp java tls # CPU implementer : 0x41 # CPU architecture: 7 # CPU variant : 0x0 # CPU part : 0xb76 # CPU revision : 7 # # Hardware : BCM2708 # Revision : 0002 # Serial : 00000000 elif key == 'Processor': grains['cpu_model'] = val.split('-')[0] grains['num_cpus'] = 1 if 'num_cpus' not in grains: grains['num_cpus'] = 0 if 'cpu_model' not in grains: grains['cpu_model'] = 'Unknown' if 'cpu_flags' not in grains: grains['cpu_flags'] = [] return grains def _linux_gpu_data(): ''' num_gpus: int gpus: - vendor: nvidia|amd|ati|... model: string ''' if __opts__.get('enable_lspci', True) is False: return {} if __opts__.get('enable_gpu_grains', True) is False: return {} lspci = salt.utils.path.which('lspci') if not lspci: log.debug( 'The `lspci` binary is not available on the system. GPU grains ' 'will not be available.' ) return {} # dominant gpu vendors to search for (MUST be lowercase for matching below) known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed'] gpu_classes = ('vga compatible controller', '3d controller') devs = [] try: lspci_out = __salt__['cmd.run']('{0} -vmm'.format(lspci)) cur_dev = {} error = False # Add a blank element to the lspci_out.splitlines() list, # otherwise the last device is not evaluated as a cur_dev and ignored. lspci_list = lspci_out.splitlines() lspci_list.append('') for line in lspci_list: # check for record-separating empty lines if line == '': if cur_dev.get('Class', '').lower() in gpu_classes: devs.append(cur_dev) cur_dev = {} continue if re.match(r'^\w+:\s+.*', line): key, val = line.split(':', 1) cur_dev[key.strip()] = val.strip() else: error = True log.debug('Unexpected lspci output: \'%s\'', line) if error: log.warning( 'Error loading grains, unexpected linux_gpu_data output, ' 'check that you have a valid shell configured and ' 'permissions to run lspci command' ) except OSError: pass gpus = [] for gpu in devs: vendor_strings = re.split('[^A-Za-z0-9]', gpu['Vendor'].lower()) # default vendor to 'unknown', overwrite if we match a known one vendor = 'unknown' for name in known_vendors: # search for an 'expected' vendor name in the list of strings if name in vendor_strings: vendor = name break gpus.append({'vendor': vendor, 'model': gpu['Device']}) grains = {} grains['num_gpus'] = len(gpus) grains['gpus'] = gpus return grains def _netbsd_gpu_data(): ''' num_gpus: int gpus: - vendor: nvidia|amd|ati|... model: string ''' known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed'] gpus = [] try: pcictl_out = __salt__['cmd.run']('pcictl pci0 list') for line in pcictl_out.splitlines(): for vendor in known_vendors: vendor_match = re.match( r'[0-9:]+ ({0}) (.+) \(VGA .+\)'.format(vendor), line, re.IGNORECASE ) if vendor_match: gpus.append({'vendor': vendor_match.group(1), 'model': vendor_match.group(2)}) except OSError: pass grains = {} grains['num_gpus'] = len(gpus) grains['gpus'] = gpus return grains def _osx_gpudata(): ''' num_gpus: int gpus: - vendor: nvidia|amd|ati|... model: string ''' gpus = [] try: pcictl_out = __salt__['cmd.run']('system_profiler SPDisplaysDataType') for line in pcictl_out.splitlines(): fieldname, _, fieldval = line.partition(': ') if fieldname.strip() == "Chipset Model": vendor, _, model = fieldval.partition(' ') vendor = vendor.lower() gpus.append({'vendor': vendor, 'model': model}) except OSError: pass grains = {} grains['num_gpus'] = len(gpus) grains['gpus'] = gpus return grains def _bsd_cpudata(osdata): ''' Return CPU information for BSD-like systems ''' # Provides: # cpuarch # num_cpus # cpu_model # cpu_flags sysctl = salt.utils.path.which('sysctl') arch = salt.utils.path.which('arch') cmds = {} if sysctl: cmds.update({ 'num_cpus': '{0} -n hw.ncpu'.format(sysctl), 'cpuarch': '{0} -n hw.machine'.format(sysctl), 'cpu_model': '{0} -n hw.model'.format(sysctl), }) if arch and osdata['kernel'] == 'OpenBSD': cmds['cpuarch'] = '{0} -s'.format(arch) if osdata['kernel'] == 'Darwin': cmds['cpu_model'] = '{0} -n machdep.cpu.brand_string'.format(sysctl) cmds['cpu_flags'] = '{0} -n machdep.cpu.features'.format(sysctl) grains = dict([(k, __salt__['cmd.run'](v)) for k, v in six.iteritems(cmds)]) if 'cpu_flags' in grains and isinstance(grains['cpu_flags'], six.string_types): grains['cpu_flags'] = grains['cpu_flags'].split(' ') if osdata['kernel'] == 'NetBSD': grains['cpu_flags'] = [] for line in __salt__['cmd.run']('cpuctl identify 0').splitlines(): cpu_match = re.match(r'cpu[0-9]:\ features[0-9]?\ .+<(.+)>', line) if cpu_match: flag = cpu_match.group(1).split(',') grains['cpu_flags'].extend(flag) if osdata['kernel'] == 'FreeBSD' and os.path.isfile('/var/run/dmesg.boot'): grains['cpu_flags'] = [] # TODO: at least it needs to be tested for BSD other then FreeBSD with salt.utils.files.fopen('/var/run/dmesg.boot', 'r') as _fp: cpu_here = False for line in _fp: if line.startswith('CPU: '): cpu_here = True # starts CPU descr continue if cpu_here: if not line.startswith(' '): break # game over if 'Features' in line: start = line.find('<') end = line.find('>') if start > 0 and end > 0: flag = line[start + 1:end].split(',') grains['cpu_flags'].extend(flag) try: grains['num_cpus'] = int(grains['num_cpus']) except ValueError: grains['num_cpus'] = 1 return grains def _sunos_cpudata(): ''' Return the CPU information for Solaris-like systems ''' # Provides: # cpuarch # num_cpus # cpu_model # cpu_flags grains = {} grains['cpu_flags'] = [] grains['cpuarch'] = __salt__['cmd.run']('isainfo -k') psrinfo = '/usr/sbin/psrinfo 2>/dev/null' grains['num_cpus'] = len(__salt__['cmd.run'](psrinfo, python_shell=True).splitlines()) kstat_info = 'kstat -p cpu_info:*:*:brand' for line in __salt__['cmd.run'](kstat_info).splitlines(): match = re.match(r'(\w+:\d+:\w+\d+:\w+)\s+(.+)', line) if match: grains['cpu_model'] = match.group(2) isainfo = 'isainfo -n -v' for line in __salt__['cmd.run'](isainfo).splitlines(): match = re.match(r'^\s+(.+)', line) if match: cpu_flags = match.group(1).split() grains['cpu_flags'].extend(cpu_flags) return grains def _aix_cpudata(): ''' Return CPU information for AIX systems ''' # Provides: # cpuarch # num_cpus # cpu_model # cpu_flags grains = {} cmd = salt.utils.path.which('prtconf') if cmd: data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep for dest, regstring in (('cpuarch', r'(?im)^\s*Processor\s+Type:\s+(\S+)'), ('cpu_flags', r'(?im)^\s*Processor\s+Version:\s+(\S+)'), ('cpu_model', r'(?im)^\s*Processor\s+Implementation\s+Mode:\s+(.*)'), ('num_cpus', r'(?im)^\s*Number\s+Of\s+Processors:\s+(\S+)')): for regex in [re.compile(r) for r in [regstring]]: res = regex.search(data) if res and len(res.groups()) >= 1: grains[dest] = res.group(1).strip().replace("'", '') else: log.error('The \'prtconf\' binary was not found in $PATH.') return grains def _linux_memdata(): ''' Return the memory information for Linux-like systems ''' grains = {'mem_total': 0, 'swap_total': 0} meminfo = '/proc/meminfo' if os.path.isfile(meminfo): with salt.utils.files.fopen(meminfo, 'r') as ifile: for line in ifile: comps = line.rstrip('\n').split(':') if not len(comps) > 1: continue if comps[0].strip() == 'MemTotal': # Use floor division to force output to be an integer grains['mem_total'] = int(comps[1].split()[0]) // 1024 if comps[0].strip() == 'SwapTotal': # Use floor division to force output to be an integer grains['swap_total'] = int(comps[1].split()[0]) // 1024 return grains def _osx_memdata(): ''' Return the memory information for BSD-like systems ''' grains = {'mem_total': 0, 'swap_total': 0} sysctl = salt.utils.path.which('sysctl') if sysctl: mem = __salt__['cmd.run']('{0} -n hw.memsize'.format(sysctl)) swap_total = __salt__['cmd.run']('{0} -n vm.swapusage'.format(sysctl)).split()[2].replace(',', '.') if swap_total.endswith('K'): _power = 2**10 elif swap_total.endswith('M'): _power = 2**20 elif swap_total.endswith('G'): _power = 2**30 swap_total = float(swap_total[:-1]) * _power grains['mem_total'] = int(mem) // 1024 // 1024 grains['swap_total'] = int(swap_total) // 1024 // 1024 return grains def _bsd_memdata(osdata): ''' Return the memory information for BSD-like systems ''' grains = {'mem_total': 0, 'swap_total': 0} sysctl = salt.utils.path.which('sysctl') if sysctl: mem = __salt__['cmd.run']('{0} -n hw.physmem'.format(sysctl)) if osdata['kernel'] == 'NetBSD' and mem.startswith('-'): mem = __salt__['cmd.run']('{0} -n hw.physmem64'.format(sysctl)) grains['mem_total'] = int(mem) // 1024 // 1024 if osdata['kernel'] in ['OpenBSD', 'NetBSD']: swapctl = salt.utils.path.which('swapctl') swap_data = __salt__['cmd.run']('{0} -sk'.format(swapctl)) if swap_data == 'no swap devices configured': swap_total = 0 else: swap_total = swap_data.split(' ')[1] else: swap_total = __salt__['cmd.run']('{0} -n vm.swap_total'.format(sysctl)) grains['swap_total'] = int(swap_total) // 1024 // 1024 return grains def _sunos_memdata(): ''' Return the memory information for SunOS-like systems ''' grains = {'mem_total': 0, 'swap_total': 0} prtconf = '/usr/sbin/prtconf 2>/dev/null' for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines(): comps = line.split(' ') if comps[0].strip() == 'Memory' and comps[1].strip() == 'size:': grains['mem_total'] = int(comps[2].strip()) swap_cmd = salt.utils.path.which('swap') swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split() try: swap_avail = int(swap_data[-2][:-1]) swap_used = int(swap_data[-4][:-1]) swap_total = (swap_avail + swap_used) // 1024 except ValueError: swap_total = None grains['swap_total'] = swap_total return grains def _aix_memdata(): ''' Return the memory information for AIX systems ''' grains = {'mem_total': 0, 'swap_total': 0} prtconf = salt.utils.path.which('prtconf') if prtconf: for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines(): comps = [x for x in line.strip().split(' ') if x] if len(comps) > 2 and 'Memory' in comps[0] and 'Size' in comps[1]: grains['mem_total'] = int(comps[2]) break else: log.error('The \'prtconf\' binary was not found in $PATH.') swap_cmd = salt.utils.path.which('swap') if swap_cmd: swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split() try: swap_total = (int(swap_data[-2]) + int(swap_data[-6])) * 4 except ValueError: swap_total = None grains['swap_total'] = swap_total else: log.error('The \'swap\' binary was not found in $PATH.') return grains def _windows_memdata(): ''' Return the memory information for Windows systems ''' grains = {'mem_total': 0} # get the Total Physical memory as reported by msinfo32 tot_bytes = win32api.GlobalMemoryStatusEx()['TotalPhys'] # return memory info in gigabytes grains['mem_total'] = int(tot_bytes / (1024 ** 2)) return grains def _memdata(osdata): ''' Gather information about the system memory ''' # Provides: # mem_total # swap_total, for supported systems. grains = {'mem_total': 0} if osdata['kernel'] == 'Linux': grains.update(_linux_memdata()) elif osdata['kernel'] in ('FreeBSD', 'OpenBSD', 'NetBSD'): grains.update(_bsd_memdata(osdata)) elif osdata['kernel'] == 'Darwin': grains.update(_osx_memdata()) elif osdata['kernel'] == 'SunOS': grains.update(_sunos_memdata()) elif osdata['kernel'] == 'AIX': grains.update(_aix_memdata()) elif osdata['kernel'] == 'Windows' and HAS_WMI: grains.update(_windows_memdata()) return grains def _aix_get_machine_id(): ''' Parse the output of lsattr -El sys0 for os_uuid ''' grains = {} cmd = salt.utils.path.which('lsattr') if cmd: data = __salt__['cmd.run']('{0} -El sys0'.format(cmd)) + os.linesep uuid_regexes = [re.compile(r'(?im)^\s*os_uuid\s+(\S+)\s+(.*)')] for regex in uuid_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: grains['machine_id'] = res.group(1).strip() break else: log.error('The \'lsattr\' binary was not found in $PATH.') return grains def _windows_virtual(osdata): ''' Returns what type of virtual hardware is under the hood, kvm or physical ''' # Provides: # virtual # virtual_subtype grains = dict() if osdata['kernel'] != 'Windows': return grains grains['virtual'] = 'physical' # It is possible that the 'manufacturer' and/or 'productname' grains # exist but have a value of None. manufacturer = osdata.get('manufacturer', '') if manufacturer is None: manufacturer = '' productname = osdata.get('productname', '') if productname is None: productname = '' if 'QEMU' in manufacturer: # FIXME: Make this detect between kvm or qemu grains['virtual'] = 'kvm' if 'Bochs' in manufacturer: grains['virtual'] = 'kvm' # Product Name: (oVirt) www.ovirt.org # Red Hat Community virtualization Project based on kvm elif 'oVirt' in productname: grains['virtual'] = 'kvm' grains['virtual_subtype'] = 'oVirt' # Red Hat Enterprise Virtualization elif 'RHEV Hypervisor' in productname: grains['virtual'] = 'kvm' grains['virtual_subtype'] = 'rhev' # Product Name: VirtualBox elif 'VirtualBox' in productname: grains['virtual'] = 'VirtualBox' # Product Name: VMware Virtual Platform elif 'VMware Virtual Platform' in productname: grains['virtual'] = 'VMware' # Manufacturer: Microsoft Corporation # Product Name: Virtual Machine elif 'Microsoft' in manufacturer and \ 'Virtual Machine' in productname: grains['virtual'] = 'VirtualPC' # Manufacturer: Parallels Software International Inc. elif 'Parallels Software' in manufacturer: grains['virtual'] = 'Parallels' # Apache CloudStack elif 'CloudStack KVM Hypervisor' in productname: grains['virtual'] = 'kvm' grains['virtual_subtype'] = 'cloudstack' return grains def _virtual(osdata): ''' Returns what type of virtual hardware is under the hood, kvm or physical ''' # This is going to be a monster, if you are running a vm you can test this # grain with please submit patches! # Provides: # virtual # virtual_subtype grains = {'virtual': 'physical'} # Skip the below loop on platforms which have none of the desired cmds # This is a temporary measure until we can write proper virtual hardware # detection. skip_cmds = ('AIX',) # list of commands to be executed to determine the 'virtual' grain _cmds = ['systemd-detect-virt', 'virt-what', 'dmidecode'] # test first for virt-what, which covers most of the desired functionality # on most platforms if not salt.utils.platform.is_windows() and osdata['kernel'] not in skip_cmds: if salt.utils.path.which('virt-what'): _cmds = ['virt-what'] # Check if enable_lspci is True or False if __opts__.get('enable_lspci', True) is True: # /proc/bus/pci does not exists, lspci will fail if os.path.exists('/proc/bus/pci'): _cmds += ['lspci'] # Add additional last resort commands if osdata['kernel'] in skip_cmds: _cmds = () # Quick backout for BrandZ (Solaris LX Branded zones) # Don't waste time trying other commands to detect the virtual grain if HAS_UNAME and osdata['kernel'] == 'Linux' and 'BrandZ virtual linux' in os.uname(): grains['virtual'] = 'zone' return grains failed_commands = set() for command in _cmds: args = [] if osdata['kernel'] == 'Darwin': command = 'system_profiler' args = ['SPDisplaysDataType'] elif osdata['kernel'] == 'SunOS': virtinfo = salt.utils.path.which('virtinfo') if virtinfo: try: ret = __salt__['cmd.run_all']('{0} -a'.format(virtinfo)) except salt.exceptions.CommandExecutionError: if salt.log.is_logging_configured(): failed_commands.add(virtinfo) else: if ret['stdout'].endswith('not supported'): command = 'prtdiag' else: command = 'virtinfo' else: command = 'prtdiag' cmd = salt.utils.path.which(command) if not cmd: continue cmd = '{0} {1}'.format(cmd, ' '.join(args)) try: ret = __salt__['cmd.run_all'](cmd) if ret['retcode'] > 0: if salt.log.is_logging_configured(): # systemd-detect-virt always returns > 0 on non-virtualized # systems # prtdiag only works in the global zone, skip if it fails if salt.utils.platform.is_windows() or 'systemd-detect-virt' in cmd or 'prtdiag' in cmd: continue failed_commands.add(command) continue except salt.exceptions.CommandExecutionError: if salt.log.is_logging_configured(): if salt.utils.platform.is_windows(): continue failed_commands.add(command) continue output = ret['stdout'] if command == "system_profiler": macoutput = output.lower() if '0x1ab8' in macoutput: grains['virtual'] = 'Parallels' if 'parallels' in macoutput: grains['virtual'] = 'Parallels' if 'vmware' in macoutput: grains['virtual'] = 'VMware' if '0x15ad' in macoutput: grains['virtual'] = 'VMware' if 'virtualbox' in macoutput: grains['virtual'] = 'VirtualBox' # Break out of the loop so the next log message is not issued break elif command == 'systemd-detect-virt': if output in ('qemu', 'kvm', 'oracle', 'xen', 'bochs', 'chroot', 'uml', 'systemd-nspawn'): grains['virtual'] = output break elif 'vmware' in output: grains['virtual'] = 'VMware' break elif 'microsoft' in output: grains['virtual'] = 'VirtualPC' break elif 'lxc' in output: grains['virtual'] = 'LXC' break elif 'systemd-nspawn' in output: grains['virtual'] = 'LXC' break elif command == 'virt-what': try: output = output.splitlines()[-1] except IndexError: pass if output in ('kvm', 'qemu', 'uml', 'xen', 'lxc'): grains['virtual'] = output break elif 'vmware' in output: grains['virtual'] = 'VMware' break elif 'parallels' in output: grains['virtual'] = 'Parallels' break elif 'hyperv' in output: grains['virtual'] = 'HyperV' break elif command == 'dmidecode': # Product Name: VirtualBox if 'Vendor: QEMU' in output: # FIXME: Make this detect between kvm or qemu grains['virtual'] = 'kvm' if 'Manufacturer: QEMU' in output: grains['virtual'] = 'kvm' if 'Vendor: Bochs' in output: grains['virtual'] = 'kvm' if 'Manufacturer: Bochs' in output: grains['virtual'] = 'kvm' if 'BHYVE' in output: grains['virtual'] = 'bhyve' # Product Name: (oVirt) www.ovirt.org # Red Hat Community virtualization Project based on kvm elif 'Manufacturer: oVirt' in output: grains['virtual'] = 'kvm' grains['virtual_subtype'] = 'ovirt' # Red Hat Enterprise Virtualization elif 'Product Name: RHEV Hypervisor' in output: grains['virtual'] = 'kvm' grains['virtual_subtype'] = 'rhev' elif 'VirtualBox' in output: grains['virtual'] = 'VirtualBox' # Product Name: VMware Virtual Platform elif 'VMware' in output: grains['virtual'] = 'VMware' # Manufacturer: Microsoft Corporation # Product Name: Virtual Machine elif ': Microsoft' in output and 'Virtual Machine' in output: grains['virtual'] = 'VirtualPC' # Manufacturer: Parallels Software International Inc. elif 'Parallels Software' in output: grains['virtual'] = 'Parallels' elif 'Manufacturer: Google' in output: grains['virtual'] = 'kvm' # Proxmox KVM elif 'Vendor: SeaBIOS' in output: grains['virtual'] = 'kvm' # Break out of the loop, lspci parsing is not necessary break elif command == 'lspci': # dmidecode not available or the user does not have the necessary # permissions model = output.lower() if 'vmware' in model: grains['virtual'] = 'VMware' # 00:04.0 System peripheral: InnoTek Systemberatung GmbH # VirtualBox Guest Service elif 'virtualbox' in model: grains['virtual'] = 'VirtualBox' elif 'qemu' in model: grains['virtual'] = 'kvm' elif 'virtio' in model: grains['virtual'] = 'kvm' # Break out of the loop so the next log message is not issued break elif command == 'prtdiag': model = output.lower().split("\n")[0] if 'vmware' in model: grains['virtual'] = 'VMware' elif 'virtualbox' in model: grains['virtual'] = 'VirtualBox' elif 'qemu' in model: grains['virtual'] = 'kvm' elif 'joyent smartdc hvm' in model: grains['virtual'] = 'kvm' break elif command == 'virtinfo': grains['virtual'] = 'LDOM' break choices = ('Linux', 'HP-UX') isdir = os.path.isdir sysctl = salt.utils.path.which('sysctl') if osdata['kernel'] in choices: if os.path.isdir('/proc'): try: self_root = os.stat('/') init_root = os.stat('/proc/1/root/.') if self_root != init_root: grains['virtual_subtype'] = 'chroot' except (IOError, OSError): pass if isdir('/proc/vz'): if os.path.isfile('/proc/vz/version'): grains['virtual'] = 'openvzhn' elif os.path.isfile('/proc/vz/veinfo'): grains['virtual'] = 'openvzve' # a posteriori, it's expected for these to have failed: failed_commands.discard('lspci') failed_commands.discard('dmidecode') # Provide additional detection for OpenVZ if os.path.isfile('/proc/self/status'): with salt.utils.files.fopen('/proc/self/status') as status_file: vz_re = re.compile(r'^envID:\s+(\d+)$') for line in status_file: vz_match = vz_re.match(line.rstrip('\n')) if vz_match and int(vz_match.groups()[0]) != 0: grains['virtual'] = 'openvzve' elif vz_match and int(vz_match.groups()[0]) == 0: grains['virtual'] = 'openvzhn' if isdir('/proc/sys/xen') or \ isdir('/sys/bus/xen') or isdir('/proc/xen'): if os.path.isfile('/proc/xen/xsd_kva'): # Tested on CentOS 5.3 / 2.6.18-194.26.1.el5xen # Tested on CentOS 5.4 / 2.6.18-164.15.1.el5xen grains['virtual_subtype'] = 'Xen Dom0' else: if osdata.get('productname', '') == 'HVM domU': # Requires dmidecode! grains['virtual_subtype'] = 'Xen HVM DomU' elif os.path.isfile('/proc/xen/capabilities') and \ os.access('/proc/xen/capabilities', os.R_OK): with salt.utils.files.fopen('/proc/xen/capabilities') as fhr: if 'control_d' not in fhr.read(): # Tested on CentOS 5.5 / 2.6.18-194.3.1.el5xen grains['virtual_subtype'] = 'Xen PV DomU' else: # Shouldn't get to this, but just in case grains['virtual_subtype'] = 'Xen Dom0' # Tested on Fedora 10 / 2.6.27.30-170.2.82 with xen # Tested on Fedora 15 / 2.6.41.4-1 without running xen elif isdir('/sys/bus/xen'): if 'xen:' in __salt__['cmd.run']('dmesg').lower(): grains['virtual_subtype'] = 'Xen PV DomU' elif os.path.isfile('/sys/bus/xen/drivers/xenconsole'): # An actual DomU will have the xenconsole driver grains['virtual_subtype'] = 'Xen PV DomU' # If a Dom0 or DomU was detected, obviously this is xen if 'dom' in grains.get('virtual_subtype', '').lower(): grains['virtual'] = 'xen' # Check container type after hypervisors, to avoid variable overwrite on containers running in virtual environment. if os.path.isfile('/proc/1/cgroup'): try: with salt.utils.files.fopen('/proc/1/cgroup', 'r') as fhr: fhr_contents = fhr.read() if ':/lxc/' in fhr_contents: grains['virtual_subtype'] = 'LXC' elif ':/kubepods/' in fhr_contents: grains['virtual_subtype'] = 'kubernetes' elif ':/libpod_parent/' in fhr_contents: grains['virtual_subtype'] = 'libpod' else: if any(x in fhr_contents for x in (':/system.slice/docker', ':/docker/', ':/docker-ce/')): grains['virtual_subtype'] = 'Docker' except IOError: pass if os.path.isfile('/proc/cpuinfo'): with salt.utils.files.fopen('/proc/cpuinfo', 'r') as fhr: if 'QEMU Virtual CPU' in fhr.read(): grains['virtual'] = 'kvm' if os.path.isfile('/sys/devices/virtual/dmi/id/product_name'): try: with salt.utils.files.fopen('/sys/devices/virtual/dmi/id/product_name', 'r') as fhr: output = salt.utils.stringutils.to_unicode(fhr.read(), errors='replace') if 'VirtualBox' in output: grains['virtual'] = 'VirtualBox' elif 'RHEV Hypervisor' in output: grains['virtual'] = 'kvm' grains['virtual_subtype'] = 'rhev' elif 'oVirt Node' in output: grains['virtual'] = 'kvm' grains['virtual_subtype'] = 'ovirt' elif 'Google' in output: grains['virtual'] = 'gce' elif 'BHYVE' in output: grains['virtual'] = 'bhyve' except IOError: pass elif osdata['kernel'] == 'FreeBSD': kenv = salt.utils.path.which('kenv') if kenv: product = __salt__['cmd.run']( '{0} smbios.system.product'.format(kenv) ) maker = __salt__['cmd.run']( '{0} smbios.system.maker'.format(kenv) ) if product.startswith('VMware'): grains['virtual'] = 'VMware' if product.startswith('VirtualBox'): grains['virtual'] = 'VirtualBox' if maker.startswith('Xen'): grains['virtual_subtype'] = '{0} {1}'.format(maker, product) grains['virtual'] = 'xen' if maker.startswith('Microsoft') and product.startswith('Virtual'): grains['virtual'] = 'VirtualPC' if maker.startswith('OpenStack'): grains['virtual'] = 'OpenStack' if maker.startswith('Bochs'): grains['virtual'] = 'kvm' if sysctl: hv_vendor = __salt__['cmd.run']('{0} hw.hv_vendor'.format(sysctl)) model = __salt__['cmd.run']('{0} hw.model'.format(sysctl)) jail = __salt__['cmd.run']( '{0} -n security.jail.jailed'.format(sysctl) ) if 'bhyve' in hv_vendor: grains['virtual'] = 'bhyve' if jail == '1': grains['virtual_subtype'] = 'jail' if 'QEMU Virtual CPU' in model: grains['virtual'] = 'kvm' elif osdata['kernel'] == 'OpenBSD': if 'manufacturer' in osdata: if osdata['manufacturer'] in ['QEMU', 'Red Hat', 'Joyent']: grains['virtual'] = 'kvm' if osdata['manufacturer'] == 'OpenBSD': grains['virtual'] = 'vmm' elif osdata['kernel'] == 'SunOS': if grains['virtual'] == 'LDOM': roles = [] for role in ('control', 'io', 'root', 'service'): subtype_cmd = '{0} -c current get -H -o value {1}-role'.format(cmd, role) ret = __salt__['cmd.run_all']('{0}'.format(subtype_cmd)) if ret['stdout'] == 'true': roles.append(role) if roles: grains['virtual_subtype'] = roles else: # Check if it's a "regular" zone. (i.e. Solaris 10/11 zone) zonename = salt.utils.path.which('zonename') if zonename: zone = __salt__['cmd.run']('{0}'.format(zonename)) if zone != 'global': grains['virtual'] = 'zone' # Check if it's a branded zone (i.e. Solaris 8/9 zone) if isdir('/.SUNWnative'): grains['virtual'] = 'zone' elif osdata['kernel'] == 'NetBSD': if sysctl: if 'QEMU Virtual CPU' in __salt__['cmd.run']( '{0} -n machdep.cpu_brand'.format(sysctl)): grains['virtual'] = 'kvm' elif 'invalid' not in __salt__['cmd.run']( '{0} -n machdep.xen.suspend'.format(sysctl)): grains['virtual'] = 'Xen PV DomU' elif 'VMware' in __salt__['cmd.run']( '{0} -n machdep.dmi.system-vendor'.format(sysctl)): grains['virtual'] = 'VMware' # NetBSD has Xen dom0 support elif __salt__['cmd.run']( '{0} -n machdep.idle-mechanism'.format(sysctl)) == 'xen': if os.path.isfile('/var/run/xenconsoled.pid'): grains['virtual_subtype'] = 'Xen Dom0' for command in failed_commands: log.info( "Although '%s' was found in path, the current user " 'cannot execute it. Grains output might not be ' 'accurate.', command ) return grains def _virtual_hv(osdata): ''' Returns detailed hypervisor information from sysfs Currently this seems to be used only by Xen ''' grains = {} # Bail early if we're not running on Xen try: if 'xen' not in osdata['virtual']: return grains except KeyError: return grains # Try to get the exact hypervisor version from sysfs try: version = {} for fn in ('major', 'minor', 'extra'): with salt.utils.files.fopen('/sys/hypervisor/version/{}'.format(fn), 'r') as fhr: version[fn] = salt.utils.stringutils.to_unicode(fhr.read().strip()) grains['virtual_hv_version'] = '{}.{}{}'.format(version['major'], version['minor'], version['extra']) grains['virtual_hv_version_info'] = [version['major'], version['minor'], version['extra']] except (IOError, OSError, KeyError): pass # Try to read and decode the supported feature set of the hypervisor # Based on https://github.com/brendangregg/Misc/blob/master/xen/xen-features.py # Table data from include/xen/interface/features.h xen_feature_table = {0: 'writable_page_tables', 1: 'writable_descriptor_tables', 2: 'auto_translated_physmap', 3: 'supervisor_mode_kernel', 4: 'pae_pgdir_above_4gb', 5: 'mmu_pt_update_preserve_ad', 7: 'gnttab_map_avail_bits', 8: 'hvm_callback_vector', 9: 'hvm_safe_pvclock', 10: 'hvm_pirqs', 11: 'dom0', 12: 'grant_map_identity', 13: 'memory_op_vnode_supported', 14: 'ARM_SMCCC_supported'} try: with salt.utils.files.fopen('/sys/hypervisor/properties/features', 'r') as fhr: features = salt.utils.stringutils.to_unicode(fhr.read().strip()) enabled_features = [] for bit, feat in six.iteritems(xen_feature_table): if int(features, 16) & (1 << bit): enabled_features.append(feat) grains['virtual_hv_features'] = features grains['virtual_hv_features_list'] = enabled_features except (IOError, OSError, KeyError): pass return grains def _ps(osdata): ''' Return the ps grain ''' grains = {} bsd_choices = ('FreeBSD', 'NetBSD', 'OpenBSD', 'MacOS') if osdata['os'] in bsd_choices: grains['ps'] = 'ps auxwww' elif osdata['os_family'] == 'Solaris': grains['ps'] = '/usr/ucb/ps auxwww' elif osdata['os'] == 'Windows': grains['ps'] = 'tasklist.exe' elif osdata.get('virtual', '') == 'openvzhn': grains['ps'] = ( 'ps -fH -p $(grep -l \"^envID:[[:space:]]*0\\$\" ' '/proc/[0-9]*/status | sed -e \"s=/proc/\\([0-9]*\\)/.*=\\1=\") ' '| awk \'{ $7=\"\"; print }\'' ) elif osdata['os_family'] == 'AIX': grains['ps'] = '/usr/bin/ps auxww' elif osdata['os_family'] == 'NILinuxRT': grains['ps'] = 'ps -o user,pid,ppid,tty,time,comm' else: grains['ps'] = 'ps -efHww' return grains def _clean_value(key, val): ''' Clean out well-known bogus values. If it isn't clean (for example has value 'None'), return None. Otherwise, return the original value. NOTE: This logic also exists in the smbios module. This function is for use when not using smbios to retrieve the value. ''' if (val is None or not val or re.match('none', val, flags=re.IGNORECASE)): return None elif 'uuid' in key: # Try each version (1-5) of RFC4122 to check if it's actually a UUID for uuidver in range(1, 5): try: uuid.UUID(val, version=uuidver) return val except ValueError: continue log.trace('HW %s value %s is an invalid UUID', key, val.replace('\n', ' ')) return None elif re.search('serial|part|version', key): # 'To be filled by O.E.M. # 'Not applicable' etc. # 'Not specified' etc. # 0000000, 1234567 etc. # begone! if (re.match(r'^[0]+$', val) or re.match(r'[0]?1234567[8]?[9]?[0]?', val) or re.search(r'sernum|part[_-]?number|specified|filled|applicable', val, flags=re.IGNORECASE)): return None elif re.search('asset|manufacturer', key): # AssetTag0. Manufacturer04. Begone. if re.search(r'manufacturer|to be filled|available|asset|^no(ne|t)', val, flags=re.IGNORECASE): return None else: # map unspecified, undefined, unknown & whatever to None if (re.search(r'to be filled', val, flags=re.IGNORECASE) or re.search(r'un(known|specified)|no(t|ne)? (asset|provided|defined|available|present|specified)', val, flags=re.IGNORECASE)): return None return val def _windows_platform_data(): ''' Use the platform module for as much as we can. ''' # Provides: # kernelrelease # kernelversion # osversion # osrelease # osservicepack # osmanufacturer # manufacturer # productname # biosversion # serialnumber # osfullname # timezone # windowsdomain # windowsdomaintype # motherboard.productname # motherboard.serialnumber # virtual if not HAS_WMI: return {} with salt.utils.winapi.Com(): wmi_c = wmi.WMI() # http://msdn.microsoft.com/en-us/library/windows/desktop/aa394102%28v=vs.85%29.aspx systeminfo = wmi_c.Win32_ComputerSystem()[0] # https://msdn.microsoft.com/en-us/library/aa394239(v=vs.85).aspx osinfo = wmi_c.Win32_OperatingSystem()[0] # http://msdn.microsoft.com/en-us/library/windows/desktop/aa394077(v=vs.85).aspx biosinfo = wmi_c.Win32_BIOS()[0] # http://msdn.microsoft.com/en-us/library/windows/desktop/aa394498(v=vs.85).aspx timeinfo = wmi_c.Win32_TimeZone()[0] # http://msdn.microsoft.com/en-us/library/windows/desktop/aa394072(v=vs.85).aspx motherboard = {'product': None, 'serial': None} try: motherboardinfo = wmi_c.Win32_BaseBoard()[0] motherboard['product'] = motherboardinfo.Product motherboard['serial'] = motherboardinfo.SerialNumber except IndexError: log.debug('Motherboard info not available on this system') os_release = platform.release() kernel_version = platform.version() info = salt.utils.win_osinfo.get_os_version_info() net_info = salt.utils.win_osinfo.get_join_info() service_pack = None if info['ServicePackMajor'] > 0: service_pack = ''.join(['SP', six.text_type(info['ServicePackMajor'])]) # This creates the osrelease grain based on the Windows Operating # System Product Name. As long as Microsoft maintains a similar format # this should be future proof version = 'Unknown' release = '' if 'Server' in osinfo.Caption: for item in osinfo.Caption.split(' '): # If it's all digits, then it's version if re.match(r'\d+', item): version = item # If it starts with R and then numbers, it's the release # ie: R2 if re.match(r'^R\d+$', item): release = item os_release = '{0}Server{1}'.format(version, release) else: for item in osinfo.Caption.split(' '): # If it's a number, decimal number, Thin or Vista, then it's the # version if re.match(r'^(\d+(\.\d+)?)|Thin|Vista$', item): version = item os_release = version grains = { 'kernelrelease': _clean_value('kernelrelease', osinfo.Version), 'kernelversion': _clean_value('kernelversion', kernel_version), 'osversion': _clean_value('osversion', osinfo.Version), 'osrelease': _clean_value('osrelease', os_release), 'osservicepack': _clean_value('osservicepack', service_pack), 'osmanufacturer': _clean_value('osmanufacturer', osinfo.Manufacturer), 'manufacturer': _clean_value('manufacturer', systeminfo.Manufacturer), 'productname': _clean_value('productname', systeminfo.Model), # bios name had a bunch of whitespace appended to it in my testing # 'PhoenixBIOS 4.0 Release 6.0 ' 'biosversion': _clean_value('biosversion', biosinfo.Name.strip()), 'serialnumber': _clean_value('serialnumber', biosinfo.SerialNumber), 'osfullname': _clean_value('osfullname', osinfo.Caption), 'timezone': _clean_value('timezone', timeinfo.Description), 'windowsdomain': _clean_value('windowsdomain', net_info['Domain']), 'windowsdomaintype': _clean_value('windowsdomaintype', net_info['DomainType']), 'motherboard': { 'productname': _clean_value('motherboard.productname', motherboard['product']), 'serialnumber': _clean_value('motherboard.serialnumber', motherboard['serial']), } } # test for virtualized environments # I only had VMware available so the rest are unvalidated if 'VRTUAL' in biosinfo.Version: # (not a typo) grains['virtual'] = 'HyperV' elif 'A M I' in biosinfo.Version: grains['virtual'] = 'VirtualPC' elif 'VMware' in systeminfo.Model: grains['virtual'] = 'VMware' elif 'VirtualBox' in systeminfo.Model: grains['virtual'] = 'VirtualBox' elif 'Xen' in biosinfo.Version: grains['virtual'] = 'Xen' if 'HVM domU' in systeminfo.Model: grains['virtual_subtype'] = 'HVM domU' elif 'OpenStack' in systeminfo.Model: grains['virtual'] = 'OpenStack' return grains def _osx_platform_data(): ''' Additional data for macOS systems Returns: A dictionary containing values for the following: - model_name - boot_rom_version - smc_version - system_serialnumber ''' cmd = 'system_profiler SPHardwareDataType' hardware = __salt__['cmd.run'](cmd) grains = {} for line in hardware.splitlines(): field_name, _, field_val = line.partition(': ') if field_name.strip() == "Model Name": key = 'model_name' grains[key] = _clean_value(key, field_val) if field_name.strip() == "Boot ROM Version": key = 'boot_rom_version' grains[key] = _clean_value(key, field_val) if field_name.strip() == "SMC Version (system)": key = 'smc_version' grains[key] = _clean_value(key, field_val) if field_name.strip() == "Serial Number (system)": key = 'system_serialnumber' grains[key] = _clean_value(key, field_val) return grains def id_(): ''' Return the id ''' return {'id': __opts__.get('id', '')} _REPLACE_LINUX_RE = re.compile(r'\W(?:gnu/)?linux', re.IGNORECASE) # This maps (at most) the first ten characters (no spaces, lowercased) of # 'osfullname' to the 'os' grain that Salt traditionally uses. # Please see os_data() and _supported_dists. # If your system is not detecting properly it likely needs an entry here. _OS_NAME_MAP = { 'redhatente': 'RedHat', 'gentoobase': 'Gentoo', 'archarm': 'Arch ARM', 'arch': 'Arch', 'debian': 'Debian', 'raspbian': 'Raspbian', 'fedoraremi': 'Fedora', 'chapeau': 'Chapeau', 'korora': 'Korora', 'amazonami': 'Amazon', 'alt': 'ALT', 'enterprise': 'OEL', 'oracleserv': 'OEL', 'cloudserve': 'CloudLinux', 'cloudlinux': 'CloudLinux', 'pidora': 'Fedora', 'scientific': 'ScientificLinux', 'synology': 'Synology', 'nilrt': 'NILinuxRT', 'poky': 'Poky', 'manjaro': 'Manjaro', 'manjarolin': 'Manjaro', 'univention': 'Univention', 'antergos': 'Antergos', 'sles': 'SUSE', 'void': 'Void', 'slesexpand': 'RES', 'linuxmint': 'Mint', 'neon': 'KDE neon', } # Map the 'os' grain to the 'os_family' grain # These should always be capitalized entries as the lookup comes # post-_OS_NAME_MAP. If your system is having trouble with detection, please # make sure that the 'os' grain is capitalized and working correctly first. _OS_FAMILY_MAP = { 'Ubuntu': 'Debian', 'Fedora': 'RedHat', 'Chapeau': 'RedHat', 'Korora': 'RedHat', 'FedBerry': 'RedHat', 'CentOS': 'RedHat', 'GoOSe': 'RedHat', 'Scientific': 'RedHat', 'Amazon': 'RedHat', 'CloudLinux': 'RedHat', 'OVS': 'RedHat', 'OEL': 'RedHat', 'XCP': 'RedHat', 'XCP-ng': 'RedHat', 'XenServer': 'RedHat', 'RES': 'RedHat', 'Sangoma': 'RedHat', 'Mandrake': 'Mandriva', 'ESXi': 'VMware', 'Mint': 'Debian', 'VMwareESX': 'VMware', 'Bluewhite64': 'Bluewhite', 'Slamd64': 'Slackware', 'SLES': 'Suse', 'SUSE Enterprise Server': 'Suse', 'SUSE Enterprise Server': 'Suse', 'SLED': 'Suse', 'openSUSE': 'Suse', 'SUSE': 'Suse', 'openSUSE Leap': 'Suse', 'openSUSE Tumbleweed': 'Suse', 'SLES_SAP': 'Suse', 'Solaris': 'Solaris', 'SmartOS': 'Solaris', 'OmniOS': 'Solaris', 'OpenIndiana Development': 'Solaris', 'OpenIndiana': 'Solaris', 'OpenSolaris Development': 'Solaris', 'OpenSolaris': 'Solaris', 'Oracle Solaris': 'Solaris', 'Arch ARM': 'Arch', 'Manjaro': 'Arch', 'Antergos': 'Arch', 'ALT': 'RedHat', 'Trisquel': 'Debian', 'GCEL': 'Debian', 'Linaro': 'Debian', 'elementary OS': 'Debian', 'elementary': 'Debian', 'Univention': 'Debian', 'ScientificLinux': 'RedHat', 'Raspbian': 'Debian', 'Devuan': 'Debian', 'antiX': 'Debian', 'Kali': 'Debian', 'neon': 'Debian', 'Cumulus': 'Debian', 'Deepin': 'Debian', 'NILinuxRT': 'NILinuxRT', 'KDE neon': 'Debian', 'Void': 'Void', 'IDMS': 'Debian', 'Funtoo': 'Gentoo', 'AIX': 'AIX', 'TurnKey': 'Debian', } # Matches any possible format: # DISTRIB_ID="Ubuntu" # DISTRIB_ID='Mageia' # DISTRIB_ID=Fedora # DISTRIB_RELEASE='10.10' # DISTRIB_CODENAME='squeeze' # DISTRIB_DESCRIPTION='Ubuntu 10.10' _LSB_REGEX = re.compile(( '^(DISTRIB_(?:ID|RELEASE|CODENAME|DESCRIPTION))=(?:\'|")?' '([\\w\\s\\.\\-_]+)(?:\'|")?' )) def _linux_bin_exists(binary): ''' Does a binary exist in linux (depends on which, type, or whereis) ''' for search_cmd in ('which', 'type -ap'): try: return __salt__['cmd.retcode']( '{0} {1}'.format(search_cmd, binary) ) == 0 except salt.exceptions.CommandExecutionError: pass try: return len(__salt__['cmd.run_all']( 'whereis -b {0}'.format(binary) )['stdout'].split()) > 1 except salt.exceptions.CommandExecutionError: return False def _get_interfaces(): ''' Provide a dict of the connected interfaces and their ip addresses ''' global _INTERFACES if not _INTERFACES: _INTERFACES = salt.utils.network.interfaces() return _INTERFACES def _parse_lsb_release(): ret = {} try: log.trace('Attempting to parse /etc/lsb-release') with salt.utils.files.fopen('/etc/lsb-release') as ifile: for line in ifile: try: key, value = _LSB_REGEX.match(line.rstrip('\n')).groups()[:2] except AttributeError: pass else: # Adds lsb_distrib_{id,release,codename,description} ret['lsb_{0}'.format(key.lower())] = value.rstrip() except (IOError, OSError) as exc: log.trace('Failed to parse /etc/lsb-release: %s', exc) return ret def _parse_os_release(*os_release_files): ''' Parse os-release and return a parameter dictionary See http://www.freedesktop.org/software/systemd/man/os-release.html for specification of the file format. ''' ret = {} for filename in os_release_files: try: with salt.utils.files.fopen(filename) as ifile: regex = re.compile('^([\\w]+)=(?:\'|")?(.*?)(?:\'|")?$') for line in ifile: match = regex.match(line.strip()) if match: # Shell special characters ("$", quotes, backslash, # backtick) are escaped with backslashes ret[match.group(1)] = re.sub( r'\\([$"\'\\`])', r'\1', match.group(2) ) break except (IOError, OSError): pass return ret def _parse_cpe_name(cpe): ''' Parse CPE_NAME data from the os-release Info: https://csrc.nist.gov/projects/security-content-automation-protocol/scap-specifications/cpe :param cpe: :return: ''' part = { 'o': 'operating system', 'h': 'hardware', 'a': 'application', } ret = {} cpe = (cpe or '').split(':') if len(cpe) > 4 and cpe[0] == 'cpe': if cpe[1].startswith('/'): # WFN to URI ret['vendor'], ret['product'], ret['version'] = cpe[2:5] ret['phase'] = cpe[5] if len(cpe) > 5 else None ret['part'] = part.get(cpe[1][1:]) elif len(cpe) == 13 and cpe[1] == '2.3': # WFN to a string ret['vendor'], ret['product'], ret['version'], ret['phase'] = [x if x != '*' else None for x in cpe[3:7]] ret['part'] = part.get(cpe[2]) return ret def os_data(): ''' Return grains pertaining to the operating system ''' grains = { 'num_gpus': 0, 'gpus': [], } # Windows Server 2008 64-bit # ('Windows', 'MINIONNAME', '2008ServerR2', '6.1.7601', 'AMD64', # 'Intel64 Fam ily 6 Model 23 Stepping 6, GenuineIntel') # Ubuntu 10.04 # ('Linux', 'MINIONNAME', '2.6.32-38-server', # '#83-Ubuntu SMP Wed Jan 4 11:26:59 UTC 2012', 'x86_64', '') # pylint: disable=unpacking-non-sequence (grains['kernel'], grains['nodename'], grains['kernelrelease'], grains['kernelversion'], grains['cpuarch'], _) = platform.uname() # pylint: enable=unpacking-non-sequence if salt.utils.platform.is_proxy(): grains['kernel'] = 'proxy' grains['kernelrelease'] = 'proxy' grains['kernelversion'] = 'proxy' grains['osrelease'] = 'proxy' grains['os'] = 'proxy' grains['os_family'] = 'proxy' grains['osfullname'] = 'proxy' elif salt.utils.platform.is_windows(): grains['os'] = 'Windows' grains['os_family'] = 'Windows' grains.update(_memdata(grains)) grains.update(_windows_platform_data()) grains.update(_windows_cpudata()) grains.update(_windows_virtual(grains)) grains.update(_ps(grains)) if 'Server' in grains['osrelease']: osrelease_info = grains['osrelease'].split('Server', 1) osrelease_info[1] = osrelease_info[1].lstrip('R') else: osrelease_info = grains['osrelease'].split('.') for idx, value in enumerate(osrelease_info): if not value.isdigit(): continue osrelease_info[idx] = int(value) grains['osrelease_info'] = tuple(osrelease_info) grains['osfinger'] = '{os}-{ver}'.format( os=grains['os'], ver=grains['osrelease']) grains['init'] = 'Windows' return grains elif salt.utils.platform.is_linux(): # Add SELinux grain, if you have it if _linux_bin_exists('selinuxenabled'): log.trace('Adding selinux grains') grains['selinux'] = {} grains['selinux']['enabled'] = __salt__['cmd.retcode']( 'selinuxenabled' ) == 0 if _linux_bin_exists('getenforce'): grains['selinux']['enforced'] = __salt__['cmd.run']( 'getenforce' ).strip() # Add systemd grain, if you have it if _linux_bin_exists('systemctl') and _linux_bin_exists('localectl'): log.trace('Adding systemd grains') grains['systemd'] = {} systemd_info = __salt__['cmd.run']( 'systemctl --version' ).splitlines() grains['systemd']['version'] = systemd_info[0].split()[1] grains['systemd']['features'] = systemd_info[1] # Add init grain grains['init'] = 'unknown' log.trace('Adding init grain') try: os.stat('/run/systemd/system') grains['init'] = 'systemd' except (OSError, IOError): try: with salt.utils.files.fopen('/proc/1/cmdline') as fhr: init_cmdline = fhr.read().replace('\x00', ' ').split() except (IOError, OSError): pass else: try: init_bin = salt.utils.path.which(init_cmdline[0]) except IndexError: # Emtpy init_cmdline init_bin = None log.warning('Unable to fetch data from /proc/1/cmdline') if init_bin is not None and init_bin.endswith('bin/init'): supported_inits = (b'upstart', b'sysvinit', b'systemd') edge_len = max(len(x) for x in supported_inits) - 1 try: buf_size = __opts__['file_buffer_size'] except KeyError: # Default to the value of file_buffer_size for the minion buf_size = 262144 try: with salt.utils.files.fopen(init_bin, 'rb') as fp_: edge = b'' buf = fp_.read(buf_size).lower() while buf: buf = edge + buf for item in supported_inits: if item in buf: if six.PY3: item = item.decode('utf-8') grains['init'] = item buf = b'' break edge = buf[-edge_len:] buf = fp_.read(buf_size).lower() except (IOError, OSError) as exc: log.error( 'Unable to read from init_bin (%s): %s', init_bin, exc ) elif salt.utils.path.which('supervisord') in init_cmdline: grains['init'] = 'supervisord' elif salt.utils.path.which('dumb-init') in init_cmdline: # https://github.com/Yelp/dumb-init grains['init'] = 'dumb-init' elif salt.utils.path.which('tini') in init_cmdline: # https://github.com/krallin/tini grains['init'] = 'tini' elif init_cmdline == ['runit']: grains['init'] = 'runit' elif '/sbin/my_init' in init_cmdline: # Phusion Base docker container use runit for srv mgmt, but # my_init as pid1 grains['init'] = 'runit' else: log.debug( 'Could not determine init system from command line: (%s)', ' '.join(init_cmdline) ) # Add lsb grains on any distro with lsb-release. Note that this import # can fail on systems with lsb-release installed if the system package # does not install the python package for the python interpreter used by # Salt (i.e. python2 or python3) try: log.trace('Getting lsb_release distro information') import lsb_release # pylint: disable=import-error release = lsb_release.get_distro_information() for key, value in six.iteritems(release): key = key.lower() lsb_param = 'lsb_{0}{1}'.format( '' if key.startswith('distrib_') else 'distrib_', key ) grains[lsb_param] = value # Catch a NameError to workaround possible breakage in lsb_release # See https://github.com/saltstack/salt/issues/37867 except (ImportError, NameError): # if the python library isn't available, try to parse # /etc/lsb-release using regex log.trace('lsb_release python bindings not available') grains.update(_parse_lsb_release()) if grains.get('lsb_distrib_description', '').lower().startswith('antergos'): # Antergos incorrectly configures their /etc/lsb-release, # setting the DISTRIB_ID to "Arch". This causes the "os" grain # to be incorrectly set to "Arch". grains['osfullname'] = 'Antergos Linux' elif 'lsb_distrib_id' not in grains: log.trace( 'Failed to get lsb_distrib_id, trying to parse os-release' ) os_release = _parse_os_release('/etc/os-release', '/usr/lib/os-release') if os_release: if 'NAME' in os_release: grains['lsb_distrib_id'] = os_release['NAME'].strip() if 'VERSION_ID' in os_release: grains['lsb_distrib_release'] = os_release['VERSION_ID'] if 'VERSION_CODENAME' in os_release: grains['lsb_distrib_codename'] = os_release['VERSION_CODENAME'] elif 'PRETTY_NAME' in os_release: codename = os_release['PRETTY_NAME'] # https://github.com/saltstack/salt/issues/44108 if os_release['ID'] == 'debian': codename_match = re.search(r'\((\w+)\)$', codename) if codename_match: codename = codename_match.group(1) grains['lsb_distrib_codename'] = codename if 'CPE_NAME' in os_release: cpe = _parse_cpe_name(os_release['CPE_NAME']) if not cpe: log.error('Broken CPE_NAME format in /etc/os-release!') elif cpe.get('vendor', '').lower() in ['suse', 'opensuse']: grains['os'] = "SUSE" # openSUSE `osfullname` grain normalization if os_release.get("NAME") == "openSUSE Leap": grains['osfullname'] = "Leap" elif os_release.get("VERSION") == "Tumbleweed": grains['osfullname'] = os_release["VERSION"] # Override VERSION_ID, if CPE_NAME around if cpe.get('version') and cpe.get('vendor') == 'opensuse': # Keep VERSION_ID for SLES grains['lsb_distrib_release'] = cpe['version'] elif os.path.isfile('/etc/SuSE-release'): log.trace('Parsing distrib info from /etc/SuSE-release') grains['lsb_distrib_id'] = 'SUSE' version = '' patch = '' with salt.utils.files.fopen('/etc/SuSE-release') as fhr: for line in fhr: if 'enterprise' in line.lower(): grains['lsb_distrib_id'] = 'SLES' grains['lsb_distrib_codename'] = re.sub(r'\(.+\)', '', line).strip() elif 'version' in line.lower(): version = re.sub(r'[^0-9]', '', line) elif 'patchlevel' in line.lower(): patch = re.sub(r'[^0-9]', '', line) grains['lsb_distrib_release'] = version if patch: grains['lsb_distrib_release'] += '.' + patch patchstr = 'SP' + patch if grains['lsb_distrib_codename'] and patchstr not in grains['lsb_distrib_codename']: grains['lsb_distrib_codename'] += ' ' + patchstr if not grains.get('lsb_distrib_codename'): grains['lsb_distrib_codename'] = 'n.a' elif os.path.isfile('/etc/altlinux-release'): log.trace('Parsing distrib info from /etc/altlinux-release') # ALT Linux grains['lsb_distrib_id'] = 'altlinux' with salt.utils.files.fopen('/etc/altlinux-release') as ifile: # This file is symlinked to from: # /etc/fedora-release # /etc/redhat-release # /etc/system-release for line in ifile: # ALT Linux Sisyphus (unstable) comps = line.split() if comps[0] == 'ALT': grains['lsb_distrib_release'] = comps[2] grains['lsb_distrib_codename'] = \ comps[3].replace('(', '').replace(')', '') elif os.path.isfile('/etc/centos-release'): log.trace('Parsing distrib info from /etc/centos-release') # Maybe CentOS Linux; could also be SUSE Expanded Support. # SUSE ES has both, centos-release and redhat-release. if os.path.isfile('/etc/redhat-release'): with salt.utils.files.fopen('/etc/redhat-release') as ifile: for line in ifile: if "red hat enterprise linux server" in line.lower(): # This is a SUSE Expanded Support Rhel installation grains['lsb_distrib_id'] = 'RedHat' break grains.setdefault('lsb_distrib_id', 'CentOS') with salt.utils.files.fopen('/etc/centos-release') as ifile: for line in ifile: # Need to pull out the version and codename # in the case of custom content in /etc/centos-release find_release = re.compile(r'\d+\.\d+') find_codename = re.compile(r'(?<=\()(.*?)(?=\))') release = find_release.search(line) codename = find_codename.search(line) if release is not None: grains['lsb_distrib_release'] = release.group() if codename is not None: grains['lsb_distrib_codename'] = codename.group() elif os.path.isfile('/etc.defaults/VERSION') \ and os.path.isfile('/etc.defaults/synoinfo.conf'): grains['osfullname'] = 'Synology' log.trace( 'Parsing Synology distrib info from /etc/.defaults/VERSION' ) with salt.utils.files.fopen('/etc.defaults/VERSION', 'r') as fp_: synoinfo = {} for line in fp_: try: key, val = line.rstrip('\n').split('=') except ValueError: continue if key in ('majorversion', 'minorversion', 'buildnumber'): synoinfo[key] = val.strip('"') if len(synoinfo) != 3: log.warning( 'Unable to determine Synology version info. ' 'Please report this, as it is likely a bug.' ) else: grains['osrelease'] = ( '{majorversion}.{minorversion}-{buildnumber}' .format(**synoinfo) ) # Use the already intelligent platform module to get distro info # (though apparently it's not intelligent enough to strip quotes) log.trace( 'Getting OS name, release, and codename from ' 'distro.linux_distribution()' ) (osname, osrelease, oscodename) = \ [x.strip('"').strip("'") for x in linux_distribution(supported_dists=_supported_dists)] # Try to assign these three names based on the lsb info, they tend to # be more accurate than what python gets from /etc/DISTRO-release. # It's worth noting that Ubuntu has patched their Python distribution # so that linux_distribution() does the /etc/lsb-release parsing, but # we do it anyway here for the sake for full portability. if 'osfullname' not in grains: # If NI Linux RT distribution, set the grains['osfullname'] to 'nilrt' if grains.get('lsb_distrib_id', '').lower().startswith('nilrt'): grains['osfullname'] = 'nilrt' else: grains['osfullname'] = grains.get('lsb_distrib_id', osname).strip() if 'osrelease' not in grains: # NOTE: This is a workaround for CentOS 7 os-release bug # https://bugs.centos.org/view.php?id=8359 # /etc/os-release contains no minor distro release number so we fall back to parse # /etc/centos-release file instead. # Commit introducing this comment should be reverted after the upstream bug is released. if 'CentOS Linux 7' in grains.get('lsb_distrib_codename', ''): grains.pop('lsb_distrib_release', None) grains['osrelease'] = grains.get('lsb_distrib_release', osrelease).strip() grains['oscodename'] = grains.get('lsb_distrib_codename', '').strip() or oscodename if 'Red Hat' in grains['oscodename']: grains['oscodename'] = oscodename distroname = _REPLACE_LINUX_RE.sub('', grains['osfullname']).strip() # return the first ten characters with no spaces, lowercased shortname = distroname.replace(' ', '').lower()[:10] # this maps the long names from the /etc/DISTRO-release files to the # traditional short names that Salt has used. if 'os' not in grains: grains['os'] = _OS_NAME_MAP.get(shortname, distroname) grains.update(_linux_cpudata()) grains.update(_linux_gpu_data()) elif grains['kernel'] == 'SunOS': if salt.utils.platform.is_smartos(): # See https://github.com/joyent/smartos-live/issues/224 if HAS_UNAME: uname_v = os.uname()[3] # format: joyent_20161101T004406Z else: uname_v = os.name uname_v = uname_v[uname_v.index('_')+1:] grains['os'] = grains['osfullname'] = 'SmartOS' # store a parsed version of YYYY.MM.DD as osrelease grains['osrelease'] = ".".join([ uname_v.split('T')[0][0:4], uname_v.split('T')[0][4:6], uname_v.split('T')[0][6:8], ]) # store a untouched copy of the timestamp in osrelease_stamp grains['osrelease_stamp'] = uname_v elif os.path.isfile('/etc/release'): with salt.utils.files.fopen('/etc/release', 'r') as fp_: rel_data = fp_.read() try: release_re = re.compile( r'((?:Open|Oracle )?Solaris|OpenIndiana|OmniOS) (Development)?' r'\s*(\d+\.?\d*|v\d+)\s?[A-Z]*\s?(r\d+|\d+\/\d+|oi_\S+|snv_\S+)?' ) osname, development, osmajorrelease, osminorrelease = release_re.search(rel_data).groups() except AttributeError: # Set a blank osrelease grain and fallback to 'Solaris' # as the 'os' grain. grains['os'] = grains['osfullname'] = 'Solaris' grains['osrelease'] = '' else: if development is not None: osname = ' '.join((osname, development)) if HAS_UNAME: uname_v = os.uname()[3] else: uname_v = os.name grains['os'] = grains['osfullname'] = osname if osname in ['Oracle Solaris'] and uname_v.startswith(osmajorrelease): # Oracla Solars 11 and up have minor version in uname grains['osrelease'] = uname_v elif osname in ['OmniOS']: # OmniOS osrelease = [] osrelease.append(osmajorrelease[1:]) osrelease.append(osminorrelease[1:]) grains['osrelease'] = ".".join(osrelease) grains['osrelease_stamp'] = uname_v else: # Sun Solaris 10 and earlier/comparable osrelease = [] osrelease.append(osmajorrelease) if osminorrelease: osrelease.append(osminorrelease) grains['osrelease'] = ".".join(osrelease) grains['osrelease_stamp'] = uname_v grains.update(_sunos_cpudata()) elif grains['kernel'] == 'VMkernel': grains['os'] = 'ESXi' elif grains['kernel'] == 'Darwin': osrelease = __salt__['cmd.run']('sw_vers -productVersion') osname = __salt__['cmd.run']('sw_vers -productName') osbuild = __salt__['cmd.run']('sw_vers -buildVersion') grains['os'] = 'MacOS' grains['os_family'] = 'MacOS' grains['osfullname'] = "{0} {1}".format(osname, osrelease) grains['osrelease'] = osrelease grains['osbuild'] = osbuild grains['init'] = 'launchd' grains.update(_bsd_cpudata(grains)) grains.update(_osx_gpudata()) grains.update(_osx_platform_data()) elif grains['kernel'] == 'AIX': osrelease = __salt__['cmd.run']('oslevel') osrelease_techlevel = __salt__['cmd.run']('oslevel -r') osname = __salt__['cmd.run']('uname') grains['os'] = 'AIX' grains['osfullname'] = osname grains['osrelease'] = osrelease grains['osrelease_techlevel'] = osrelease_techlevel grains.update(_aix_cpudata()) else: grains['os'] = grains['kernel'] if grains['kernel'] == 'FreeBSD': try: grains['osrelease'] = __salt__['cmd.run']('freebsd-version -u').split('-')[0] except salt.exceptions.CommandExecutionError: # freebsd-version was introduced in 10.0. # derive osrelease from kernelversion prior to that grains['osrelease'] = grains['kernelrelease'].split('-')[0] grains.update(_bsd_cpudata(grains)) if grains['kernel'] in ('OpenBSD', 'NetBSD'): grains.update(_bsd_cpudata(grains)) grains['osrelease'] = grains['kernelrelease'].split('-')[0] if grains['kernel'] == 'NetBSD': grains.update(_netbsd_gpu_data()) if not grains['os']: grains['os'] = 'Unknown {0}'.format(grains['kernel']) grains['os_family'] = 'Unknown' else: # this assigns family names based on the os name # family defaults to the os name if not found grains['os_family'] = _OS_FAMILY_MAP.get(grains['os'], grains['os']) # Build the osarch grain. This grain will be used for platform-specific # considerations such as package management. Fall back to the CPU # architecture. if grains.get('os_family') == 'Debian': osarch = __salt__['cmd.run']('dpkg --print-architecture').strip() elif grains.get('os_family') in ['RedHat', 'Suse']: osarch = salt.utils.pkg.rpm.get_osarch() elif grains.get('os_family') in ('NILinuxRT', 'Poky'): archinfo = {} for line in __salt__['cmd.run']('opkg print-architecture').splitlines(): if line.startswith('arch'): _, arch, priority = line.split() archinfo[arch.strip()] = int(priority.strip()) # Return osarch in priority order (higher to lower) osarch = sorted(archinfo, key=archinfo.get, reverse=True) else: osarch = grains['cpuarch'] grains['osarch'] = osarch grains.update(_memdata(grains)) # Get the hardware and bios data grains.update(_hw_data(grains)) # Load the virtual machine info grains.update(_virtual(grains)) grains.update(_virtual_hv(grains)) grains.update(_ps(grains)) if grains.get('osrelease', ''): osrelease_info = grains['osrelease'].split('.') for idx, value in enumerate(osrelease_info): if not value.isdigit(): continue osrelease_info[idx] = int(value) grains['osrelease_info'] = tuple(osrelease_info) try: grains['osmajorrelease'] = int(grains['osrelease_info'][0]) except (IndexError, TypeError, ValueError): log.debug( 'Unable to derive osmajorrelease from osrelease_info \'%s\'. ' 'The osmajorrelease grain will not be set.', grains['osrelease_info'] ) os_name = grains['os' if grains.get('os') in ( 'Debian', 'FreeBSD', 'OpenBSD', 'NetBSD', 'Mac', 'Raspbian') else 'osfullname'] grains['osfinger'] = '{0}-{1}'.format( os_name, grains['osrelease'] if os_name in ('Ubuntu',) else grains['osrelease_info'][0]) return grains def locale_info(): ''' Provides defaultlanguage defaultencoding ''' grains = {} grains['locale_info'] = {} if salt.utils.platform.is_proxy(): return grains try: ( grains['locale_info']['defaultlanguage'], grains['locale_info']['defaultencoding'] ) = locale.getdefaultlocale() except Exception: # locale.getdefaultlocale can ValueError!! Catch anything else it # might do, per #2205 grains['locale_info']['defaultlanguage'] = 'unknown' grains['locale_info']['defaultencoding'] = 'unknown' grains['locale_info']['detectedencoding'] = __salt_system_encoding__ if _DATEUTIL_TZ: grains['locale_info']['timezone'] = datetime.datetime.now(dateutil.tz.tzlocal()).tzname() return grains def hostname(): ''' Return fqdn, hostname, domainname ''' # This is going to need some work # Provides: # fqdn # host # localhost # domain global __FQDN__ grains = {} if salt.utils.platform.is_proxy(): return grains grains['localhost'] = socket.gethostname() if __FQDN__ is None: __FQDN__ = salt.utils.network.get_fqhostname() # On some distros (notably FreeBSD) if there is no hostname set # salt.utils.network.get_fqhostname() will return None. # In this case we punt and log a message at error level, but force the # hostname and domain to be localhost.localdomain # Otherwise we would stacktrace below if __FQDN__ is None: # still! log.error('Having trouble getting a hostname. Does this machine have its hostname and domain set properly?') __FQDN__ = 'localhost.localdomain' grains['fqdn'] = __FQDN__ (grains['host'], grains['domain']) = grains['fqdn'].partition('.')[::2] return grains def append_domain(): ''' Return append_domain if set ''' grain = {} if salt.utils.platform.is_proxy(): return grain if 'append_domain' in __opts__: grain['append_domain'] = __opts__['append_domain'] return grain def fqdns(): ''' Return all known FQDNs for the system by enumerating all interfaces and then trying to reverse resolve them (excluding 'lo' interface). ''' # Provides: # fqdns grains = {} fqdns = set() addresses = salt.utils.network.ip_addrs(include_loopback=False, interface_data=_get_interfaces()) addresses.extend(salt.utils.network.ip_addrs6(include_loopback=False, interface_data=_get_interfaces())) err_message = 'Exception during resolving address: %s' for ip in addresses: try: name, aliaslist, addresslist = socket.gethostbyaddr(ip) fqdns.update([socket.getfqdn(name)] + [als for als in aliaslist if salt.utils.network.is_fqdn(als)]) except socket.herror as err: if err.errno == 0: # No FQDN for this IP address, so we don't need to know this all the time. log.debug("Unable to resolve address %s: %s", ip, err) else: log.error(err_message, err) except (socket.error, socket.gaierror, socket.timeout) as err: log.error(err_message, err) return {"fqdns": sorted(list(fqdns))} def ip_fqdn(): ''' Return ip address and FQDN grains ''' if salt.utils.platform.is_proxy(): return {} ret = {} ret['ipv4'] = salt.utils.network.ip_addrs(include_loopback=True) ret['ipv6'] = salt.utils.network.ip_addrs6(include_loopback=True) _fqdn = hostname()['fqdn'] for socket_type, ipv_num in ((socket.AF_INET, '4'), (socket.AF_INET6, '6')): key = 'fqdn_ip' + ipv_num if not ret['ipv' + ipv_num]: ret[key] = [] else: try: start_time = datetime.datetime.utcnow() info = socket.getaddrinfo(_fqdn, None, socket_type) ret[key] = list(set(item[4][0] for item in info)) except socket.error: timediff = datetime.datetime.utcnow() - start_time if timediff.seconds > 5 and __opts__['__role'] == 'master': log.warning( 'Unable to find IPv%s record for "%s" causing a %s ' 'second timeout when rendering grains. Set the dns or ' '/etc/hosts for IPv%s to clear this.', ipv_num, _fqdn, timediff, ipv_num ) ret[key] = [] return ret def ip_interfaces(): ''' Provide a dict of the connected interfaces and their ip addresses The addresses will be passed as a list for each interface ''' # Provides: # ip_interfaces if salt.utils.platform.is_proxy(): return {} ret = {} ifaces = _get_interfaces() for face in ifaces: iface_ips = [] for inet in ifaces[face].get('inet', []): if 'address' in inet: iface_ips.append(inet['address']) for inet in ifaces[face].get('inet6', []): if 'address' in inet: iface_ips.append(inet['address']) for secondary in ifaces[face].get('secondary', []): if 'address' in secondary: iface_ips.append(secondary['address']) ret[face] = iface_ips return {'ip_interfaces': ret} def ip4_interfaces(): ''' Provide a dict of the connected interfaces and their ip4 addresses The addresses will be passed as a list for each interface ''' # Provides: # ip_interfaces if salt.utils.platform.is_proxy(): return {} ret = {} ifaces = _get_interfaces() for face in ifaces: iface_ips = [] for inet in ifaces[face].get('inet', []): if 'address' in inet: iface_ips.append(inet['address']) for secondary in ifaces[face].get('secondary', []): if 'address' in secondary: iface_ips.append(secondary['address']) ret[face] = iface_ips return {'ip4_interfaces': ret} def ip6_interfaces(): ''' Provide a dict of the connected interfaces and their ip6 addresses The addresses will be passed as a list for each interface ''' # Provides: # ip_interfaces if salt.utils.platform.is_proxy(): return {} ret = {} ifaces = _get_interfaces() for face in ifaces: iface_ips = [] for inet in ifaces[face].get('inet6', []): if 'address' in inet: iface_ips.append(inet['address']) for secondary in ifaces[face].get('secondary', []): if 'address' in secondary: iface_ips.append(secondary['address']) ret[face] = iface_ips return {'ip6_interfaces': ret} def hwaddr_interfaces(): ''' Provide a dict of the connected interfaces and their hw addresses (Mac Address) ''' # Provides: # hwaddr_interfaces ret = {} ifaces = _get_interfaces() for face in ifaces: if 'hwaddr' in ifaces[face]: ret[face] = ifaces[face]['hwaddr'] return {'hwaddr_interfaces': ret} def get_machine_id(): ''' Provide the machine-id for machine/virtualization combination ''' # Provides: # machine-id if platform.system() == 'AIX': return _aix_get_machine_id() locations = ['/etc/machine-id', '/var/lib/dbus/machine-id'] existing_locations = [loc for loc in locations if os.path.exists(loc)] if not existing_locations: return {} else: with salt.utils.files.fopen(existing_locations[0]) as machineid: return {'machine_id': machineid.read().strip()} def cwd(): ''' Current working directory ''' return {'cwd': os.getcwd()} def path(): ''' Return the path ''' # Provides: # path return {'path': os.environ.get('PATH', '').strip()} def pythonversion(): ''' Return the Python version ''' # Provides: # pythonversion return {'pythonversion': list(sys.version_info)} def pythonpath(): ''' Return the Python path ''' # Provides: # pythonpath return {'pythonpath': sys.path} def pythonexecutable(): ''' Return the python executable in use ''' # Provides: # pythonexecutable return {'pythonexecutable': sys.executable} def saltpath(): ''' Return the path of the salt module ''' # Provides: # saltpath salt_path = os.path.abspath(os.path.join(__file__, os.path.pardir)) return {'saltpath': os.path.dirname(salt_path)} def saltversion(): ''' Return the version of salt ''' # Provides: # saltversion from salt.version import __version__ return {'saltversion': __version__} def zmqversion(): ''' Return the zeromq version ''' # Provides: # zmqversion try: import zmq return {'zmqversion': zmq.zmq_version()} # pylint: disable=no-member except ImportError: return {} def saltversioninfo(): ''' Return the version_info of salt .. versionadded:: 0.17.0 ''' # Provides: # saltversioninfo from salt.version import __version_info__ return {'saltversioninfo': list(__version_info__)} def _hw_data(osdata): ''' Get system specific hardware data from dmidecode Provides biosversion productname manufacturer serialnumber biosreleasedate uuid .. versionadded:: 0.9.5 ''' if salt.utils.platform.is_proxy(): return {} grains = {} if osdata['kernel'] == 'Linux' and os.path.exists('/sys/class/dmi/id'): # On many Linux distributions basic firmware information is available via sysfs # requires CONFIG_DMIID to be enabled in the Linux kernel configuration sysfs_firmware_info = { 'biosversion': 'bios_version', 'productname': 'product_name', 'manufacturer': 'sys_vendor', 'biosreleasedate': 'bios_date', 'uuid': 'product_uuid', 'serialnumber': 'product_serial' } for key, fw_file in sysfs_firmware_info.items(): contents_file = os.path.join('/sys/class/dmi/id', fw_file) if os.path.exists(contents_file): try: with salt.utils.files.fopen(contents_file, 'r') as ifile: grains[key] = salt.utils.stringutils.to_unicode(ifile.read().strip(), errors='replace') if key == 'uuid': grains['uuid'] = grains['uuid'].lower() except (IOError, OSError) as err: # PermissionError is new to Python 3, but corresponds to the EACESS and # EPERM error numbers. Use those instead here for PY2 compatibility. if err.errno == EACCES or err.errno == EPERM: # Skip the grain if non-root user has no access to the file. pass elif salt.utils.path.which_bin(['dmidecode', 'smbios']) is not None and not ( salt.utils.platform.is_smartos() or ( # SunOS on SPARC - 'smbios: failed to load SMBIOS: System does not export an SMBIOS table' osdata['kernel'] == 'SunOS' and osdata['cpuarch'].startswith('sparc') )): # On SmartOS (possibly SunOS also) smbios only works in the global zone # smbios is also not compatible with linux's smbios (smbios -s = print summarized) grains = { 'biosversion': __salt__['smbios.get']('bios-version'), 'productname': __salt__['smbios.get']('system-product-name'), 'manufacturer': __salt__['smbios.get']('system-manufacturer'), 'biosreleasedate': __salt__['smbios.get']('bios-release-date'), 'uuid': __salt__['smbios.get']('system-uuid') } grains = dict([(key, val) for key, val in grains.items() if val is not None]) uuid = __salt__['smbios.get']('system-uuid') if uuid is not None: grains['uuid'] = uuid.lower() for serial in ('system-serial-number', 'chassis-serial-number', 'baseboard-serial-number'): serial = __salt__['smbios.get'](serial) if serial is not None: grains['serialnumber'] = serial break elif salt.utils.path.which_bin(['fw_printenv']) is not None: # ARM Linux devices expose UBOOT env variables via fw_printenv hwdata = { 'manufacturer': 'manufacturer', 'serialnumber': 'serial#', 'productname': 'DeviceDesc', } for grain_name, cmd_key in six.iteritems(hwdata): result = __salt__['cmd.run_all']('fw_printenv {0}'.format(cmd_key)) if result['retcode'] == 0: uboot_keyval = result['stdout'].split('=') grains[grain_name] = _clean_value(grain_name, uboot_keyval[1]) elif osdata['kernel'] == 'FreeBSD': # On FreeBSD /bin/kenv (already in base system) # can be used instead of dmidecode kenv = salt.utils.path.which('kenv') if kenv: # In theory, it will be easier to add new fields to this later fbsd_hwdata = { 'biosversion': 'smbios.bios.version', 'manufacturer': 'smbios.system.maker', 'serialnumber': 'smbios.system.serial', 'productname': 'smbios.system.product', 'biosreleasedate': 'smbios.bios.reldate', 'uuid': 'smbios.system.uuid', } for key, val in six.iteritems(fbsd_hwdata): value = __salt__['cmd.run']('{0} {1}'.format(kenv, val)) grains[key] = _clean_value(key, value) elif osdata['kernel'] == 'OpenBSD': sysctl = salt.utils.path.which('sysctl') hwdata = {'biosversion': 'hw.version', 'manufacturer': 'hw.vendor', 'productname': 'hw.product', 'serialnumber': 'hw.serialno', 'uuid': 'hw.uuid'} for key, oid in six.iteritems(hwdata): value = __salt__['cmd.run']('{0} -n {1}'.format(sysctl, oid)) if not value.endswith(' value is not available'): grains[key] = _clean_value(key, value) elif osdata['kernel'] == 'NetBSD': sysctl = salt.utils.path.which('sysctl') nbsd_hwdata = { 'biosversion': 'machdep.dmi.board-version', 'manufacturer': 'machdep.dmi.system-vendor', 'serialnumber': 'machdep.dmi.system-serial', 'productname': 'machdep.dmi.system-product', 'biosreleasedate': 'machdep.dmi.bios-date', 'uuid': 'machdep.dmi.system-uuid', } for key, oid in six.iteritems(nbsd_hwdata): result = __salt__['cmd.run_all']('{0} -n {1}'.format(sysctl, oid)) if result['retcode'] == 0: grains[key] = _clean_value(key, result['stdout']) elif osdata['kernel'] == 'Darwin': grains['manufacturer'] = 'Apple Inc.' sysctl = salt.utils.path.which('sysctl') hwdata = {'productname': 'hw.model'} for key, oid in hwdata.items(): value = __salt__['cmd.run']('{0} -b {1}'.format(sysctl, oid)) if not value.endswith(' is invalid'): grains[key] = _clean_value(key, value) elif osdata['kernel'] == 'SunOS' and osdata['cpuarch'].startswith('sparc'): # Depending on the hardware model, commands can report different bits # of information. With that said, consolidate the output from various # commands and attempt various lookups. data = "" for (cmd, args) in (('/usr/sbin/prtdiag', '-v'), ('/usr/sbin/prtconf', '-vp'), ('/usr/sbin/virtinfo', '-a')): if salt.utils.path.which(cmd): # Also verifies that cmd is executable data += __salt__['cmd.run']('{0} {1}'.format(cmd, args)) data += '\n' sn_regexes = [ re.compile(r) for r in [ r'(?im)^\s*Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag r'(?im)^\s*chassis-sn:\s*(\S+)', # prtconf r'(?im)^\s*Chassis\s+Serial#:\s*(\S+)', # virtinfo ] ] obp_regexes = [ re.compile(r) for r in [ r'(?im)^\s*System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag r'(?im)^\s*version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf ] ] fw_regexes = [ re.compile(r) for r in [ r'(?im)^\s*Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag ] ] uuid_regexes = [ re.compile(r) for r in [ r'(?im)^\s*Domain\s+UUID:\s*(\S+)', # virtinfo ] ] manufacture_regexes = [ re.compile(r) for r in [ r'(?im)^\s*System\s+Configuration:\s*(.*)(?=sun)', # prtdiag ] ] product_regexes = [ re.compile(r) for r in [ r'(?im)^\s*System\s+Configuration:\s*.*?sun\d\S+[^\S\r\n]*(.*)', # prtdiag r'(?im)^[^\S\r\n]*banner-name:[^\S\r\n]*(.*)', # prtconf r'(?im)^[^\S\r\n]*product-name:[^\S\r\n]*(.*)', # prtconf ] ] sn_regexes = [ re.compile(r) for r in [ r'(?im)Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag r'(?i)Chassis\s+Serial#:\s*(\S+)', # virtinfo r'(?i)chassis-sn:\s*(\S+)', # prtconf ] ] obp_regexes = [ re.compile(r) for r in [ r'(?im)System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag r'(?im)version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf ] ] fw_regexes = [ re.compile(r) for r in [ r'(?i)Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag ] ] uuid_regexes = [ re.compile(r) for r in [ r'(?i)Domain\s+UUID:\s+(\S+)', # virtinfo ] ] for regex in sn_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: grains['serialnumber'] = res.group(1).strip().replace("'", "") break for regex in obp_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: obp_rev, obp_date = res.groups()[0:2] # Limit the number in case we found the data in multiple places grains['biosversion'] = obp_rev.strip().replace("'", "") grains['biosreleasedate'] = obp_date.strip().replace("'", "") for regex in fw_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: fw_rev, fw_date = res.groups()[0:2] grains['systemfirmware'] = fw_rev.strip().replace("'", "") grains['systemfirmwaredate'] = fw_date.strip().replace("'", "") break for regex in uuid_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: grains['uuid'] = res.group(1).strip().replace("'", "") break for regex in manufacture_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: grains['manufacture'] = res.group(1).strip().replace("'", "") break for regex in product_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: t_productname = res.group(1).strip().replace("'", "") if t_productname: grains['product'] = t_productname grains['productname'] = t_productname break elif osdata['kernel'] == 'AIX': cmd = salt.utils.path.which('prtconf') if cmd: data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'), ('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')): for regex in [re.compile(r) for r in [regstring]]: res = regex.search(data) if res and len(res.groups()) >= 1: grains[dest] = res.group(1).strip().replace("'", '') product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')] for regex in product_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",") break else: log.error('The \'prtconf\' binary was not found in $PATH.') elif osdata['kernel'] == 'AIX': cmd = salt.utils.path.which('prtconf') if data: data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'), ('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')): for regex in [re.compile(r) for r in [regstring]]: res = regex.search(data) if res and len(res.groups()) >= 1: grains[dest] = res.group(1).strip().replace("'", '') product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')] for regex in product_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",") break else: log.error('The \'prtconf\' binary was not found in $PATH.') return grains def _get_hash_by_shell(): ''' Shell-out Python 3 for compute reliable hash :return: ''' id_ = __opts__.get('id', '') id_hash = None py_ver = sys.version_info[:2] if py_ver >= (3, 3): # Python 3.3 enabled hash randomization, so we need to shell out to get # a reliable hash. id_hash = __salt__['cmd.run']([sys.executable, '-c', 'print(hash("{0}"))'.format(id_)], env={'PYTHONHASHSEED': '0'}) try: id_hash = int(id_hash) except (TypeError, ValueError): log.debug('Failed to hash the ID to get the server_id grain. Result of hash command: %s', id_hash) id_hash = None if id_hash is None: # Python < 3.3 or error encountered above id_hash = hash(id_) return abs(id_hash % (2 ** 31)) def get_server_id(): ''' Provides an integer based on the FQDN of a machine. Useful as server-id in MySQL replication or anywhere else you'll need an ID like this. ''' # Provides: # server_id if salt.utils.platform.is_proxy(): server_id = {} else: use_crc = __opts__.get('server_id_use_crc') if bool(use_crc): id_hash = getattr(zlib, use_crc, zlib.adler32)(__opts__.get('id', '').encode()) & 0xffffffff else: log.debug('This server_id is computed not by Adler32 nor by CRC32. ' 'Please use "server_id_use_crc" option and define algorithm you ' 'prefer (default "Adler32"). Starting with Sodium, the ' 'server_id will be computed with Adler32 by default.') id_hash = _get_hash_by_shell() server_id = {'server_id': id_hash} return server_id def get_master(): ''' Provides the minion with the name of its master. This is useful in states to target other services running on the master. ''' # Provides: # master return {'master': __opts__.get('master', '')} def default_gateway(): ''' Populates grains which describe whether a server has a default gateway configured or not. Uses `ip -4 route show` and `ip -6 route show` and greps for a `default` at the beginning of any line. Assuming the standard `default via <ip>` format for default gateways, it will also parse out the ip address of the default gateway, and put it in ip4_gw or ip6_gw. If the `ip` command is unavailable, no grains will be populated. Currently does not support multiple default gateways. The grains will be set to the first default gateway found. List of grains: ip4_gw: True # ip/True/False if default ipv4 gateway ip6_gw: True # ip/True/False if default ipv6 gateway ip_gw: True # True if either of the above is True, False otherwise ''' grains = {} ip_bin = salt.utils.path.which('ip') if not ip_bin: return {} grains['ip_gw'] = False grains['ip4_gw'] = False grains['ip6_gw'] = False for ip_version in ('4', '6'): try: out = __salt__['cmd.run']([ip_bin, '-' + ip_version, 'route', 'show']) for line in out.splitlines(): if line.startswith('default'): grains['ip_gw'] = True grains['ip{0}_gw'.format(ip_version)] = True try: via, gw_ip = line.split()[1:3] except ValueError: pass else: if via == 'via': grains['ip{0}_gw'.format(ip_version)] = gw_ip break except Exception: continue return grains def kernelparams(): ''' Return the kernel boot parameters ''' if salt.utils.platform.is_windows(): # TODO: add grains using `bcdedit /enum {current}` return {} else: try: with salt.utils.files.fopen('/proc/cmdline', 'r') as fhr: cmdline = fhr.read() grains = {'kernelparams': []} for data in [item.split('=') for item in salt.utils.args.shlex_split(cmdline)]: value = None if len(data) == 2: value = data[1].strip('"') grains['kernelparams'] += [(data[0], value)] except IOError as exc: grains = {} log.debug('Failed to read /proc/cmdline: %s', exc) return grains
saltstack/salt
salt/grains/core.py
get_machine_id
python
def get_machine_id(): ''' Provide the machine-id for machine/virtualization combination ''' # Provides: # machine-id if platform.system() == 'AIX': return _aix_get_machine_id() locations = ['/etc/machine-id', '/var/lib/dbus/machine-id'] existing_locations = [loc for loc in locations if os.path.exists(loc)] if not existing_locations: return {} else: with salt.utils.files.fopen(existing_locations[0]) as machineid: return {'machine_id': machineid.read().strip()}
Provide the machine-id for machine/virtualization combination
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/grains/core.py#L2342-L2357
[ "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 _aix_get_machine_id():\n '''\n Parse the output of lsattr -El sys0 for os_uuid\n '''\n grains = {}\n cmd = salt.utils.path.which('lsattr')\n if cmd:\n data = __salt__['cmd.run']('{0} -El sys0'.format(cmd)) + os.linesep\n uuid_regexes = [re.compile(r'(?im)^\\s*os_uuid\\s+(\\S+)\\s+(.*)')]\n for regex in uuid_regexes:\n res = regex.search(data)\n if res and len(res.groups()) >= 1:\n grains['machine_id'] = res.group(1).strip()\n break\n else:\n log.error('The \\'lsattr\\' binary was not found in $PATH.')\n return grains\n" ]
# -*- coding: utf-8 -*- ''' The static grains, these are the core, or built in grains. When grains are loaded they are not loaded in the same way that modules are loaded, grain functions are detected and executed, the functions MUST return a dict which will be applied to the main grains dict. This module will always be executed first, so that any grains loaded here in the core module can be overwritten just by returning dict keys with the same value as those returned here ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import socket import sys import re import platform import logging import locale import uuid import zlib from errno import EACCES, EPERM import datetime import warnings # pylint: disable=import-error try: import dateutil.tz _DATEUTIL_TZ = True except ImportError: _DATEUTIL_TZ = False __proxyenabled__ = ['*'] __FQDN__ = None # Extend the default list of supported distros. This will be used for the # /etc/DISTRO-release checking that is part of linux_distribution() from platform import _supported_dists _supported_dists += ('arch', 'mageia', 'meego', 'vmware', 'bluewhite64', 'slamd64', 'ovs', 'system', 'mint', 'oracle', 'void') # linux_distribution deprecated in py3.7 try: from platform import linux_distribution as _deprecated_linux_distribution def linux_distribution(**kwargs): with warnings.catch_warnings(): warnings.simplefilter("ignore") return _deprecated_linux_distribution(**kwargs) except ImportError: from distro import linux_distribution # Import salt libs import salt.exceptions import salt.log import salt.utils.args import salt.utils.dns import salt.utils.files import salt.utils.network import salt.utils.path import salt.utils.pkg.rpm import salt.utils.platform import salt.utils.stringutils import salt.utils.versions from salt.ext import six from salt.ext.six.moves import range if salt.utils.platform.is_windows(): import salt.utils.win_osinfo # Solve the Chicken and egg problem where grains need to run before any # of the modules are loaded and are generally available for any usage. import salt.modules.cmdmod import salt.modules.smbios __salt__ = { 'cmd.run': salt.modules.cmdmod._run_quiet, 'cmd.retcode': salt.modules.cmdmod._retcode_quiet, 'cmd.run_all': salt.modules.cmdmod._run_all_quiet, 'smbios.records': salt.modules.smbios.records, 'smbios.get': salt.modules.smbios.get, } log = logging.getLogger(__name__) HAS_WMI = False if salt.utils.platform.is_windows(): # attempt to import the python wmi module # the Windows minion uses WMI for some of its grains try: import wmi # pylint: disable=import-error import salt.utils.winapi import win32api import salt.utils.win_reg HAS_WMI = True except ImportError: log.exception( 'Unable to import Python wmi module, some core grains ' 'will be missing' ) HAS_UNAME = True if not hasattr(os, 'uname'): HAS_UNAME = False _INTERFACES = {} def _windows_cpudata(): ''' Return some CPU information on Windows minions ''' # Provides: # num_cpus # cpu_model grains = {} if 'NUMBER_OF_PROCESSORS' in os.environ: # Cast to int so that the logic isn't broken when used as a # conditional in templating. Also follows _linux_cpudata() try: grains['num_cpus'] = int(os.environ['NUMBER_OF_PROCESSORS']) except ValueError: grains['num_cpus'] = 1 grains['cpu_model'] = salt.utils.win_reg.read_value( hive="HKEY_LOCAL_MACHINE", key="HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", vname="ProcessorNameString").get('vdata') return grains def _linux_cpudata(): ''' Return some CPU information for Linux minions ''' # Provides: # num_cpus # cpu_model # cpu_flags grains = {} cpuinfo = '/proc/cpuinfo' # Parse over the cpuinfo file if os.path.isfile(cpuinfo): with salt.utils.files.fopen(cpuinfo, 'r') as _fp: grains['num_cpus'] = 0 for line in _fp: comps = line.split(':') if not len(comps) > 1: continue key = comps[0].strip() val = comps[1].strip() if key == 'processor': grains['num_cpus'] += 1 elif key == 'model name': grains['cpu_model'] = val elif key == 'flags': grains['cpu_flags'] = val.split() elif key == 'Features': grains['cpu_flags'] = val.split() # ARM support - /proc/cpuinfo # # Processor : ARMv6-compatible processor rev 7 (v6l) # BogoMIPS : 697.95 # Features : swp half thumb fastmult vfp edsp java tls # CPU implementer : 0x41 # CPU architecture: 7 # CPU variant : 0x0 # CPU part : 0xb76 # CPU revision : 7 # # Hardware : BCM2708 # Revision : 0002 # Serial : 00000000 elif key == 'Processor': grains['cpu_model'] = val.split('-')[0] grains['num_cpus'] = 1 if 'num_cpus' not in grains: grains['num_cpus'] = 0 if 'cpu_model' not in grains: grains['cpu_model'] = 'Unknown' if 'cpu_flags' not in grains: grains['cpu_flags'] = [] return grains def _linux_gpu_data(): ''' num_gpus: int gpus: - vendor: nvidia|amd|ati|... model: string ''' if __opts__.get('enable_lspci', True) is False: return {} if __opts__.get('enable_gpu_grains', True) is False: return {} lspci = salt.utils.path.which('lspci') if not lspci: log.debug( 'The `lspci` binary is not available on the system. GPU grains ' 'will not be available.' ) return {} # dominant gpu vendors to search for (MUST be lowercase for matching below) known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed'] gpu_classes = ('vga compatible controller', '3d controller') devs = [] try: lspci_out = __salt__['cmd.run']('{0} -vmm'.format(lspci)) cur_dev = {} error = False # Add a blank element to the lspci_out.splitlines() list, # otherwise the last device is not evaluated as a cur_dev and ignored. lspci_list = lspci_out.splitlines() lspci_list.append('') for line in lspci_list: # check for record-separating empty lines if line == '': if cur_dev.get('Class', '').lower() in gpu_classes: devs.append(cur_dev) cur_dev = {} continue if re.match(r'^\w+:\s+.*', line): key, val = line.split(':', 1) cur_dev[key.strip()] = val.strip() else: error = True log.debug('Unexpected lspci output: \'%s\'', line) if error: log.warning( 'Error loading grains, unexpected linux_gpu_data output, ' 'check that you have a valid shell configured and ' 'permissions to run lspci command' ) except OSError: pass gpus = [] for gpu in devs: vendor_strings = re.split('[^A-Za-z0-9]', gpu['Vendor'].lower()) # default vendor to 'unknown', overwrite if we match a known one vendor = 'unknown' for name in known_vendors: # search for an 'expected' vendor name in the list of strings if name in vendor_strings: vendor = name break gpus.append({'vendor': vendor, 'model': gpu['Device']}) grains = {} grains['num_gpus'] = len(gpus) grains['gpus'] = gpus return grains def _netbsd_gpu_data(): ''' num_gpus: int gpus: - vendor: nvidia|amd|ati|... model: string ''' known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed'] gpus = [] try: pcictl_out = __salt__['cmd.run']('pcictl pci0 list') for line in pcictl_out.splitlines(): for vendor in known_vendors: vendor_match = re.match( r'[0-9:]+ ({0}) (.+) \(VGA .+\)'.format(vendor), line, re.IGNORECASE ) if vendor_match: gpus.append({'vendor': vendor_match.group(1), 'model': vendor_match.group(2)}) except OSError: pass grains = {} grains['num_gpus'] = len(gpus) grains['gpus'] = gpus return grains def _osx_gpudata(): ''' num_gpus: int gpus: - vendor: nvidia|amd|ati|... model: string ''' gpus = [] try: pcictl_out = __salt__['cmd.run']('system_profiler SPDisplaysDataType') for line in pcictl_out.splitlines(): fieldname, _, fieldval = line.partition(': ') if fieldname.strip() == "Chipset Model": vendor, _, model = fieldval.partition(' ') vendor = vendor.lower() gpus.append({'vendor': vendor, 'model': model}) except OSError: pass grains = {} grains['num_gpus'] = len(gpus) grains['gpus'] = gpus return grains def _bsd_cpudata(osdata): ''' Return CPU information for BSD-like systems ''' # Provides: # cpuarch # num_cpus # cpu_model # cpu_flags sysctl = salt.utils.path.which('sysctl') arch = salt.utils.path.which('arch') cmds = {} if sysctl: cmds.update({ 'num_cpus': '{0} -n hw.ncpu'.format(sysctl), 'cpuarch': '{0} -n hw.machine'.format(sysctl), 'cpu_model': '{0} -n hw.model'.format(sysctl), }) if arch and osdata['kernel'] == 'OpenBSD': cmds['cpuarch'] = '{0} -s'.format(arch) if osdata['kernel'] == 'Darwin': cmds['cpu_model'] = '{0} -n machdep.cpu.brand_string'.format(sysctl) cmds['cpu_flags'] = '{0} -n machdep.cpu.features'.format(sysctl) grains = dict([(k, __salt__['cmd.run'](v)) for k, v in six.iteritems(cmds)]) if 'cpu_flags' in grains and isinstance(grains['cpu_flags'], six.string_types): grains['cpu_flags'] = grains['cpu_flags'].split(' ') if osdata['kernel'] == 'NetBSD': grains['cpu_flags'] = [] for line in __salt__['cmd.run']('cpuctl identify 0').splitlines(): cpu_match = re.match(r'cpu[0-9]:\ features[0-9]?\ .+<(.+)>', line) if cpu_match: flag = cpu_match.group(1).split(',') grains['cpu_flags'].extend(flag) if osdata['kernel'] == 'FreeBSD' and os.path.isfile('/var/run/dmesg.boot'): grains['cpu_flags'] = [] # TODO: at least it needs to be tested for BSD other then FreeBSD with salt.utils.files.fopen('/var/run/dmesg.boot', 'r') as _fp: cpu_here = False for line in _fp: if line.startswith('CPU: '): cpu_here = True # starts CPU descr continue if cpu_here: if not line.startswith(' '): break # game over if 'Features' in line: start = line.find('<') end = line.find('>') if start > 0 and end > 0: flag = line[start + 1:end].split(',') grains['cpu_flags'].extend(flag) try: grains['num_cpus'] = int(grains['num_cpus']) except ValueError: grains['num_cpus'] = 1 return grains def _sunos_cpudata(): ''' Return the CPU information for Solaris-like systems ''' # Provides: # cpuarch # num_cpus # cpu_model # cpu_flags grains = {} grains['cpu_flags'] = [] grains['cpuarch'] = __salt__['cmd.run']('isainfo -k') psrinfo = '/usr/sbin/psrinfo 2>/dev/null' grains['num_cpus'] = len(__salt__['cmd.run'](psrinfo, python_shell=True).splitlines()) kstat_info = 'kstat -p cpu_info:*:*:brand' for line in __salt__['cmd.run'](kstat_info).splitlines(): match = re.match(r'(\w+:\d+:\w+\d+:\w+)\s+(.+)', line) if match: grains['cpu_model'] = match.group(2) isainfo = 'isainfo -n -v' for line in __salt__['cmd.run'](isainfo).splitlines(): match = re.match(r'^\s+(.+)', line) if match: cpu_flags = match.group(1).split() grains['cpu_flags'].extend(cpu_flags) return grains def _aix_cpudata(): ''' Return CPU information for AIX systems ''' # Provides: # cpuarch # num_cpus # cpu_model # cpu_flags grains = {} cmd = salt.utils.path.which('prtconf') if cmd: data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep for dest, regstring in (('cpuarch', r'(?im)^\s*Processor\s+Type:\s+(\S+)'), ('cpu_flags', r'(?im)^\s*Processor\s+Version:\s+(\S+)'), ('cpu_model', r'(?im)^\s*Processor\s+Implementation\s+Mode:\s+(.*)'), ('num_cpus', r'(?im)^\s*Number\s+Of\s+Processors:\s+(\S+)')): for regex in [re.compile(r) for r in [regstring]]: res = regex.search(data) if res and len(res.groups()) >= 1: grains[dest] = res.group(1).strip().replace("'", '') else: log.error('The \'prtconf\' binary was not found in $PATH.') return grains def _linux_memdata(): ''' Return the memory information for Linux-like systems ''' grains = {'mem_total': 0, 'swap_total': 0} meminfo = '/proc/meminfo' if os.path.isfile(meminfo): with salt.utils.files.fopen(meminfo, 'r') as ifile: for line in ifile: comps = line.rstrip('\n').split(':') if not len(comps) > 1: continue if comps[0].strip() == 'MemTotal': # Use floor division to force output to be an integer grains['mem_total'] = int(comps[1].split()[0]) // 1024 if comps[0].strip() == 'SwapTotal': # Use floor division to force output to be an integer grains['swap_total'] = int(comps[1].split()[0]) // 1024 return grains def _osx_memdata(): ''' Return the memory information for BSD-like systems ''' grains = {'mem_total': 0, 'swap_total': 0} sysctl = salt.utils.path.which('sysctl') if sysctl: mem = __salt__['cmd.run']('{0} -n hw.memsize'.format(sysctl)) swap_total = __salt__['cmd.run']('{0} -n vm.swapusage'.format(sysctl)).split()[2].replace(',', '.') if swap_total.endswith('K'): _power = 2**10 elif swap_total.endswith('M'): _power = 2**20 elif swap_total.endswith('G'): _power = 2**30 swap_total = float(swap_total[:-1]) * _power grains['mem_total'] = int(mem) // 1024 // 1024 grains['swap_total'] = int(swap_total) // 1024 // 1024 return grains def _bsd_memdata(osdata): ''' Return the memory information for BSD-like systems ''' grains = {'mem_total': 0, 'swap_total': 0} sysctl = salt.utils.path.which('sysctl') if sysctl: mem = __salt__['cmd.run']('{0} -n hw.physmem'.format(sysctl)) if osdata['kernel'] == 'NetBSD' and mem.startswith('-'): mem = __salt__['cmd.run']('{0} -n hw.physmem64'.format(sysctl)) grains['mem_total'] = int(mem) // 1024 // 1024 if osdata['kernel'] in ['OpenBSD', 'NetBSD']: swapctl = salt.utils.path.which('swapctl') swap_data = __salt__['cmd.run']('{0} -sk'.format(swapctl)) if swap_data == 'no swap devices configured': swap_total = 0 else: swap_total = swap_data.split(' ')[1] else: swap_total = __salt__['cmd.run']('{0} -n vm.swap_total'.format(sysctl)) grains['swap_total'] = int(swap_total) // 1024 // 1024 return grains def _sunos_memdata(): ''' Return the memory information for SunOS-like systems ''' grains = {'mem_total': 0, 'swap_total': 0} prtconf = '/usr/sbin/prtconf 2>/dev/null' for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines(): comps = line.split(' ') if comps[0].strip() == 'Memory' and comps[1].strip() == 'size:': grains['mem_total'] = int(comps[2].strip()) swap_cmd = salt.utils.path.which('swap') swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split() try: swap_avail = int(swap_data[-2][:-1]) swap_used = int(swap_data[-4][:-1]) swap_total = (swap_avail + swap_used) // 1024 except ValueError: swap_total = None grains['swap_total'] = swap_total return grains def _aix_memdata(): ''' Return the memory information for AIX systems ''' grains = {'mem_total': 0, 'swap_total': 0} prtconf = salt.utils.path.which('prtconf') if prtconf: for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines(): comps = [x for x in line.strip().split(' ') if x] if len(comps) > 2 and 'Memory' in comps[0] and 'Size' in comps[1]: grains['mem_total'] = int(comps[2]) break else: log.error('The \'prtconf\' binary was not found in $PATH.') swap_cmd = salt.utils.path.which('swap') if swap_cmd: swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split() try: swap_total = (int(swap_data[-2]) + int(swap_data[-6])) * 4 except ValueError: swap_total = None grains['swap_total'] = swap_total else: log.error('The \'swap\' binary was not found in $PATH.') return grains def _windows_memdata(): ''' Return the memory information for Windows systems ''' grains = {'mem_total': 0} # get the Total Physical memory as reported by msinfo32 tot_bytes = win32api.GlobalMemoryStatusEx()['TotalPhys'] # return memory info in gigabytes grains['mem_total'] = int(tot_bytes / (1024 ** 2)) return grains def _memdata(osdata): ''' Gather information about the system memory ''' # Provides: # mem_total # swap_total, for supported systems. grains = {'mem_total': 0} if osdata['kernel'] == 'Linux': grains.update(_linux_memdata()) elif osdata['kernel'] in ('FreeBSD', 'OpenBSD', 'NetBSD'): grains.update(_bsd_memdata(osdata)) elif osdata['kernel'] == 'Darwin': grains.update(_osx_memdata()) elif osdata['kernel'] == 'SunOS': grains.update(_sunos_memdata()) elif osdata['kernel'] == 'AIX': grains.update(_aix_memdata()) elif osdata['kernel'] == 'Windows' and HAS_WMI: grains.update(_windows_memdata()) return grains def _aix_get_machine_id(): ''' Parse the output of lsattr -El sys0 for os_uuid ''' grains = {} cmd = salt.utils.path.which('lsattr') if cmd: data = __salt__['cmd.run']('{0} -El sys0'.format(cmd)) + os.linesep uuid_regexes = [re.compile(r'(?im)^\s*os_uuid\s+(\S+)\s+(.*)')] for regex in uuid_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: grains['machine_id'] = res.group(1).strip() break else: log.error('The \'lsattr\' binary was not found in $PATH.') return grains def _windows_virtual(osdata): ''' Returns what type of virtual hardware is under the hood, kvm or physical ''' # Provides: # virtual # virtual_subtype grains = dict() if osdata['kernel'] != 'Windows': return grains grains['virtual'] = 'physical' # It is possible that the 'manufacturer' and/or 'productname' grains # exist but have a value of None. manufacturer = osdata.get('manufacturer', '') if manufacturer is None: manufacturer = '' productname = osdata.get('productname', '') if productname is None: productname = '' if 'QEMU' in manufacturer: # FIXME: Make this detect between kvm or qemu grains['virtual'] = 'kvm' if 'Bochs' in manufacturer: grains['virtual'] = 'kvm' # Product Name: (oVirt) www.ovirt.org # Red Hat Community virtualization Project based on kvm elif 'oVirt' in productname: grains['virtual'] = 'kvm' grains['virtual_subtype'] = 'oVirt' # Red Hat Enterprise Virtualization elif 'RHEV Hypervisor' in productname: grains['virtual'] = 'kvm' grains['virtual_subtype'] = 'rhev' # Product Name: VirtualBox elif 'VirtualBox' in productname: grains['virtual'] = 'VirtualBox' # Product Name: VMware Virtual Platform elif 'VMware Virtual Platform' in productname: grains['virtual'] = 'VMware' # Manufacturer: Microsoft Corporation # Product Name: Virtual Machine elif 'Microsoft' in manufacturer and \ 'Virtual Machine' in productname: grains['virtual'] = 'VirtualPC' # Manufacturer: Parallels Software International Inc. elif 'Parallels Software' in manufacturer: grains['virtual'] = 'Parallels' # Apache CloudStack elif 'CloudStack KVM Hypervisor' in productname: grains['virtual'] = 'kvm' grains['virtual_subtype'] = 'cloudstack' return grains def _virtual(osdata): ''' Returns what type of virtual hardware is under the hood, kvm or physical ''' # This is going to be a monster, if you are running a vm you can test this # grain with please submit patches! # Provides: # virtual # virtual_subtype grains = {'virtual': 'physical'} # Skip the below loop on platforms which have none of the desired cmds # This is a temporary measure until we can write proper virtual hardware # detection. skip_cmds = ('AIX',) # list of commands to be executed to determine the 'virtual' grain _cmds = ['systemd-detect-virt', 'virt-what', 'dmidecode'] # test first for virt-what, which covers most of the desired functionality # on most platforms if not salt.utils.platform.is_windows() and osdata['kernel'] not in skip_cmds: if salt.utils.path.which('virt-what'): _cmds = ['virt-what'] # Check if enable_lspci is True or False if __opts__.get('enable_lspci', True) is True: # /proc/bus/pci does not exists, lspci will fail if os.path.exists('/proc/bus/pci'): _cmds += ['lspci'] # Add additional last resort commands if osdata['kernel'] in skip_cmds: _cmds = () # Quick backout for BrandZ (Solaris LX Branded zones) # Don't waste time trying other commands to detect the virtual grain if HAS_UNAME and osdata['kernel'] == 'Linux' and 'BrandZ virtual linux' in os.uname(): grains['virtual'] = 'zone' return grains failed_commands = set() for command in _cmds: args = [] if osdata['kernel'] == 'Darwin': command = 'system_profiler' args = ['SPDisplaysDataType'] elif osdata['kernel'] == 'SunOS': virtinfo = salt.utils.path.which('virtinfo') if virtinfo: try: ret = __salt__['cmd.run_all']('{0} -a'.format(virtinfo)) except salt.exceptions.CommandExecutionError: if salt.log.is_logging_configured(): failed_commands.add(virtinfo) else: if ret['stdout'].endswith('not supported'): command = 'prtdiag' else: command = 'virtinfo' else: command = 'prtdiag' cmd = salt.utils.path.which(command) if not cmd: continue cmd = '{0} {1}'.format(cmd, ' '.join(args)) try: ret = __salt__['cmd.run_all'](cmd) if ret['retcode'] > 0: if salt.log.is_logging_configured(): # systemd-detect-virt always returns > 0 on non-virtualized # systems # prtdiag only works in the global zone, skip if it fails if salt.utils.platform.is_windows() or 'systemd-detect-virt' in cmd or 'prtdiag' in cmd: continue failed_commands.add(command) continue except salt.exceptions.CommandExecutionError: if salt.log.is_logging_configured(): if salt.utils.platform.is_windows(): continue failed_commands.add(command) continue output = ret['stdout'] if command == "system_profiler": macoutput = output.lower() if '0x1ab8' in macoutput: grains['virtual'] = 'Parallels' if 'parallels' in macoutput: grains['virtual'] = 'Parallels' if 'vmware' in macoutput: grains['virtual'] = 'VMware' if '0x15ad' in macoutput: grains['virtual'] = 'VMware' if 'virtualbox' in macoutput: grains['virtual'] = 'VirtualBox' # Break out of the loop so the next log message is not issued break elif command == 'systemd-detect-virt': if output in ('qemu', 'kvm', 'oracle', 'xen', 'bochs', 'chroot', 'uml', 'systemd-nspawn'): grains['virtual'] = output break elif 'vmware' in output: grains['virtual'] = 'VMware' break elif 'microsoft' in output: grains['virtual'] = 'VirtualPC' break elif 'lxc' in output: grains['virtual'] = 'LXC' break elif 'systemd-nspawn' in output: grains['virtual'] = 'LXC' break elif command == 'virt-what': try: output = output.splitlines()[-1] except IndexError: pass if output in ('kvm', 'qemu', 'uml', 'xen', 'lxc'): grains['virtual'] = output break elif 'vmware' in output: grains['virtual'] = 'VMware' break elif 'parallels' in output: grains['virtual'] = 'Parallels' break elif 'hyperv' in output: grains['virtual'] = 'HyperV' break elif command == 'dmidecode': # Product Name: VirtualBox if 'Vendor: QEMU' in output: # FIXME: Make this detect between kvm or qemu grains['virtual'] = 'kvm' if 'Manufacturer: QEMU' in output: grains['virtual'] = 'kvm' if 'Vendor: Bochs' in output: grains['virtual'] = 'kvm' if 'Manufacturer: Bochs' in output: grains['virtual'] = 'kvm' if 'BHYVE' in output: grains['virtual'] = 'bhyve' # Product Name: (oVirt) www.ovirt.org # Red Hat Community virtualization Project based on kvm elif 'Manufacturer: oVirt' in output: grains['virtual'] = 'kvm' grains['virtual_subtype'] = 'ovirt' # Red Hat Enterprise Virtualization elif 'Product Name: RHEV Hypervisor' in output: grains['virtual'] = 'kvm' grains['virtual_subtype'] = 'rhev' elif 'VirtualBox' in output: grains['virtual'] = 'VirtualBox' # Product Name: VMware Virtual Platform elif 'VMware' in output: grains['virtual'] = 'VMware' # Manufacturer: Microsoft Corporation # Product Name: Virtual Machine elif ': Microsoft' in output and 'Virtual Machine' in output: grains['virtual'] = 'VirtualPC' # Manufacturer: Parallels Software International Inc. elif 'Parallels Software' in output: grains['virtual'] = 'Parallels' elif 'Manufacturer: Google' in output: grains['virtual'] = 'kvm' # Proxmox KVM elif 'Vendor: SeaBIOS' in output: grains['virtual'] = 'kvm' # Break out of the loop, lspci parsing is not necessary break elif command == 'lspci': # dmidecode not available or the user does not have the necessary # permissions model = output.lower() if 'vmware' in model: grains['virtual'] = 'VMware' # 00:04.0 System peripheral: InnoTek Systemberatung GmbH # VirtualBox Guest Service elif 'virtualbox' in model: grains['virtual'] = 'VirtualBox' elif 'qemu' in model: grains['virtual'] = 'kvm' elif 'virtio' in model: grains['virtual'] = 'kvm' # Break out of the loop so the next log message is not issued break elif command == 'prtdiag': model = output.lower().split("\n")[0] if 'vmware' in model: grains['virtual'] = 'VMware' elif 'virtualbox' in model: grains['virtual'] = 'VirtualBox' elif 'qemu' in model: grains['virtual'] = 'kvm' elif 'joyent smartdc hvm' in model: grains['virtual'] = 'kvm' break elif command == 'virtinfo': grains['virtual'] = 'LDOM' break choices = ('Linux', 'HP-UX') isdir = os.path.isdir sysctl = salt.utils.path.which('sysctl') if osdata['kernel'] in choices: if os.path.isdir('/proc'): try: self_root = os.stat('/') init_root = os.stat('/proc/1/root/.') if self_root != init_root: grains['virtual_subtype'] = 'chroot' except (IOError, OSError): pass if isdir('/proc/vz'): if os.path.isfile('/proc/vz/version'): grains['virtual'] = 'openvzhn' elif os.path.isfile('/proc/vz/veinfo'): grains['virtual'] = 'openvzve' # a posteriori, it's expected for these to have failed: failed_commands.discard('lspci') failed_commands.discard('dmidecode') # Provide additional detection for OpenVZ if os.path.isfile('/proc/self/status'): with salt.utils.files.fopen('/proc/self/status') as status_file: vz_re = re.compile(r'^envID:\s+(\d+)$') for line in status_file: vz_match = vz_re.match(line.rstrip('\n')) if vz_match and int(vz_match.groups()[0]) != 0: grains['virtual'] = 'openvzve' elif vz_match and int(vz_match.groups()[0]) == 0: grains['virtual'] = 'openvzhn' if isdir('/proc/sys/xen') or \ isdir('/sys/bus/xen') or isdir('/proc/xen'): if os.path.isfile('/proc/xen/xsd_kva'): # Tested on CentOS 5.3 / 2.6.18-194.26.1.el5xen # Tested on CentOS 5.4 / 2.6.18-164.15.1.el5xen grains['virtual_subtype'] = 'Xen Dom0' else: if osdata.get('productname', '') == 'HVM domU': # Requires dmidecode! grains['virtual_subtype'] = 'Xen HVM DomU' elif os.path.isfile('/proc/xen/capabilities') and \ os.access('/proc/xen/capabilities', os.R_OK): with salt.utils.files.fopen('/proc/xen/capabilities') as fhr: if 'control_d' not in fhr.read(): # Tested on CentOS 5.5 / 2.6.18-194.3.1.el5xen grains['virtual_subtype'] = 'Xen PV DomU' else: # Shouldn't get to this, but just in case grains['virtual_subtype'] = 'Xen Dom0' # Tested on Fedora 10 / 2.6.27.30-170.2.82 with xen # Tested on Fedora 15 / 2.6.41.4-1 without running xen elif isdir('/sys/bus/xen'): if 'xen:' in __salt__['cmd.run']('dmesg').lower(): grains['virtual_subtype'] = 'Xen PV DomU' elif os.path.isfile('/sys/bus/xen/drivers/xenconsole'): # An actual DomU will have the xenconsole driver grains['virtual_subtype'] = 'Xen PV DomU' # If a Dom0 or DomU was detected, obviously this is xen if 'dom' in grains.get('virtual_subtype', '').lower(): grains['virtual'] = 'xen' # Check container type after hypervisors, to avoid variable overwrite on containers running in virtual environment. if os.path.isfile('/proc/1/cgroup'): try: with salt.utils.files.fopen('/proc/1/cgroup', 'r') as fhr: fhr_contents = fhr.read() if ':/lxc/' in fhr_contents: grains['virtual_subtype'] = 'LXC' elif ':/kubepods/' in fhr_contents: grains['virtual_subtype'] = 'kubernetes' elif ':/libpod_parent/' in fhr_contents: grains['virtual_subtype'] = 'libpod' else: if any(x in fhr_contents for x in (':/system.slice/docker', ':/docker/', ':/docker-ce/')): grains['virtual_subtype'] = 'Docker' except IOError: pass if os.path.isfile('/proc/cpuinfo'): with salt.utils.files.fopen('/proc/cpuinfo', 'r') as fhr: if 'QEMU Virtual CPU' in fhr.read(): grains['virtual'] = 'kvm' if os.path.isfile('/sys/devices/virtual/dmi/id/product_name'): try: with salt.utils.files.fopen('/sys/devices/virtual/dmi/id/product_name', 'r') as fhr: output = salt.utils.stringutils.to_unicode(fhr.read(), errors='replace') if 'VirtualBox' in output: grains['virtual'] = 'VirtualBox' elif 'RHEV Hypervisor' in output: grains['virtual'] = 'kvm' grains['virtual_subtype'] = 'rhev' elif 'oVirt Node' in output: grains['virtual'] = 'kvm' grains['virtual_subtype'] = 'ovirt' elif 'Google' in output: grains['virtual'] = 'gce' elif 'BHYVE' in output: grains['virtual'] = 'bhyve' except IOError: pass elif osdata['kernel'] == 'FreeBSD': kenv = salt.utils.path.which('kenv') if kenv: product = __salt__['cmd.run']( '{0} smbios.system.product'.format(kenv) ) maker = __salt__['cmd.run']( '{0} smbios.system.maker'.format(kenv) ) if product.startswith('VMware'): grains['virtual'] = 'VMware' if product.startswith('VirtualBox'): grains['virtual'] = 'VirtualBox' if maker.startswith('Xen'): grains['virtual_subtype'] = '{0} {1}'.format(maker, product) grains['virtual'] = 'xen' if maker.startswith('Microsoft') and product.startswith('Virtual'): grains['virtual'] = 'VirtualPC' if maker.startswith('OpenStack'): grains['virtual'] = 'OpenStack' if maker.startswith('Bochs'): grains['virtual'] = 'kvm' if sysctl: hv_vendor = __salt__['cmd.run']('{0} hw.hv_vendor'.format(sysctl)) model = __salt__['cmd.run']('{0} hw.model'.format(sysctl)) jail = __salt__['cmd.run']( '{0} -n security.jail.jailed'.format(sysctl) ) if 'bhyve' in hv_vendor: grains['virtual'] = 'bhyve' if jail == '1': grains['virtual_subtype'] = 'jail' if 'QEMU Virtual CPU' in model: grains['virtual'] = 'kvm' elif osdata['kernel'] == 'OpenBSD': if 'manufacturer' in osdata: if osdata['manufacturer'] in ['QEMU', 'Red Hat', 'Joyent']: grains['virtual'] = 'kvm' if osdata['manufacturer'] == 'OpenBSD': grains['virtual'] = 'vmm' elif osdata['kernel'] == 'SunOS': if grains['virtual'] == 'LDOM': roles = [] for role in ('control', 'io', 'root', 'service'): subtype_cmd = '{0} -c current get -H -o value {1}-role'.format(cmd, role) ret = __salt__['cmd.run_all']('{0}'.format(subtype_cmd)) if ret['stdout'] == 'true': roles.append(role) if roles: grains['virtual_subtype'] = roles else: # Check if it's a "regular" zone. (i.e. Solaris 10/11 zone) zonename = salt.utils.path.which('zonename') if zonename: zone = __salt__['cmd.run']('{0}'.format(zonename)) if zone != 'global': grains['virtual'] = 'zone' # Check if it's a branded zone (i.e. Solaris 8/9 zone) if isdir('/.SUNWnative'): grains['virtual'] = 'zone' elif osdata['kernel'] == 'NetBSD': if sysctl: if 'QEMU Virtual CPU' in __salt__['cmd.run']( '{0} -n machdep.cpu_brand'.format(sysctl)): grains['virtual'] = 'kvm' elif 'invalid' not in __salt__['cmd.run']( '{0} -n machdep.xen.suspend'.format(sysctl)): grains['virtual'] = 'Xen PV DomU' elif 'VMware' in __salt__['cmd.run']( '{0} -n machdep.dmi.system-vendor'.format(sysctl)): grains['virtual'] = 'VMware' # NetBSD has Xen dom0 support elif __salt__['cmd.run']( '{0} -n machdep.idle-mechanism'.format(sysctl)) == 'xen': if os.path.isfile('/var/run/xenconsoled.pid'): grains['virtual_subtype'] = 'Xen Dom0' for command in failed_commands: log.info( "Although '%s' was found in path, the current user " 'cannot execute it. Grains output might not be ' 'accurate.', command ) return grains def _virtual_hv(osdata): ''' Returns detailed hypervisor information from sysfs Currently this seems to be used only by Xen ''' grains = {} # Bail early if we're not running on Xen try: if 'xen' not in osdata['virtual']: return grains except KeyError: return grains # Try to get the exact hypervisor version from sysfs try: version = {} for fn in ('major', 'minor', 'extra'): with salt.utils.files.fopen('/sys/hypervisor/version/{}'.format(fn), 'r') as fhr: version[fn] = salt.utils.stringutils.to_unicode(fhr.read().strip()) grains['virtual_hv_version'] = '{}.{}{}'.format(version['major'], version['minor'], version['extra']) grains['virtual_hv_version_info'] = [version['major'], version['minor'], version['extra']] except (IOError, OSError, KeyError): pass # Try to read and decode the supported feature set of the hypervisor # Based on https://github.com/brendangregg/Misc/blob/master/xen/xen-features.py # Table data from include/xen/interface/features.h xen_feature_table = {0: 'writable_page_tables', 1: 'writable_descriptor_tables', 2: 'auto_translated_physmap', 3: 'supervisor_mode_kernel', 4: 'pae_pgdir_above_4gb', 5: 'mmu_pt_update_preserve_ad', 7: 'gnttab_map_avail_bits', 8: 'hvm_callback_vector', 9: 'hvm_safe_pvclock', 10: 'hvm_pirqs', 11: 'dom0', 12: 'grant_map_identity', 13: 'memory_op_vnode_supported', 14: 'ARM_SMCCC_supported'} try: with salt.utils.files.fopen('/sys/hypervisor/properties/features', 'r') as fhr: features = salt.utils.stringutils.to_unicode(fhr.read().strip()) enabled_features = [] for bit, feat in six.iteritems(xen_feature_table): if int(features, 16) & (1 << bit): enabled_features.append(feat) grains['virtual_hv_features'] = features grains['virtual_hv_features_list'] = enabled_features except (IOError, OSError, KeyError): pass return grains def _ps(osdata): ''' Return the ps grain ''' grains = {} bsd_choices = ('FreeBSD', 'NetBSD', 'OpenBSD', 'MacOS') if osdata['os'] in bsd_choices: grains['ps'] = 'ps auxwww' elif osdata['os_family'] == 'Solaris': grains['ps'] = '/usr/ucb/ps auxwww' elif osdata['os'] == 'Windows': grains['ps'] = 'tasklist.exe' elif osdata.get('virtual', '') == 'openvzhn': grains['ps'] = ( 'ps -fH -p $(grep -l \"^envID:[[:space:]]*0\\$\" ' '/proc/[0-9]*/status | sed -e \"s=/proc/\\([0-9]*\\)/.*=\\1=\") ' '| awk \'{ $7=\"\"; print }\'' ) elif osdata['os_family'] == 'AIX': grains['ps'] = '/usr/bin/ps auxww' elif osdata['os_family'] == 'NILinuxRT': grains['ps'] = 'ps -o user,pid,ppid,tty,time,comm' else: grains['ps'] = 'ps -efHww' return grains def _clean_value(key, val): ''' Clean out well-known bogus values. If it isn't clean (for example has value 'None'), return None. Otherwise, return the original value. NOTE: This logic also exists in the smbios module. This function is for use when not using smbios to retrieve the value. ''' if (val is None or not val or re.match('none', val, flags=re.IGNORECASE)): return None elif 'uuid' in key: # Try each version (1-5) of RFC4122 to check if it's actually a UUID for uuidver in range(1, 5): try: uuid.UUID(val, version=uuidver) return val except ValueError: continue log.trace('HW %s value %s is an invalid UUID', key, val.replace('\n', ' ')) return None elif re.search('serial|part|version', key): # 'To be filled by O.E.M. # 'Not applicable' etc. # 'Not specified' etc. # 0000000, 1234567 etc. # begone! if (re.match(r'^[0]+$', val) or re.match(r'[0]?1234567[8]?[9]?[0]?', val) or re.search(r'sernum|part[_-]?number|specified|filled|applicable', val, flags=re.IGNORECASE)): return None elif re.search('asset|manufacturer', key): # AssetTag0. Manufacturer04. Begone. if re.search(r'manufacturer|to be filled|available|asset|^no(ne|t)', val, flags=re.IGNORECASE): return None else: # map unspecified, undefined, unknown & whatever to None if (re.search(r'to be filled', val, flags=re.IGNORECASE) or re.search(r'un(known|specified)|no(t|ne)? (asset|provided|defined|available|present|specified)', val, flags=re.IGNORECASE)): return None return val def _windows_platform_data(): ''' Use the platform module for as much as we can. ''' # Provides: # kernelrelease # kernelversion # osversion # osrelease # osservicepack # osmanufacturer # manufacturer # productname # biosversion # serialnumber # osfullname # timezone # windowsdomain # windowsdomaintype # motherboard.productname # motherboard.serialnumber # virtual if not HAS_WMI: return {} with salt.utils.winapi.Com(): wmi_c = wmi.WMI() # http://msdn.microsoft.com/en-us/library/windows/desktop/aa394102%28v=vs.85%29.aspx systeminfo = wmi_c.Win32_ComputerSystem()[0] # https://msdn.microsoft.com/en-us/library/aa394239(v=vs.85).aspx osinfo = wmi_c.Win32_OperatingSystem()[0] # http://msdn.microsoft.com/en-us/library/windows/desktop/aa394077(v=vs.85).aspx biosinfo = wmi_c.Win32_BIOS()[0] # http://msdn.microsoft.com/en-us/library/windows/desktop/aa394498(v=vs.85).aspx timeinfo = wmi_c.Win32_TimeZone()[0] # http://msdn.microsoft.com/en-us/library/windows/desktop/aa394072(v=vs.85).aspx motherboard = {'product': None, 'serial': None} try: motherboardinfo = wmi_c.Win32_BaseBoard()[0] motherboard['product'] = motherboardinfo.Product motherboard['serial'] = motherboardinfo.SerialNumber except IndexError: log.debug('Motherboard info not available on this system') os_release = platform.release() kernel_version = platform.version() info = salt.utils.win_osinfo.get_os_version_info() net_info = salt.utils.win_osinfo.get_join_info() service_pack = None if info['ServicePackMajor'] > 0: service_pack = ''.join(['SP', six.text_type(info['ServicePackMajor'])]) # This creates the osrelease grain based on the Windows Operating # System Product Name. As long as Microsoft maintains a similar format # this should be future proof version = 'Unknown' release = '' if 'Server' in osinfo.Caption: for item in osinfo.Caption.split(' '): # If it's all digits, then it's version if re.match(r'\d+', item): version = item # If it starts with R and then numbers, it's the release # ie: R2 if re.match(r'^R\d+$', item): release = item os_release = '{0}Server{1}'.format(version, release) else: for item in osinfo.Caption.split(' '): # If it's a number, decimal number, Thin or Vista, then it's the # version if re.match(r'^(\d+(\.\d+)?)|Thin|Vista$', item): version = item os_release = version grains = { 'kernelrelease': _clean_value('kernelrelease', osinfo.Version), 'kernelversion': _clean_value('kernelversion', kernel_version), 'osversion': _clean_value('osversion', osinfo.Version), 'osrelease': _clean_value('osrelease', os_release), 'osservicepack': _clean_value('osservicepack', service_pack), 'osmanufacturer': _clean_value('osmanufacturer', osinfo.Manufacturer), 'manufacturer': _clean_value('manufacturer', systeminfo.Manufacturer), 'productname': _clean_value('productname', systeminfo.Model), # bios name had a bunch of whitespace appended to it in my testing # 'PhoenixBIOS 4.0 Release 6.0 ' 'biosversion': _clean_value('biosversion', biosinfo.Name.strip()), 'serialnumber': _clean_value('serialnumber', biosinfo.SerialNumber), 'osfullname': _clean_value('osfullname', osinfo.Caption), 'timezone': _clean_value('timezone', timeinfo.Description), 'windowsdomain': _clean_value('windowsdomain', net_info['Domain']), 'windowsdomaintype': _clean_value('windowsdomaintype', net_info['DomainType']), 'motherboard': { 'productname': _clean_value('motherboard.productname', motherboard['product']), 'serialnumber': _clean_value('motherboard.serialnumber', motherboard['serial']), } } # test for virtualized environments # I only had VMware available so the rest are unvalidated if 'VRTUAL' in biosinfo.Version: # (not a typo) grains['virtual'] = 'HyperV' elif 'A M I' in biosinfo.Version: grains['virtual'] = 'VirtualPC' elif 'VMware' in systeminfo.Model: grains['virtual'] = 'VMware' elif 'VirtualBox' in systeminfo.Model: grains['virtual'] = 'VirtualBox' elif 'Xen' in biosinfo.Version: grains['virtual'] = 'Xen' if 'HVM domU' in systeminfo.Model: grains['virtual_subtype'] = 'HVM domU' elif 'OpenStack' in systeminfo.Model: grains['virtual'] = 'OpenStack' return grains def _osx_platform_data(): ''' Additional data for macOS systems Returns: A dictionary containing values for the following: - model_name - boot_rom_version - smc_version - system_serialnumber ''' cmd = 'system_profiler SPHardwareDataType' hardware = __salt__['cmd.run'](cmd) grains = {} for line in hardware.splitlines(): field_name, _, field_val = line.partition(': ') if field_name.strip() == "Model Name": key = 'model_name' grains[key] = _clean_value(key, field_val) if field_name.strip() == "Boot ROM Version": key = 'boot_rom_version' grains[key] = _clean_value(key, field_val) if field_name.strip() == "SMC Version (system)": key = 'smc_version' grains[key] = _clean_value(key, field_val) if field_name.strip() == "Serial Number (system)": key = 'system_serialnumber' grains[key] = _clean_value(key, field_val) return grains def id_(): ''' Return the id ''' return {'id': __opts__.get('id', '')} _REPLACE_LINUX_RE = re.compile(r'\W(?:gnu/)?linux', re.IGNORECASE) # This maps (at most) the first ten characters (no spaces, lowercased) of # 'osfullname' to the 'os' grain that Salt traditionally uses. # Please see os_data() and _supported_dists. # If your system is not detecting properly it likely needs an entry here. _OS_NAME_MAP = { 'redhatente': 'RedHat', 'gentoobase': 'Gentoo', 'archarm': 'Arch ARM', 'arch': 'Arch', 'debian': 'Debian', 'raspbian': 'Raspbian', 'fedoraremi': 'Fedora', 'chapeau': 'Chapeau', 'korora': 'Korora', 'amazonami': 'Amazon', 'alt': 'ALT', 'enterprise': 'OEL', 'oracleserv': 'OEL', 'cloudserve': 'CloudLinux', 'cloudlinux': 'CloudLinux', 'pidora': 'Fedora', 'scientific': 'ScientificLinux', 'synology': 'Synology', 'nilrt': 'NILinuxRT', 'poky': 'Poky', 'manjaro': 'Manjaro', 'manjarolin': 'Manjaro', 'univention': 'Univention', 'antergos': 'Antergos', 'sles': 'SUSE', 'void': 'Void', 'slesexpand': 'RES', 'linuxmint': 'Mint', 'neon': 'KDE neon', } # Map the 'os' grain to the 'os_family' grain # These should always be capitalized entries as the lookup comes # post-_OS_NAME_MAP. If your system is having trouble with detection, please # make sure that the 'os' grain is capitalized and working correctly first. _OS_FAMILY_MAP = { 'Ubuntu': 'Debian', 'Fedora': 'RedHat', 'Chapeau': 'RedHat', 'Korora': 'RedHat', 'FedBerry': 'RedHat', 'CentOS': 'RedHat', 'GoOSe': 'RedHat', 'Scientific': 'RedHat', 'Amazon': 'RedHat', 'CloudLinux': 'RedHat', 'OVS': 'RedHat', 'OEL': 'RedHat', 'XCP': 'RedHat', 'XCP-ng': 'RedHat', 'XenServer': 'RedHat', 'RES': 'RedHat', 'Sangoma': 'RedHat', 'Mandrake': 'Mandriva', 'ESXi': 'VMware', 'Mint': 'Debian', 'VMwareESX': 'VMware', 'Bluewhite64': 'Bluewhite', 'Slamd64': 'Slackware', 'SLES': 'Suse', 'SUSE Enterprise Server': 'Suse', 'SUSE Enterprise Server': 'Suse', 'SLED': 'Suse', 'openSUSE': 'Suse', 'SUSE': 'Suse', 'openSUSE Leap': 'Suse', 'openSUSE Tumbleweed': 'Suse', 'SLES_SAP': 'Suse', 'Solaris': 'Solaris', 'SmartOS': 'Solaris', 'OmniOS': 'Solaris', 'OpenIndiana Development': 'Solaris', 'OpenIndiana': 'Solaris', 'OpenSolaris Development': 'Solaris', 'OpenSolaris': 'Solaris', 'Oracle Solaris': 'Solaris', 'Arch ARM': 'Arch', 'Manjaro': 'Arch', 'Antergos': 'Arch', 'ALT': 'RedHat', 'Trisquel': 'Debian', 'GCEL': 'Debian', 'Linaro': 'Debian', 'elementary OS': 'Debian', 'elementary': 'Debian', 'Univention': 'Debian', 'ScientificLinux': 'RedHat', 'Raspbian': 'Debian', 'Devuan': 'Debian', 'antiX': 'Debian', 'Kali': 'Debian', 'neon': 'Debian', 'Cumulus': 'Debian', 'Deepin': 'Debian', 'NILinuxRT': 'NILinuxRT', 'KDE neon': 'Debian', 'Void': 'Void', 'IDMS': 'Debian', 'Funtoo': 'Gentoo', 'AIX': 'AIX', 'TurnKey': 'Debian', } # Matches any possible format: # DISTRIB_ID="Ubuntu" # DISTRIB_ID='Mageia' # DISTRIB_ID=Fedora # DISTRIB_RELEASE='10.10' # DISTRIB_CODENAME='squeeze' # DISTRIB_DESCRIPTION='Ubuntu 10.10' _LSB_REGEX = re.compile(( '^(DISTRIB_(?:ID|RELEASE|CODENAME|DESCRIPTION))=(?:\'|")?' '([\\w\\s\\.\\-_]+)(?:\'|")?' )) def _linux_bin_exists(binary): ''' Does a binary exist in linux (depends on which, type, or whereis) ''' for search_cmd in ('which', 'type -ap'): try: return __salt__['cmd.retcode']( '{0} {1}'.format(search_cmd, binary) ) == 0 except salt.exceptions.CommandExecutionError: pass try: return len(__salt__['cmd.run_all']( 'whereis -b {0}'.format(binary) )['stdout'].split()) > 1 except salt.exceptions.CommandExecutionError: return False def _get_interfaces(): ''' Provide a dict of the connected interfaces and their ip addresses ''' global _INTERFACES if not _INTERFACES: _INTERFACES = salt.utils.network.interfaces() return _INTERFACES def _parse_lsb_release(): ret = {} try: log.trace('Attempting to parse /etc/lsb-release') with salt.utils.files.fopen('/etc/lsb-release') as ifile: for line in ifile: try: key, value = _LSB_REGEX.match(line.rstrip('\n')).groups()[:2] except AttributeError: pass else: # Adds lsb_distrib_{id,release,codename,description} ret['lsb_{0}'.format(key.lower())] = value.rstrip() except (IOError, OSError) as exc: log.trace('Failed to parse /etc/lsb-release: %s', exc) return ret def _parse_os_release(*os_release_files): ''' Parse os-release and return a parameter dictionary See http://www.freedesktop.org/software/systemd/man/os-release.html for specification of the file format. ''' ret = {} for filename in os_release_files: try: with salt.utils.files.fopen(filename) as ifile: regex = re.compile('^([\\w]+)=(?:\'|")?(.*?)(?:\'|")?$') for line in ifile: match = regex.match(line.strip()) if match: # Shell special characters ("$", quotes, backslash, # backtick) are escaped with backslashes ret[match.group(1)] = re.sub( r'\\([$"\'\\`])', r'\1', match.group(2) ) break except (IOError, OSError): pass return ret def _parse_cpe_name(cpe): ''' Parse CPE_NAME data from the os-release Info: https://csrc.nist.gov/projects/security-content-automation-protocol/scap-specifications/cpe :param cpe: :return: ''' part = { 'o': 'operating system', 'h': 'hardware', 'a': 'application', } ret = {} cpe = (cpe or '').split(':') if len(cpe) > 4 and cpe[0] == 'cpe': if cpe[1].startswith('/'): # WFN to URI ret['vendor'], ret['product'], ret['version'] = cpe[2:5] ret['phase'] = cpe[5] if len(cpe) > 5 else None ret['part'] = part.get(cpe[1][1:]) elif len(cpe) == 13 and cpe[1] == '2.3': # WFN to a string ret['vendor'], ret['product'], ret['version'], ret['phase'] = [x if x != '*' else None for x in cpe[3:7]] ret['part'] = part.get(cpe[2]) return ret def os_data(): ''' Return grains pertaining to the operating system ''' grains = { 'num_gpus': 0, 'gpus': [], } # Windows Server 2008 64-bit # ('Windows', 'MINIONNAME', '2008ServerR2', '6.1.7601', 'AMD64', # 'Intel64 Fam ily 6 Model 23 Stepping 6, GenuineIntel') # Ubuntu 10.04 # ('Linux', 'MINIONNAME', '2.6.32-38-server', # '#83-Ubuntu SMP Wed Jan 4 11:26:59 UTC 2012', 'x86_64', '') # pylint: disable=unpacking-non-sequence (grains['kernel'], grains['nodename'], grains['kernelrelease'], grains['kernelversion'], grains['cpuarch'], _) = platform.uname() # pylint: enable=unpacking-non-sequence if salt.utils.platform.is_proxy(): grains['kernel'] = 'proxy' grains['kernelrelease'] = 'proxy' grains['kernelversion'] = 'proxy' grains['osrelease'] = 'proxy' grains['os'] = 'proxy' grains['os_family'] = 'proxy' grains['osfullname'] = 'proxy' elif salt.utils.platform.is_windows(): grains['os'] = 'Windows' grains['os_family'] = 'Windows' grains.update(_memdata(grains)) grains.update(_windows_platform_data()) grains.update(_windows_cpudata()) grains.update(_windows_virtual(grains)) grains.update(_ps(grains)) if 'Server' in grains['osrelease']: osrelease_info = grains['osrelease'].split('Server', 1) osrelease_info[1] = osrelease_info[1].lstrip('R') else: osrelease_info = grains['osrelease'].split('.') for idx, value in enumerate(osrelease_info): if not value.isdigit(): continue osrelease_info[idx] = int(value) grains['osrelease_info'] = tuple(osrelease_info) grains['osfinger'] = '{os}-{ver}'.format( os=grains['os'], ver=grains['osrelease']) grains['init'] = 'Windows' return grains elif salt.utils.platform.is_linux(): # Add SELinux grain, if you have it if _linux_bin_exists('selinuxenabled'): log.trace('Adding selinux grains') grains['selinux'] = {} grains['selinux']['enabled'] = __salt__['cmd.retcode']( 'selinuxenabled' ) == 0 if _linux_bin_exists('getenforce'): grains['selinux']['enforced'] = __salt__['cmd.run']( 'getenforce' ).strip() # Add systemd grain, if you have it if _linux_bin_exists('systemctl') and _linux_bin_exists('localectl'): log.trace('Adding systemd grains') grains['systemd'] = {} systemd_info = __salt__['cmd.run']( 'systemctl --version' ).splitlines() grains['systemd']['version'] = systemd_info[0].split()[1] grains['systemd']['features'] = systemd_info[1] # Add init grain grains['init'] = 'unknown' log.trace('Adding init grain') try: os.stat('/run/systemd/system') grains['init'] = 'systemd' except (OSError, IOError): try: with salt.utils.files.fopen('/proc/1/cmdline') as fhr: init_cmdline = fhr.read().replace('\x00', ' ').split() except (IOError, OSError): pass else: try: init_bin = salt.utils.path.which(init_cmdline[0]) except IndexError: # Emtpy init_cmdline init_bin = None log.warning('Unable to fetch data from /proc/1/cmdline') if init_bin is not None and init_bin.endswith('bin/init'): supported_inits = (b'upstart', b'sysvinit', b'systemd') edge_len = max(len(x) for x in supported_inits) - 1 try: buf_size = __opts__['file_buffer_size'] except KeyError: # Default to the value of file_buffer_size for the minion buf_size = 262144 try: with salt.utils.files.fopen(init_bin, 'rb') as fp_: edge = b'' buf = fp_.read(buf_size).lower() while buf: buf = edge + buf for item in supported_inits: if item in buf: if six.PY3: item = item.decode('utf-8') grains['init'] = item buf = b'' break edge = buf[-edge_len:] buf = fp_.read(buf_size).lower() except (IOError, OSError) as exc: log.error( 'Unable to read from init_bin (%s): %s', init_bin, exc ) elif salt.utils.path.which('supervisord') in init_cmdline: grains['init'] = 'supervisord' elif salt.utils.path.which('dumb-init') in init_cmdline: # https://github.com/Yelp/dumb-init grains['init'] = 'dumb-init' elif salt.utils.path.which('tini') in init_cmdline: # https://github.com/krallin/tini grains['init'] = 'tini' elif init_cmdline == ['runit']: grains['init'] = 'runit' elif '/sbin/my_init' in init_cmdline: # Phusion Base docker container use runit for srv mgmt, but # my_init as pid1 grains['init'] = 'runit' else: log.debug( 'Could not determine init system from command line: (%s)', ' '.join(init_cmdline) ) # Add lsb grains on any distro with lsb-release. Note that this import # can fail on systems with lsb-release installed if the system package # does not install the python package for the python interpreter used by # Salt (i.e. python2 or python3) try: log.trace('Getting lsb_release distro information') import lsb_release # pylint: disable=import-error release = lsb_release.get_distro_information() for key, value in six.iteritems(release): key = key.lower() lsb_param = 'lsb_{0}{1}'.format( '' if key.startswith('distrib_') else 'distrib_', key ) grains[lsb_param] = value # Catch a NameError to workaround possible breakage in lsb_release # See https://github.com/saltstack/salt/issues/37867 except (ImportError, NameError): # if the python library isn't available, try to parse # /etc/lsb-release using regex log.trace('lsb_release python bindings not available') grains.update(_parse_lsb_release()) if grains.get('lsb_distrib_description', '').lower().startswith('antergos'): # Antergos incorrectly configures their /etc/lsb-release, # setting the DISTRIB_ID to "Arch". This causes the "os" grain # to be incorrectly set to "Arch". grains['osfullname'] = 'Antergos Linux' elif 'lsb_distrib_id' not in grains: log.trace( 'Failed to get lsb_distrib_id, trying to parse os-release' ) os_release = _parse_os_release('/etc/os-release', '/usr/lib/os-release') if os_release: if 'NAME' in os_release: grains['lsb_distrib_id'] = os_release['NAME'].strip() if 'VERSION_ID' in os_release: grains['lsb_distrib_release'] = os_release['VERSION_ID'] if 'VERSION_CODENAME' in os_release: grains['lsb_distrib_codename'] = os_release['VERSION_CODENAME'] elif 'PRETTY_NAME' in os_release: codename = os_release['PRETTY_NAME'] # https://github.com/saltstack/salt/issues/44108 if os_release['ID'] == 'debian': codename_match = re.search(r'\((\w+)\)$', codename) if codename_match: codename = codename_match.group(1) grains['lsb_distrib_codename'] = codename if 'CPE_NAME' in os_release: cpe = _parse_cpe_name(os_release['CPE_NAME']) if not cpe: log.error('Broken CPE_NAME format in /etc/os-release!') elif cpe.get('vendor', '').lower() in ['suse', 'opensuse']: grains['os'] = "SUSE" # openSUSE `osfullname` grain normalization if os_release.get("NAME") == "openSUSE Leap": grains['osfullname'] = "Leap" elif os_release.get("VERSION") == "Tumbleweed": grains['osfullname'] = os_release["VERSION"] # Override VERSION_ID, if CPE_NAME around if cpe.get('version') and cpe.get('vendor') == 'opensuse': # Keep VERSION_ID for SLES grains['lsb_distrib_release'] = cpe['version'] elif os.path.isfile('/etc/SuSE-release'): log.trace('Parsing distrib info from /etc/SuSE-release') grains['lsb_distrib_id'] = 'SUSE' version = '' patch = '' with salt.utils.files.fopen('/etc/SuSE-release') as fhr: for line in fhr: if 'enterprise' in line.lower(): grains['lsb_distrib_id'] = 'SLES' grains['lsb_distrib_codename'] = re.sub(r'\(.+\)', '', line).strip() elif 'version' in line.lower(): version = re.sub(r'[^0-9]', '', line) elif 'patchlevel' in line.lower(): patch = re.sub(r'[^0-9]', '', line) grains['lsb_distrib_release'] = version if patch: grains['lsb_distrib_release'] += '.' + patch patchstr = 'SP' + patch if grains['lsb_distrib_codename'] and patchstr not in grains['lsb_distrib_codename']: grains['lsb_distrib_codename'] += ' ' + patchstr if not grains.get('lsb_distrib_codename'): grains['lsb_distrib_codename'] = 'n.a' elif os.path.isfile('/etc/altlinux-release'): log.trace('Parsing distrib info from /etc/altlinux-release') # ALT Linux grains['lsb_distrib_id'] = 'altlinux' with salt.utils.files.fopen('/etc/altlinux-release') as ifile: # This file is symlinked to from: # /etc/fedora-release # /etc/redhat-release # /etc/system-release for line in ifile: # ALT Linux Sisyphus (unstable) comps = line.split() if comps[0] == 'ALT': grains['lsb_distrib_release'] = comps[2] grains['lsb_distrib_codename'] = \ comps[3].replace('(', '').replace(')', '') elif os.path.isfile('/etc/centos-release'): log.trace('Parsing distrib info from /etc/centos-release') # Maybe CentOS Linux; could also be SUSE Expanded Support. # SUSE ES has both, centos-release and redhat-release. if os.path.isfile('/etc/redhat-release'): with salt.utils.files.fopen('/etc/redhat-release') as ifile: for line in ifile: if "red hat enterprise linux server" in line.lower(): # This is a SUSE Expanded Support Rhel installation grains['lsb_distrib_id'] = 'RedHat' break grains.setdefault('lsb_distrib_id', 'CentOS') with salt.utils.files.fopen('/etc/centos-release') as ifile: for line in ifile: # Need to pull out the version and codename # in the case of custom content in /etc/centos-release find_release = re.compile(r'\d+\.\d+') find_codename = re.compile(r'(?<=\()(.*?)(?=\))') release = find_release.search(line) codename = find_codename.search(line) if release is not None: grains['lsb_distrib_release'] = release.group() if codename is not None: grains['lsb_distrib_codename'] = codename.group() elif os.path.isfile('/etc.defaults/VERSION') \ and os.path.isfile('/etc.defaults/synoinfo.conf'): grains['osfullname'] = 'Synology' log.trace( 'Parsing Synology distrib info from /etc/.defaults/VERSION' ) with salt.utils.files.fopen('/etc.defaults/VERSION', 'r') as fp_: synoinfo = {} for line in fp_: try: key, val = line.rstrip('\n').split('=') except ValueError: continue if key in ('majorversion', 'minorversion', 'buildnumber'): synoinfo[key] = val.strip('"') if len(synoinfo) != 3: log.warning( 'Unable to determine Synology version info. ' 'Please report this, as it is likely a bug.' ) else: grains['osrelease'] = ( '{majorversion}.{minorversion}-{buildnumber}' .format(**synoinfo) ) # Use the already intelligent platform module to get distro info # (though apparently it's not intelligent enough to strip quotes) log.trace( 'Getting OS name, release, and codename from ' 'distro.linux_distribution()' ) (osname, osrelease, oscodename) = \ [x.strip('"').strip("'") for x in linux_distribution(supported_dists=_supported_dists)] # Try to assign these three names based on the lsb info, they tend to # be more accurate than what python gets from /etc/DISTRO-release. # It's worth noting that Ubuntu has patched their Python distribution # so that linux_distribution() does the /etc/lsb-release parsing, but # we do it anyway here for the sake for full portability. if 'osfullname' not in grains: # If NI Linux RT distribution, set the grains['osfullname'] to 'nilrt' if grains.get('lsb_distrib_id', '').lower().startswith('nilrt'): grains['osfullname'] = 'nilrt' else: grains['osfullname'] = grains.get('lsb_distrib_id', osname).strip() if 'osrelease' not in grains: # NOTE: This is a workaround for CentOS 7 os-release bug # https://bugs.centos.org/view.php?id=8359 # /etc/os-release contains no minor distro release number so we fall back to parse # /etc/centos-release file instead. # Commit introducing this comment should be reverted after the upstream bug is released. if 'CentOS Linux 7' in grains.get('lsb_distrib_codename', ''): grains.pop('lsb_distrib_release', None) grains['osrelease'] = grains.get('lsb_distrib_release', osrelease).strip() grains['oscodename'] = grains.get('lsb_distrib_codename', '').strip() or oscodename if 'Red Hat' in grains['oscodename']: grains['oscodename'] = oscodename distroname = _REPLACE_LINUX_RE.sub('', grains['osfullname']).strip() # return the first ten characters with no spaces, lowercased shortname = distroname.replace(' ', '').lower()[:10] # this maps the long names from the /etc/DISTRO-release files to the # traditional short names that Salt has used. if 'os' not in grains: grains['os'] = _OS_NAME_MAP.get(shortname, distroname) grains.update(_linux_cpudata()) grains.update(_linux_gpu_data()) elif grains['kernel'] == 'SunOS': if salt.utils.platform.is_smartos(): # See https://github.com/joyent/smartos-live/issues/224 if HAS_UNAME: uname_v = os.uname()[3] # format: joyent_20161101T004406Z else: uname_v = os.name uname_v = uname_v[uname_v.index('_')+1:] grains['os'] = grains['osfullname'] = 'SmartOS' # store a parsed version of YYYY.MM.DD as osrelease grains['osrelease'] = ".".join([ uname_v.split('T')[0][0:4], uname_v.split('T')[0][4:6], uname_v.split('T')[0][6:8], ]) # store a untouched copy of the timestamp in osrelease_stamp grains['osrelease_stamp'] = uname_v elif os.path.isfile('/etc/release'): with salt.utils.files.fopen('/etc/release', 'r') as fp_: rel_data = fp_.read() try: release_re = re.compile( r'((?:Open|Oracle )?Solaris|OpenIndiana|OmniOS) (Development)?' r'\s*(\d+\.?\d*|v\d+)\s?[A-Z]*\s?(r\d+|\d+\/\d+|oi_\S+|snv_\S+)?' ) osname, development, osmajorrelease, osminorrelease = release_re.search(rel_data).groups() except AttributeError: # Set a blank osrelease grain and fallback to 'Solaris' # as the 'os' grain. grains['os'] = grains['osfullname'] = 'Solaris' grains['osrelease'] = '' else: if development is not None: osname = ' '.join((osname, development)) if HAS_UNAME: uname_v = os.uname()[3] else: uname_v = os.name grains['os'] = grains['osfullname'] = osname if osname in ['Oracle Solaris'] and uname_v.startswith(osmajorrelease): # Oracla Solars 11 and up have minor version in uname grains['osrelease'] = uname_v elif osname in ['OmniOS']: # OmniOS osrelease = [] osrelease.append(osmajorrelease[1:]) osrelease.append(osminorrelease[1:]) grains['osrelease'] = ".".join(osrelease) grains['osrelease_stamp'] = uname_v else: # Sun Solaris 10 and earlier/comparable osrelease = [] osrelease.append(osmajorrelease) if osminorrelease: osrelease.append(osminorrelease) grains['osrelease'] = ".".join(osrelease) grains['osrelease_stamp'] = uname_v grains.update(_sunos_cpudata()) elif grains['kernel'] == 'VMkernel': grains['os'] = 'ESXi' elif grains['kernel'] == 'Darwin': osrelease = __salt__['cmd.run']('sw_vers -productVersion') osname = __salt__['cmd.run']('sw_vers -productName') osbuild = __salt__['cmd.run']('sw_vers -buildVersion') grains['os'] = 'MacOS' grains['os_family'] = 'MacOS' grains['osfullname'] = "{0} {1}".format(osname, osrelease) grains['osrelease'] = osrelease grains['osbuild'] = osbuild grains['init'] = 'launchd' grains.update(_bsd_cpudata(grains)) grains.update(_osx_gpudata()) grains.update(_osx_platform_data()) elif grains['kernel'] == 'AIX': osrelease = __salt__['cmd.run']('oslevel') osrelease_techlevel = __salt__['cmd.run']('oslevel -r') osname = __salt__['cmd.run']('uname') grains['os'] = 'AIX' grains['osfullname'] = osname grains['osrelease'] = osrelease grains['osrelease_techlevel'] = osrelease_techlevel grains.update(_aix_cpudata()) else: grains['os'] = grains['kernel'] if grains['kernel'] == 'FreeBSD': try: grains['osrelease'] = __salt__['cmd.run']('freebsd-version -u').split('-')[0] except salt.exceptions.CommandExecutionError: # freebsd-version was introduced in 10.0. # derive osrelease from kernelversion prior to that grains['osrelease'] = grains['kernelrelease'].split('-')[0] grains.update(_bsd_cpudata(grains)) if grains['kernel'] in ('OpenBSD', 'NetBSD'): grains.update(_bsd_cpudata(grains)) grains['osrelease'] = grains['kernelrelease'].split('-')[0] if grains['kernel'] == 'NetBSD': grains.update(_netbsd_gpu_data()) if not grains['os']: grains['os'] = 'Unknown {0}'.format(grains['kernel']) grains['os_family'] = 'Unknown' else: # this assigns family names based on the os name # family defaults to the os name if not found grains['os_family'] = _OS_FAMILY_MAP.get(grains['os'], grains['os']) # Build the osarch grain. This grain will be used for platform-specific # considerations such as package management. Fall back to the CPU # architecture. if grains.get('os_family') == 'Debian': osarch = __salt__['cmd.run']('dpkg --print-architecture').strip() elif grains.get('os_family') in ['RedHat', 'Suse']: osarch = salt.utils.pkg.rpm.get_osarch() elif grains.get('os_family') in ('NILinuxRT', 'Poky'): archinfo = {} for line in __salt__['cmd.run']('opkg print-architecture').splitlines(): if line.startswith('arch'): _, arch, priority = line.split() archinfo[arch.strip()] = int(priority.strip()) # Return osarch in priority order (higher to lower) osarch = sorted(archinfo, key=archinfo.get, reverse=True) else: osarch = grains['cpuarch'] grains['osarch'] = osarch grains.update(_memdata(grains)) # Get the hardware and bios data grains.update(_hw_data(grains)) # Load the virtual machine info grains.update(_virtual(grains)) grains.update(_virtual_hv(grains)) grains.update(_ps(grains)) if grains.get('osrelease', ''): osrelease_info = grains['osrelease'].split('.') for idx, value in enumerate(osrelease_info): if not value.isdigit(): continue osrelease_info[idx] = int(value) grains['osrelease_info'] = tuple(osrelease_info) try: grains['osmajorrelease'] = int(grains['osrelease_info'][0]) except (IndexError, TypeError, ValueError): log.debug( 'Unable to derive osmajorrelease from osrelease_info \'%s\'. ' 'The osmajorrelease grain will not be set.', grains['osrelease_info'] ) os_name = grains['os' if grains.get('os') in ( 'Debian', 'FreeBSD', 'OpenBSD', 'NetBSD', 'Mac', 'Raspbian') else 'osfullname'] grains['osfinger'] = '{0}-{1}'.format( os_name, grains['osrelease'] if os_name in ('Ubuntu',) else grains['osrelease_info'][0]) return grains def locale_info(): ''' Provides defaultlanguage defaultencoding ''' grains = {} grains['locale_info'] = {} if salt.utils.platform.is_proxy(): return grains try: ( grains['locale_info']['defaultlanguage'], grains['locale_info']['defaultencoding'] ) = locale.getdefaultlocale() except Exception: # locale.getdefaultlocale can ValueError!! Catch anything else it # might do, per #2205 grains['locale_info']['defaultlanguage'] = 'unknown' grains['locale_info']['defaultencoding'] = 'unknown' grains['locale_info']['detectedencoding'] = __salt_system_encoding__ if _DATEUTIL_TZ: grains['locale_info']['timezone'] = datetime.datetime.now(dateutil.tz.tzlocal()).tzname() return grains def hostname(): ''' Return fqdn, hostname, domainname ''' # This is going to need some work # Provides: # fqdn # host # localhost # domain global __FQDN__ grains = {} if salt.utils.platform.is_proxy(): return grains grains['localhost'] = socket.gethostname() if __FQDN__ is None: __FQDN__ = salt.utils.network.get_fqhostname() # On some distros (notably FreeBSD) if there is no hostname set # salt.utils.network.get_fqhostname() will return None. # In this case we punt and log a message at error level, but force the # hostname and domain to be localhost.localdomain # Otherwise we would stacktrace below if __FQDN__ is None: # still! log.error('Having trouble getting a hostname. Does this machine have its hostname and domain set properly?') __FQDN__ = 'localhost.localdomain' grains['fqdn'] = __FQDN__ (grains['host'], grains['domain']) = grains['fqdn'].partition('.')[::2] return grains def append_domain(): ''' Return append_domain if set ''' grain = {} if salt.utils.platform.is_proxy(): return grain if 'append_domain' in __opts__: grain['append_domain'] = __opts__['append_domain'] return grain def fqdns(): ''' Return all known FQDNs for the system by enumerating all interfaces and then trying to reverse resolve them (excluding 'lo' interface). ''' # Provides: # fqdns grains = {} fqdns = set() addresses = salt.utils.network.ip_addrs(include_loopback=False, interface_data=_get_interfaces()) addresses.extend(salt.utils.network.ip_addrs6(include_loopback=False, interface_data=_get_interfaces())) err_message = 'Exception during resolving address: %s' for ip in addresses: try: name, aliaslist, addresslist = socket.gethostbyaddr(ip) fqdns.update([socket.getfqdn(name)] + [als for als in aliaslist if salt.utils.network.is_fqdn(als)]) except socket.herror as err: if err.errno == 0: # No FQDN for this IP address, so we don't need to know this all the time. log.debug("Unable to resolve address %s: %s", ip, err) else: log.error(err_message, err) except (socket.error, socket.gaierror, socket.timeout) as err: log.error(err_message, err) return {"fqdns": sorted(list(fqdns))} def ip_fqdn(): ''' Return ip address and FQDN grains ''' if salt.utils.platform.is_proxy(): return {} ret = {} ret['ipv4'] = salt.utils.network.ip_addrs(include_loopback=True) ret['ipv6'] = salt.utils.network.ip_addrs6(include_loopback=True) _fqdn = hostname()['fqdn'] for socket_type, ipv_num in ((socket.AF_INET, '4'), (socket.AF_INET6, '6')): key = 'fqdn_ip' + ipv_num if not ret['ipv' + ipv_num]: ret[key] = [] else: try: start_time = datetime.datetime.utcnow() info = socket.getaddrinfo(_fqdn, None, socket_type) ret[key] = list(set(item[4][0] for item in info)) except socket.error: timediff = datetime.datetime.utcnow() - start_time if timediff.seconds > 5 and __opts__['__role'] == 'master': log.warning( 'Unable to find IPv%s record for "%s" causing a %s ' 'second timeout when rendering grains. Set the dns or ' '/etc/hosts for IPv%s to clear this.', ipv_num, _fqdn, timediff, ipv_num ) ret[key] = [] return ret def ip_interfaces(): ''' Provide a dict of the connected interfaces and their ip addresses The addresses will be passed as a list for each interface ''' # Provides: # ip_interfaces if salt.utils.platform.is_proxy(): return {} ret = {} ifaces = _get_interfaces() for face in ifaces: iface_ips = [] for inet in ifaces[face].get('inet', []): if 'address' in inet: iface_ips.append(inet['address']) for inet in ifaces[face].get('inet6', []): if 'address' in inet: iface_ips.append(inet['address']) for secondary in ifaces[face].get('secondary', []): if 'address' in secondary: iface_ips.append(secondary['address']) ret[face] = iface_ips return {'ip_interfaces': ret} def ip4_interfaces(): ''' Provide a dict of the connected interfaces and their ip4 addresses The addresses will be passed as a list for each interface ''' # Provides: # ip_interfaces if salt.utils.platform.is_proxy(): return {} ret = {} ifaces = _get_interfaces() for face in ifaces: iface_ips = [] for inet in ifaces[face].get('inet', []): if 'address' in inet: iface_ips.append(inet['address']) for secondary in ifaces[face].get('secondary', []): if 'address' in secondary: iface_ips.append(secondary['address']) ret[face] = iface_ips return {'ip4_interfaces': ret} def ip6_interfaces(): ''' Provide a dict of the connected interfaces and their ip6 addresses The addresses will be passed as a list for each interface ''' # Provides: # ip_interfaces if salt.utils.platform.is_proxy(): return {} ret = {} ifaces = _get_interfaces() for face in ifaces: iface_ips = [] for inet in ifaces[face].get('inet6', []): if 'address' in inet: iface_ips.append(inet['address']) for secondary in ifaces[face].get('secondary', []): if 'address' in secondary: iface_ips.append(secondary['address']) ret[face] = iface_ips return {'ip6_interfaces': ret} def hwaddr_interfaces(): ''' Provide a dict of the connected interfaces and their hw addresses (Mac Address) ''' # Provides: # hwaddr_interfaces ret = {} ifaces = _get_interfaces() for face in ifaces: if 'hwaddr' in ifaces[face]: ret[face] = ifaces[face]['hwaddr'] return {'hwaddr_interfaces': ret} def dns(): ''' Parse the resolver configuration file .. versionadded:: 2016.3.0 ''' # Provides: # dns if salt.utils.platform.is_windows() or 'proxyminion' in __opts__: return {} resolv = salt.utils.dns.parse_resolv() for key in ('nameservers', 'ip4_nameservers', 'ip6_nameservers', 'sortlist'): if key in resolv: resolv[key] = [six.text_type(i) for i in resolv[key]] return {'dns': resolv} if resolv else {} def cwd(): ''' Current working directory ''' return {'cwd': os.getcwd()} def path(): ''' Return the path ''' # Provides: # path return {'path': os.environ.get('PATH', '').strip()} def pythonversion(): ''' Return the Python version ''' # Provides: # pythonversion return {'pythonversion': list(sys.version_info)} def pythonpath(): ''' Return the Python path ''' # Provides: # pythonpath return {'pythonpath': sys.path} def pythonexecutable(): ''' Return the python executable in use ''' # Provides: # pythonexecutable return {'pythonexecutable': sys.executable} def saltpath(): ''' Return the path of the salt module ''' # Provides: # saltpath salt_path = os.path.abspath(os.path.join(__file__, os.path.pardir)) return {'saltpath': os.path.dirname(salt_path)} def saltversion(): ''' Return the version of salt ''' # Provides: # saltversion from salt.version import __version__ return {'saltversion': __version__} def zmqversion(): ''' Return the zeromq version ''' # Provides: # zmqversion try: import zmq return {'zmqversion': zmq.zmq_version()} # pylint: disable=no-member except ImportError: return {} def saltversioninfo(): ''' Return the version_info of salt .. versionadded:: 0.17.0 ''' # Provides: # saltversioninfo from salt.version import __version_info__ return {'saltversioninfo': list(__version_info__)} def _hw_data(osdata): ''' Get system specific hardware data from dmidecode Provides biosversion productname manufacturer serialnumber biosreleasedate uuid .. versionadded:: 0.9.5 ''' if salt.utils.platform.is_proxy(): return {} grains = {} if osdata['kernel'] == 'Linux' and os.path.exists('/sys/class/dmi/id'): # On many Linux distributions basic firmware information is available via sysfs # requires CONFIG_DMIID to be enabled in the Linux kernel configuration sysfs_firmware_info = { 'biosversion': 'bios_version', 'productname': 'product_name', 'manufacturer': 'sys_vendor', 'biosreleasedate': 'bios_date', 'uuid': 'product_uuid', 'serialnumber': 'product_serial' } for key, fw_file in sysfs_firmware_info.items(): contents_file = os.path.join('/sys/class/dmi/id', fw_file) if os.path.exists(contents_file): try: with salt.utils.files.fopen(contents_file, 'r') as ifile: grains[key] = salt.utils.stringutils.to_unicode(ifile.read().strip(), errors='replace') if key == 'uuid': grains['uuid'] = grains['uuid'].lower() except (IOError, OSError) as err: # PermissionError is new to Python 3, but corresponds to the EACESS and # EPERM error numbers. Use those instead here for PY2 compatibility. if err.errno == EACCES or err.errno == EPERM: # Skip the grain if non-root user has no access to the file. pass elif salt.utils.path.which_bin(['dmidecode', 'smbios']) is not None and not ( salt.utils.platform.is_smartos() or ( # SunOS on SPARC - 'smbios: failed to load SMBIOS: System does not export an SMBIOS table' osdata['kernel'] == 'SunOS' and osdata['cpuarch'].startswith('sparc') )): # On SmartOS (possibly SunOS also) smbios only works in the global zone # smbios is also not compatible with linux's smbios (smbios -s = print summarized) grains = { 'biosversion': __salt__['smbios.get']('bios-version'), 'productname': __salt__['smbios.get']('system-product-name'), 'manufacturer': __salt__['smbios.get']('system-manufacturer'), 'biosreleasedate': __salt__['smbios.get']('bios-release-date'), 'uuid': __salt__['smbios.get']('system-uuid') } grains = dict([(key, val) for key, val in grains.items() if val is not None]) uuid = __salt__['smbios.get']('system-uuid') if uuid is not None: grains['uuid'] = uuid.lower() for serial in ('system-serial-number', 'chassis-serial-number', 'baseboard-serial-number'): serial = __salt__['smbios.get'](serial) if serial is not None: grains['serialnumber'] = serial break elif salt.utils.path.which_bin(['fw_printenv']) is not None: # ARM Linux devices expose UBOOT env variables via fw_printenv hwdata = { 'manufacturer': 'manufacturer', 'serialnumber': 'serial#', 'productname': 'DeviceDesc', } for grain_name, cmd_key in six.iteritems(hwdata): result = __salt__['cmd.run_all']('fw_printenv {0}'.format(cmd_key)) if result['retcode'] == 0: uboot_keyval = result['stdout'].split('=') grains[grain_name] = _clean_value(grain_name, uboot_keyval[1]) elif osdata['kernel'] == 'FreeBSD': # On FreeBSD /bin/kenv (already in base system) # can be used instead of dmidecode kenv = salt.utils.path.which('kenv') if kenv: # In theory, it will be easier to add new fields to this later fbsd_hwdata = { 'biosversion': 'smbios.bios.version', 'manufacturer': 'smbios.system.maker', 'serialnumber': 'smbios.system.serial', 'productname': 'smbios.system.product', 'biosreleasedate': 'smbios.bios.reldate', 'uuid': 'smbios.system.uuid', } for key, val in six.iteritems(fbsd_hwdata): value = __salt__['cmd.run']('{0} {1}'.format(kenv, val)) grains[key] = _clean_value(key, value) elif osdata['kernel'] == 'OpenBSD': sysctl = salt.utils.path.which('sysctl') hwdata = {'biosversion': 'hw.version', 'manufacturer': 'hw.vendor', 'productname': 'hw.product', 'serialnumber': 'hw.serialno', 'uuid': 'hw.uuid'} for key, oid in six.iteritems(hwdata): value = __salt__['cmd.run']('{0} -n {1}'.format(sysctl, oid)) if not value.endswith(' value is not available'): grains[key] = _clean_value(key, value) elif osdata['kernel'] == 'NetBSD': sysctl = salt.utils.path.which('sysctl') nbsd_hwdata = { 'biosversion': 'machdep.dmi.board-version', 'manufacturer': 'machdep.dmi.system-vendor', 'serialnumber': 'machdep.dmi.system-serial', 'productname': 'machdep.dmi.system-product', 'biosreleasedate': 'machdep.dmi.bios-date', 'uuid': 'machdep.dmi.system-uuid', } for key, oid in six.iteritems(nbsd_hwdata): result = __salt__['cmd.run_all']('{0} -n {1}'.format(sysctl, oid)) if result['retcode'] == 0: grains[key] = _clean_value(key, result['stdout']) elif osdata['kernel'] == 'Darwin': grains['manufacturer'] = 'Apple Inc.' sysctl = salt.utils.path.which('sysctl') hwdata = {'productname': 'hw.model'} for key, oid in hwdata.items(): value = __salt__['cmd.run']('{0} -b {1}'.format(sysctl, oid)) if not value.endswith(' is invalid'): grains[key] = _clean_value(key, value) elif osdata['kernel'] == 'SunOS' and osdata['cpuarch'].startswith('sparc'): # Depending on the hardware model, commands can report different bits # of information. With that said, consolidate the output from various # commands and attempt various lookups. data = "" for (cmd, args) in (('/usr/sbin/prtdiag', '-v'), ('/usr/sbin/prtconf', '-vp'), ('/usr/sbin/virtinfo', '-a')): if salt.utils.path.which(cmd): # Also verifies that cmd is executable data += __salt__['cmd.run']('{0} {1}'.format(cmd, args)) data += '\n' sn_regexes = [ re.compile(r) for r in [ r'(?im)^\s*Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag r'(?im)^\s*chassis-sn:\s*(\S+)', # prtconf r'(?im)^\s*Chassis\s+Serial#:\s*(\S+)', # virtinfo ] ] obp_regexes = [ re.compile(r) for r in [ r'(?im)^\s*System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag r'(?im)^\s*version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf ] ] fw_regexes = [ re.compile(r) for r in [ r'(?im)^\s*Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag ] ] uuid_regexes = [ re.compile(r) for r in [ r'(?im)^\s*Domain\s+UUID:\s*(\S+)', # virtinfo ] ] manufacture_regexes = [ re.compile(r) for r in [ r'(?im)^\s*System\s+Configuration:\s*(.*)(?=sun)', # prtdiag ] ] product_regexes = [ re.compile(r) for r in [ r'(?im)^\s*System\s+Configuration:\s*.*?sun\d\S+[^\S\r\n]*(.*)', # prtdiag r'(?im)^[^\S\r\n]*banner-name:[^\S\r\n]*(.*)', # prtconf r'(?im)^[^\S\r\n]*product-name:[^\S\r\n]*(.*)', # prtconf ] ] sn_regexes = [ re.compile(r) for r in [ r'(?im)Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag r'(?i)Chassis\s+Serial#:\s*(\S+)', # virtinfo r'(?i)chassis-sn:\s*(\S+)', # prtconf ] ] obp_regexes = [ re.compile(r) for r in [ r'(?im)System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag r'(?im)version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf ] ] fw_regexes = [ re.compile(r) for r in [ r'(?i)Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag ] ] uuid_regexes = [ re.compile(r) for r in [ r'(?i)Domain\s+UUID:\s+(\S+)', # virtinfo ] ] for regex in sn_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: grains['serialnumber'] = res.group(1).strip().replace("'", "") break for regex in obp_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: obp_rev, obp_date = res.groups()[0:2] # Limit the number in case we found the data in multiple places grains['biosversion'] = obp_rev.strip().replace("'", "") grains['biosreleasedate'] = obp_date.strip().replace("'", "") for regex in fw_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: fw_rev, fw_date = res.groups()[0:2] grains['systemfirmware'] = fw_rev.strip().replace("'", "") grains['systemfirmwaredate'] = fw_date.strip().replace("'", "") break for regex in uuid_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: grains['uuid'] = res.group(1).strip().replace("'", "") break for regex in manufacture_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: grains['manufacture'] = res.group(1).strip().replace("'", "") break for regex in product_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: t_productname = res.group(1).strip().replace("'", "") if t_productname: grains['product'] = t_productname grains['productname'] = t_productname break elif osdata['kernel'] == 'AIX': cmd = salt.utils.path.which('prtconf') if cmd: data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'), ('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')): for regex in [re.compile(r) for r in [regstring]]: res = regex.search(data) if res and len(res.groups()) >= 1: grains[dest] = res.group(1).strip().replace("'", '') product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')] for regex in product_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",") break else: log.error('The \'prtconf\' binary was not found in $PATH.') elif osdata['kernel'] == 'AIX': cmd = salt.utils.path.which('prtconf') if data: data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'), ('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')): for regex in [re.compile(r) for r in [regstring]]: res = regex.search(data) if res and len(res.groups()) >= 1: grains[dest] = res.group(1).strip().replace("'", '') product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')] for regex in product_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",") break else: log.error('The \'prtconf\' binary was not found in $PATH.') return grains def _get_hash_by_shell(): ''' Shell-out Python 3 for compute reliable hash :return: ''' id_ = __opts__.get('id', '') id_hash = None py_ver = sys.version_info[:2] if py_ver >= (3, 3): # Python 3.3 enabled hash randomization, so we need to shell out to get # a reliable hash. id_hash = __salt__['cmd.run']([sys.executable, '-c', 'print(hash("{0}"))'.format(id_)], env={'PYTHONHASHSEED': '0'}) try: id_hash = int(id_hash) except (TypeError, ValueError): log.debug('Failed to hash the ID to get the server_id grain. Result of hash command: %s', id_hash) id_hash = None if id_hash is None: # Python < 3.3 or error encountered above id_hash = hash(id_) return abs(id_hash % (2 ** 31)) def get_server_id(): ''' Provides an integer based on the FQDN of a machine. Useful as server-id in MySQL replication or anywhere else you'll need an ID like this. ''' # Provides: # server_id if salt.utils.platform.is_proxy(): server_id = {} else: use_crc = __opts__.get('server_id_use_crc') if bool(use_crc): id_hash = getattr(zlib, use_crc, zlib.adler32)(__opts__.get('id', '').encode()) & 0xffffffff else: log.debug('This server_id is computed not by Adler32 nor by CRC32. ' 'Please use "server_id_use_crc" option and define algorithm you ' 'prefer (default "Adler32"). Starting with Sodium, the ' 'server_id will be computed with Adler32 by default.') id_hash = _get_hash_by_shell() server_id = {'server_id': id_hash} return server_id def get_master(): ''' Provides the minion with the name of its master. This is useful in states to target other services running on the master. ''' # Provides: # master return {'master': __opts__.get('master', '')} def default_gateway(): ''' Populates grains which describe whether a server has a default gateway configured or not. Uses `ip -4 route show` and `ip -6 route show` and greps for a `default` at the beginning of any line. Assuming the standard `default via <ip>` format for default gateways, it will also parse out the ip address of the default gateway, and put it in ip4_gw or ip6_gw. If the `ip` command is unavailable, no grains will be populated. Currently does not support multiple default gateways. The grains will be set to the first default gateway found. List of grains: ip4_gw: True # ip/True/False if default ipv4 gateway ip6_gw: True # ip/True/False if default ipv6 gateway ip_gw: True # True if either of the above is True, False otherwise ''' grains = {} ip_bin = salt.utils.path.which('ip') if not ip_bin: return {} grains['ip_gw'] = False grains['ip4_gw'] = False grains['ip6_gw'] = False for ip_version in ('4', '6'): try: out = __salt__['cmd.run']([ip_bin, '-' + ip_version, 'route', 'show']) for line in out.splitlines(): if line.startswith('default'): grains['ip_gw'] = True grains['ip{0}_gw'.format(ip_version)] = True try: via, gw_ip = line.split()[1:3] except ValueError: pass else: if via == 'via': grains['ip{0}_gw'.format(ip_version)] = gw_ip break except Exception: continue return grains def kernelparams(): ''' Return the kernel boot parameters ''' if salt.utils.platform.is_windows(): # TODO: add grains using `bcdedit /enum {current}` return {} else: try: with salt.utils.files.fopen('/proc/cmdline', 'r') as fhr: cmdline = fhr.read() grains = {'kernelparams': []} for data in [item.split('=') for item in salt.utils.args.shlex_split(cmdline)]: value = None if len(data) == 2: value = data[1].strip('"') grains['kernelparams'] += [(data[0], value)] except IOError as exc: grains = {} log.debug('Failed to read /proc/cmdline: %s', exc) return grains
saltstack/salt
salt/grains/core.py
saltpath
python
def saltpath(): ''' Return the path of the salt module ''' # Provides: # saltpath salt_path = os.path.abspath(os.path.join(__file__, os.path.pardir)) return {'saltpath': os.path.dirname(salt_path)}
Return the path of the salt module
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/grains/core.py#L2403-L2410
null
# -*- coding: utf-8 -*- ''' The static grains, these are the core, or built in grains. When grains are loaded they are not loaded in the same way that modules are loaded, grain functions are detected and executed, the functions MUST return a dict which will be applied to the main grains dict. This module will always be executed first, so that any grains loaded here in the core module can be overwritten just by returning dict keys with the same value as those returned here ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import socket import sys import re import platform import logging import locale import uuid import zlib from errno import EACCES, EPERM import datetime import warnings # pylint: disable=import-error try: import dateutil.tz _DATEUTIL_TZ = True except ImportError: _DATEUTIL_TZ = False __proxyenabled__ = ['*'] __FQDN__ = None # Extend the default list of supported distros. This will be used for the # /etc/DISTRO-release checking that is part of linux_distribution() from platform import _supported_dists _supported_dists += ('arch', 'mageia', 'meego', 'vmware', 'bluewhite64', 'slamd64', 'ovs', 'system', 'mint', 'oracle', 'void') # linux_distribution deprecated in py3.7 try: from platform import linux_distribution as _deprecated_linux_distribution def linux_distribution(**kwargs): with warnings.catch_warnings(): warnings.simplefilter("ignore") return _deprecated_linux_distribution(**kwargs) except ImportError: from distro import linux_distribution # Import salt libs import salt.exceptions import salt.log import salt.utils.args import salt.utils.dns import salt.utils.files import salt.utils.network import salt.utils.path import salt.utils.pkg.rpm import salt.utils.platform import salt.utils.stringutils import salt.utils.versions from salt.ext import six from salt.ext.six.moves import range if salt.utils.platform.is_windows(): import salt.utils.win_osinfo # Solve the Chicken and egg problem where grains need to run before any # of the modules are loaded and are generally available for any usage. import salt.modules.cmdmod import salt.modules.smbios __salt__ = { 'cmd.run': salt.modules.cmdmod._run_quiet, 'cmd.retcode': salt.modules.cmdmod._retcode_quiet, 'cmd.run_all': salt.modules.cmdmod._run_all_quiet, 'smbios.records': salt.modules.smbios.records, 'smbios.get': salt.modules.smbios.get, } log = logging.getLogger(__name__) HAS_WMI = False if salt.utils.platform.is_windows(): # attempt to import the python wmi module # the Windows minion uses WMI for some of its grains try: import wmi # pylint: disable=import-error import salt.utils.winapi import win32api import salt.utils.win_reg HAS_WMI = True except ImportError: log.exception( 'Unable to import Python wmi module, some core grains ' 'will be missing' ) HAS_UNAME = True if not hasattr(os, 'uname'): HAS_UNAME = False _INTERFACES = {} def _windows_cpudata(): ''' Return some CPU information on Windows minions ''' # Provides: # num_cpus # cpu_model grains = {} if 'NUMBER_OF_PROCESSORS' in os.environ: # Cast to int so that the logic isn't broken when used as a # conditional in templating. Also follows _linux_cpudata() try: grains['num_cpus'] = int(os.environ['NUMBER_OF_PROCESSORS']) except ValueError: grains['num_cpus'] = 1 grains['cpu_model'] = salt.utils.win_reg.read_value( hive="HKEY_LOCAL_MACHINE", key="HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", vname="ProcessorNameString").get('vdata') return grains def _linux_cpudata(): ''' Return some CPU information for Linux minions ''' # Provides: # num_cpus # cpu_model # cpu_flags grains = {} cpuinfo = '/proc/cpuinfo' # Parse over the cpuinfo file if os.path.isfile(cpuinfo): with salt.utils.files.fopen(cpuinfo, 'r') as _fp: grains['num_cpus'] = 0 for line in _fp: comps = line.split(':') if not len(comps) > 1: continue key = comps[0].strip() val = comps[1].strip() if key == 'processor': grains['num_cpus'] += 1 elif key == 'model name': grains['cpu_model'] = val elif key == 'flags': grains['cpu_flags'] = val.split() elif key == 'Features': grains['cpu_flags'] = val.split() # ARM support - /proc/cpuinfo # # Processor : ARMv6-compatible processor rev 7 (v6l) # BogoMIPS : 697.95 # Features : swp half thumb fastmult vfp edsp java tls # CPU implementer : 0x41 # CPU architecture: 7 # CPU variant : 0x0 # CPU part : 0xb76 # CPU revision : 7 # # Hardware : BCM2708 # Revision : 0002 # Serial : 00000000 elif key == 'Processor': grains['cpu_model'] = val.split('-')[0] grains['num_cpus'] = 1 if 'num_cpus' not in grains: grains['num_cpus'] = 0 if 'cpu_model' not in grains: grains['cpu_model'] = 'Unknown' if 'cpu_flags' not in grains: grains['cpu_flags'] = [] return grains def _linux_gpu_data(): ''' num_gpus: int gpus: - vendor: nvidia|amd|ati|... model: string ''' if __opts__.get('enable_lspci', True) is False: return {} if __opts__.get('enable_gpu_grains', True) is False: return {} lspci = salt.utils.path.which('lspci') if not lspci: log.debug( 'The `lspci` binary is not available on the system. GPU grains ' 'will not be available.' ) return {} # dominant gpu vendors to search for (MUST be lowercase for matching below) known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed'] gpu_classes = ('vga compatible controller', '3d controller') devs = [] try: lspci_out = __salt__['cmd.run']('{0} -vmm'.format(lspci)) cur_dev = {} error = False # Add a blank element to the lspci_out.splitlines() list, # otherwise the last device is not evaluated as a cur_dev and ignored. lspci_list = lspci_out.splitlines() lspci_list.append('') for line in lspci_list: # check for record-separating empty lines if line == '': if cur_dev.get('Class', '').lower() in gpu_classes: devs.append(cur_dev) cur_dev = {} continue if re.match(r'^\w+:\s+.*', line): key, val = line.split(':', 1) cur_dev[key.strip()] = val.strip() else: error = True log.debug('Unexpected lspci output: \'%s\'', line) if error: log.warning( 'Error loading grains, unexpected linux_gpu_data output, ' 'check that you have a valid shell configured and ' 'permissions to run lspci command' ) except OSError: pass gpus = [] for gpu in devs: vendor_strings = re.split('[^A-Za-z0-9]', gpu['Vendor'].lower()) # default vendor to 'unknown', overwrite if we match a known one vendor = 'unknown' for name in known_vendors: # search for an 'expected' vendor name in the list of strings if name in vendor_strings: vendor = name break gpus.append({'vendor': vendor, 'model': gpu['Device']}) grains = {} grains['num_gpus'] = len(gpus) grains['gpus'] = gpus return grains def _netbsd_gpu_data(): ''' num_gpus: int gpus: - vendor: nvidia|amd|ati|... model: string ''' known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed'] gpus = [] try: pcictl_out = __salt__['cmd.run']('pcictl pci0 list') for line in pcictl_out.splitlines(): for vendor in known_vendors: vendor_match = re.match( r'[0-9:]+ ({0}) (.+) \(VGA .+\)'.format(vendor), line, re.IGNORECASE ) if vendor_match: gpus.append({'vendor': vendor_match.group(1), 'model': vendor_match.group(2)}) except OSError: pass grains = {} grains['num_gpus'] = len(gpus) grains['gpus'] = gpus return grains def _osx_gpudata(): ''' num_gpus: int gpus: - vendor: nvidia|amd|ati|... model: string ''' gpus = [] try: pcictl_out = __salt__['cmd.run']('system_profiler SPDisplaysDataType') for line in pcictl_out.splitlines(): fieldname, _, fieldval = line.partition(': ') if fieldname.strip() == "Chipset Model": vendor, _, model = fieldval.partition(' ') vendor = vendor.lower() gpus.append({'vendor': vendor, 'model': model}) except OSError: pass grains = {} grains['num_gpus'] = len(gpus) grains['gpus'] = gpus return grains def _bsd_cpudata(osdata): ''' Return CPU information for BSD-like systems ''' # Provides: # cpuarch # num_cpus # cpu_model # cpu_flags sysctl = salt.utils.path.which('sysctl') arch = salt.utils.path.which('arch') cmds = {} if sysctl: cmds.update({ 'num_cpus': '{0} -n hw.ncpu'.format(sysctl), 'cpuarch': '{0} -n hw.machine'.format(sysctl), 'cpu_model': '{0} -n hw.model'.format(sysctl), }) if arch and osdata['kernel'] == 'OpenBSD': cmds['cpuarch'] = '{0} -s'.format(arch) if osdata['kernel'] == 'Darwin': cmds['cpu_model'] = '{0} -n machdep.cpu.brand_string'.format(sysctl) cmds['cpu_flags'] = '{0} -n machdep.cpu.features'.format(sysctl) grains = dict([(k, __salt__['cmd.run'](v)) for k, v in six.iteritems(cmds)]) if 'cpu_flags' in grains and isinstance(grains['cpu_flags'], six.string_types): grains['cpu_flags'] = grains['cpu_flags'].split(' ') if osdata['kernel'] == 'NetBSD': grains['cpu_flags'] = [] for line in __salt__['cmd.run']('cpuctl identify 0').splitlines(): cpu_match = re.match(r'cpu[0-9]:\ features[0-9]?\ .+<(.+)>', line) if cpu_match: flag = cpu_match.group(1).split(',') grains['cpu_flags'].extend(flag) if osdata['kernel'] == 'FreeBSD' and os.path.isfile('/var/run/dmesg.boot'): grains['cpu_flags'] = [] # TODO: at least it needs to be tested for BSD other then FreeBSD with salt.utils.files.fopen('/var/run/dmesg.boot', 'r') as _fp: cpu_here = False for line in _fp: if line.startswith('CPU: '): cpu_here = True # starts CPU descr continue if cpu_here: if not line.startswith(' '): break # game over if 'Features' in line: start = line.find('<') end = line.find('>') if start > 0 and end > 0: flag = line[start + 1:end].split(',') grains['cpu_flags'].extend(flag) try: grains['num_cpus'] = int(grains['num_cpus']) except ValueError: grains['num_cpus'] = 1 return grains def _sunos_cpudata(): ''' Return the CPU information for Solaris-like systems ''' # Provides: # cpuarch # num_cpus # cpu_model # cpu_flags grains = {} grains['cpu_flags'] = [] grains['cpuarch'] = __salt__['cmd.run']('isainfo -k') psrinfo = '/usr/sbin/psrinfo 2>/dev/null' grains['num_cpus'] = len(__salt__['cmd.run'](psrinfo, python_shell=True).splitlines()) kstat_info = 'kstat -p cpu_info:*:*:brand' for line in __salt__['cmd.run'](kstat_info).splitlines(): match = re.match(r'(\w+:\d+:\w+\d+:\w+)\s+(.+)', line) if match: grains['cpu_model'] = match.group(2) isainfo = 'isainfo -n -v' for line in __salt__['cmd.run'](isainfo).splitlines(): match = re.match(r'^\s+(.+)', line) if match: cpu_flags = match.group(1).split() grains['cpu_flags'].extend(cpu_flags) return grains def _aix_cpudata(): ''' Return CPU information for AIX systems ''' # Provides: # cpuarch # num_cpus # cpu_model # cpu_flags grains = {} cmd = salt.utils.path.which('prtconf') if cmd: data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep for dest, regstring in (('cpuarch', r'(?im)^\s*Processor\s+Type:\s+(\S+)'), ('cpu_flags', r'(?im)^\s*Processor\s+Version:\s+(\S+)'), ('cpu_model', r'(?im)^\s*Processor\s+Implementation\s+Mode:\s+(.*)'), ('num_cpus', r'(?im)^\s*Number\s+Of\s+Processors:\s+(\S+)')): for regex in [re.compile(r) for r in [regstring]]: res = regex.search(data) if res and len(res.groups()) >= 1: grains[dest] = res.group(1).strip().replace("'", '') else: log.error('The \'prtconf\' binary was not found in $PATH.') return grains def _linux_memdata(): ''' Return the memory information for Linux-like systems ''' grains = {'mem_total': 0, 'swap_total': 0} meminfo = '/proc/meminfo' if os.path.isfile(meminfo): with salt.utils.files.fopen(meminfo, 'r') as ifile: for line in ifile: comps = line.rstrip('\n').split(':') if not len(comps) > 1: continue if comps[0].strip() == 'MemTotal': # Use floor division to force output to be an integer grains['mem_total'] = int(comps[1].split()[0]) // 1024 if comps[0].strip() == 'SwapTotal': # Use floor division to force output to be an integer grains['swap_total'] = int(comps[1].split()[0]) // 1024 return grains def _osx_memdata(): ''' Return the memory information for BSD-like systems ''' grains = {'mem_total': 0, 'swap_total': 0} sysctl = salt.utils.path.which('sysctl') if sysctl: mem = __salt__['cmd.run']('{0} -n hw.memsize'.format(sysctl)) swap_total = __salt__['cmd.run']('{0} -n vm.swapusage'.format(sysctl)).split()[2].replace(',', '.') if swap_total.endswith('K'): _power = 2**10 elif swap_total.endswith('M'): _power = 2**20 elif swap_total.endswith('G'): _power = 2**30 swap_total = float(swap_total[:-1]) * _power grains['mem_total'] = int(mem) // 1024 // 1024 grains['swap_total'] = int(swap_total) // 1024 // 1024 return grains def _bsd_memdata(osdata): ''' Return the memory information for BSD-like systems ''' grains = {'mem_total': 0, 'swap_total': 0} sysctl = salt.utils.path.which('sysctl') if sysctl: mem = __salt__['cmd.run']('{0} -n hw.physmem'.format(sysctl)) if osdata['kernel'] == 'NetBSD' and mem.startswith('-'): mem = __salt__['cmd.run']('{0} -n hw.physmem64'.format(sysctl)) grains['mem_total'] = int(mem) // 1024 // 1024 if osdata['kernel'] in ['OpenBSD', 'NetBSD']: swapctl = salt.utils.path.which('swapctl') swap_data = __salt__['cmd.run']('{0} -sk'.format(swapctl)) if swap_data == 'no swap devices configured': swap_total = 0 else: swap_total = swap_data.split(' ')[1] else: swap_total = __salt__['cmd.run']('{0} -n vm.swap_total'.format(sysctl)) grains['swap_total'] = int(swap_total) // 1024 // 1024 return grains def _sunos_memdata(): ''' Return the memory information for SunOS-like systems ''' grains = {'mem_total': 0, 'swap_total': 0} prtconf = '/usr/sbin/prtconf 2>/dev/null' for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines(): comps = line.split(' ') if comps[0].strip() == 'Memory' and comps[1].strip() == 'size:': grains['mem_total'] = int(comps[2].strip()) swap_cmd = salt.utils.path.which('swap') swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split() try: swap_avail = int(swap_data[-2][:-1]) swap_used = int(swap_data[-4][:-1]) swap_total = (swap_avail + swap_used) // 1024 except ValueError: swap_total = None grains['swap_total'] = swap_total return grains def _aix_memdata(): ''' Return the memory information for AIX systems ''' grains = {'mem_total': 0, 'swap_total': 0} prtconf = salt.utils.path.which('prtconf') if prtconf: for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines(): comps = [x for x in line.strip().split(' ') if x] if len(comps) > 2 and 'Memory' in comps[0] and 'Size' in comps[1]: grains['mem_total'] = int(comps[2]) break else: log.error('The \'prtconf\' binary was not found in $PATH.') swap_cmd = salt.utils.path.which('swap') if swap_cmd: swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split() try: swap_total = (int(swap_data[-2]) + int(swap_data[-6])) * 4 except ValueError: swap_total = None grains['swap_total'] = swap_total else: log.error('The \'swap\' binary was not found in $PATH.') return grains def _windows_memdata(): ''' Return the memory information for Windows systems ''' grains = {'mem_total': 0} # get the Total Physical memory as reported by msinfo32 tot_bytes = win32api.GlobalMemoryStatusEx()['TotalPhys'] # return memory info in gigabytes grains['mem_total'] = int(tot_bytes / (1024 ** 2)) return grains def _memdata(osdata): ''' Gather information about the system memory ''' # Provides: # mem_total # swap_total, for supported systems. grains = {'mem_total': 0} if osdata['kernel'] == 'Linux': grains.update(_linux_memdata()) elif osdata['kernel'] in ('FreeBSD', 'OpenBSD', 'NetBSD'): grains.update(_bsd_memdata(osdata)) elif osdata['kernel'] == 'Darwin': grains.update(_osx_memdata()) elif osdata['kernel'] == 'SunOS': grains.update(_sunos_memdata()) elif osdata['kernel'] == 'AIX': grains.update(_aix_memdata()) elif osdata['kernel'] == 'Windows' and HAS_WMI: grains.update(_windows_memdata()) return grains def _aix_get_machine_id(): ''' Parse the output of lsattr -El sys0 for os_uuid ''' grains = {} cmd = salt.utils.path.which('lsattr') if cmd: data = __salt__['cmd.run']('{0} -El sys0'.format(cmd)) + os.linesep uuid_regexes = [re.compile(r'(?im)^\s*os_uuid\s+(\S+)\s+(.*)')] for regex in uuid_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: grains['machine_id'] = res.group(1).strip() break else: log.error('The \'lsattr\' binary was not found in $PATH.') return grains def _windows_virtual(osdata): ''' Returns what type of virtual hardware is under the hood, kvm or physical ''' # Provides: # virtual # virtual_subtype grains = dict() if osdata['kernel'] != 'Windows': return grains grains['virtual'] = 'physical' # It is possible that the 'manufacturer' and/or 'productname' grains # exist but have a value of None. manufacturer = osdata.get('manufacturer', '') if manufacturer is None: manufacturer = '' productname = osdata.get('productname', '') if productname is None: productname = '' if 'QEMU' in manufacturer: # FIXME: Make this detect between kvm or qemu grains['virtual'] = 'kvm' if 'Bochs' in manufacturer: grains['virtual'] = 'kvm' # Product Name: (oVirt) www.ovirt.org # Red Hat Community virtualization Project based on kvm elif 'oVirt' in productname: grains['virtual'] = 'kvm' grains['virtual_subtype'] = 'oVirt' # Red Hat Enterprise Virtualization elif 'RHEV Hypervisor' in productname: grains['virtual'] = 'kvm' grains['virtual_subtype'] = 'rhev' # Product Name: VirtualBox elif 'VirtualBox' in productname: grains['virtual'] = 'VirtualBox' # Product Name: VMware Virtual Platform elif 'VMware Virtual Platform' in productname: grains['virtual'] = 'VMware' # Manufacturer: Microsoft Corporation # Product Name: Virtual Machine elif 'Microsoft' in manufacturer and \ 'Virtual Machine' in productname: grains['virtual'] = 'VirtualPC' # Manufacturer: Parallels Software International Inc. elif 'Parallels Software' in manufacturer: grains['virtual'] = 'Parallels' # Apache CloudStack elif 'CloudStack KVM Hypervisor' in productname: grains['virtual'] = 'kvm' grains['virtual_subtype'] = 'cloudstack' return grains def _virtual(osdata): ''' Returns what type of virtual hardware is under the hood, kvm or physical ''' # This is going to be a monster, if you are running a vm you can test this # grain with please submit patches! # Provides: # virtual # virtual_subtype grains = {'virtual': 'physical'} # Skip the below loop on platforms which have none of the desired cmds # This is a temporary measure until we can write proper virtual hardware # detection. skip_cmds = ('AIX',) # list of commands to be executed to determine the 'virtual' grain _cmds = ['systemd-detect-virt', 'virt-what', 'dmidecode'] # test first for virt-what, which covers most of the desired functionality # on most platforms if not salt.utils.platform.is_windows() and osdata['kernel'] not in skip_cmds: if salt.utils.path.which('virt-what'): _cmds = ['virt-what'] # Check if enable_lspci is True or False if __opts__.get('enable_lspci', True) is True: # /proc/bus/pci does not exists, lspci will fail if os.path.exists('/proc/bus/pci'): _cmds += ['lspci'] # Add additional last resort commands if osdata['kernel'] in skip_cmds: _cmds = () # Quick backout for BrandZ (Solaris LX Branded zones) # Don't waste time trying other commands to detect the virtual grain if HAS_UNAME and osdata['kernel'] == 'Linux' and 'BrandZ virtual linux' in os.uname(): grains['virtual'] = 'zone' return grains failed_commands = set() for command in _cmds: args = [] if osdata['kernel'] == 'Darwin': command = 'system_profiler' args = ['SPDisplaysDataType'] elif osdata['kernel'] == 'SunOS': virtinfo = salt.utils.path.which('virtinfo') if virtinfo: try: ret = __salt__['cmd.run_all']('{0} -a'.format(virtinfo)) except salt.exceptions.CommandExecutionError: if salt.log.is_logging_configured(): failed_commands.add(virtinfo) else: if ret['stdout'].endswith('not supported'): command = 'prtdiag' else: command = 'virtinfo' else: command = 'prtdiag' cmd = salt.utils.path.which(command) if not cmd: continue cmd = '{0} {1}'.format(cmd, ' '.join(args)) try: ret = __salt__['cmd.run_all'](cmd) if ret['retcode'] > 0: if salt.log.is_logging_configured(): # systemd-detect-virt always returns > 0 on non-virtualized # systems # prtdiag only works in the global zone, skip if it fails if salt.utils.platform.is_windows() or 'systemd-detect-virt' in cmd or 'prtdiag' in cmd: continue failed_commands.add(command) continue except salt.exceptions.CommandExecutionError: if salt.log.is_logging_configured(): if salt.utils.platform.is_windows(): continue failed_commands.add(command) continue output = ret['stdout'] if command == "system_profiler": macoutput = output.lower() if '0x1ab8' in macoutput: grains['virtual'] = 'Parallels' if 'parallels' in macoutput: grains['virtual'] = 'Parallels' if 'vmware' in macoutput: grains['virtual'] = 'VMware' if '0x15ad' in macoutput: grains['virtual'] = 'VMware' if 'virtualbox' in macoutput: grains['virtual'] = 'VirtualBox' # Break out of the loop so the next log message is not issued break elif command == 'systemd-detect-virt': if output in ('qemu', 'kvm', 'oracle', 'xen', 'bochs', 'chroot', 'uml', 'systemd-nspawn'): grains['virtual'] = output break elif 'vmware' in output: grains['virtual'] = 'VMware' break elif 'microsoft' in output: grains['virtual'] = 'VirtualPC' break elif 'lxc' in output: grains['virtual'] = 'LXC' break elif 'systemd-nspawn' in output: grains['virtual'] = 'LXC' break elif command == 'virt-what': try: output = output.splitlines()[-1] except IndexError: pass if output in ('kvm', 'qemu', 'uml', 'xen', 'lxc'): grains['virtual'] = output break elif 'vmware' in output: grains['virtual'] = 'VMware' break elif 'parallels' in output: grains['virtual'] = 'Parallels' break elif 'hyperv' in output: grains['virtual'] = 'HyperV' break elif command == 'dmidecode': # Product Name: VirtualBox if 'Vendor: QEMU' in output: # FIXME: Make this detect between kvm or qemu grains['virtual'] = 'kvm' if 'Manufacturer: QEMU' in output: grains['virtual'] = 'kvm' if 'Vendor: Bochs' in output: grains['virtual'] = 'kvm' if 'Manufacturer: Bochs' in output: grains['virtual'] = 'kvm' if 'BHYVE' in output: grains['virtual'] = 'bhyve' # Product Name: (oVirt) www.ovirt.org # Red Hat Community virtualization Project based on kvm elif 'Manufacturer: oVirt' in output: grains['virtual'] = 'kvm' grains['virtual_subtype'] = 'ovirt' # Red Hat Enterprise Virtualization elif 'Product Name: RHEV Hypervisor' in output: grains['virtual'] = 'kvm' grains['virtual_subtype'] = 'rhev' elif 'VirtualBox' in output: grains['virtual'] = 'VirtualBox' # Product Name: VMware Virtual Platform elif 'VMware' in output: grains['virtual'] = 'VMware' # Manufacturer: Microsoft Corporation # Product Name: Virtual Machine elif ': Microsoft' in output and 'Virtual Machine' in output: grains['virtual'] = 'VirtualPC' # Manufacturer: Parallels Software International Inc. elif 'Parallels Software' in output: grains['virtual'] = 'Parallels' elif 'Manufacturer: Google' in output: grains['virtual'] = 'kvm' # Proxmox KVM elif 'Vendor: SeaBIOS' in output: grains['virtual'] = 'kvm' # Break out of the loop, lspci parsing is not necessary break elif command == 'lspci': # dmidecode not available or the user does not have the necessary # permissions model = output.lower() if 'vmware' in model: grains['virtual'] = 'VMware' # 00:04.0 System peripheral: InnoTek Systemberatung GmbH # VirtualBox Guest Service elif 'virtualbox' in model: grains['virtual'] = 'VirtualBox' elif 'qemu' in model: grains['virtual'] = 'kvm' elif 'virtio' in model: grains['virtual'] = 'kvm' # Break out of the loop so the next log message is not issued break elif command == 'prtdiag': model = output.lower().split("\n")[0] if 'vmware' in model: grains['virtual'] = 'VMware' elif 'virtualbox' in model: grains['virtual'] = 'VirtualBox' elif 'qemu' in model: grains['virtual'] = 'kvm' elif 'joyent smartdc hvm' in model: grains['virtual'] = 'kvm' break elif command == 'virtinfo': grains['virtual'] = 'LDOM' break choices = ('Linux', 'HP-UX') isdir = os.path.isdir sysctl = salt.utils.path.which('sysctl') if osdata['kernel'] in choices: if os.path.isdir('/proc'): try: self_root = os.stat('/') init_root = os.stat('/proc/1/root/.') if self_root != init_root: grains['virtual_subtype'] = 'chroot' except (IOError, OSError): pass if isdir('/proc/vz'): if os.path.isfile('/proc/vz/version'): grains['virtual'] = 'openvzhn' elif os.path.isfile('/proc/vz/veinfo'): grains['virtual'] = 'openvzve' # a posteriori, it's expected for these to have failed: failed_commands.discard('lspci') failed_commands.discard('dmidecode') # Provide additional detection for OpenVZ if os.path.isfile('/proc/self/status'): with salt.utils.files.fopen('/proc/self/status') as status_file: vz_re = re.compile(r'^envID:\s+(\d+)$') for line in status_file: vz_match = vz_re.match(line.rstrip('\n')) if vz_match and int(vz_match.groups()[0]) != 0: grains['virtual'] = 'openvzve' elif vz_match and int(vz_match.groups()[0]) == 0: grains['virtual'] = 'openvzhn' if isdir('/proc/sys/xen') or \ isdir('/sys/bus/xen') or isdir('/proc/xen'): if os.path.isfile('/proc/xen/xsd_kva'): # Tested on CentOS 5.3 / 2.6.18-194.26.1.el5xen # Tested on CentOS 5.4 / 2.6.18-164.15.1.el5xen grains['virtual_subtype'] = 'Xen Dom0' else: if osdata.get('productname', '') == 'HVM domU': # Requires dmidecode! grains['virtual_subtype'] = 'Xen HVM DomU' elif os.path.isfile('/proc/xen/capabilities') and \ os.access('/proc/xen/capabilities', os.R_OK): with salt.utils.files.fopen('/proc/xen/capabilities') as fhr: if 'control_d' not in fhr.read(): # Tested on CentOS 5.5 / 2.6.18-194.3.1.el5xen grains['virtual_subtype'] = 'Xen PV DomU' else: # Shouldn't get to this, but just in case grains['virtual_subtype'] = 'Xen Dom0' # Tested on Fedora 10 / 2.6.27.30-170.2.82 with xen # Tested on Fedora 15 / 2.6.41.4-1 without running xen elif isdir('/sys/bus/xen'): if 'xen:' in __salt__['cmd.run']('dmesg').lower(): grains['virtual_subtype'] = 'Xen PV DomU' elif os.path.isfile('/sys/bus/xen/drivers/xenconsole'): # An actual DomU will have the xenconsole driver grains['virtual_subtype'] = 'Xen PV DomU' # If a Dom0 or DomU was detected, obviously this is xen if 'dom' in grains.get('virtual_subtype', '').lower(): grains['virtual'] = 'xen' # Check container type after hypervisors, to avoid variable overwrite on containers running in virtual environment. if os.path.isfile('/proc/1/cgroup'): try: with salt.utils.files.fopen('/proc/1/cgroup', 'r') as fhr: fhr_contents = fhr.read() if ':/lxc/' in fhr_contents: grains['virtual_subtype'] = 'LXC' elif ':/kubepods/' in fhr_contents: grains['virtual_subtype'] = 'kubernetes' elif ':/libpod_parent/' in fhr_contents: grains['virtual_subtype'] = 'libpod' else: if any(x in fhr_contents for x in (':/system.slice/docker', ':/docker/', ':/docker-ce/')): grains['virtual_subtype'] = 'Docker' except IOError: pass if os.path.isfile('/proc/cpuinfo'): with salt.utils.files.fopen('/proc/cpuinfo', 'r') as fhr: if 'QEMU Virtual CPU' in fhr.read(): grains['virtual'] = 'kvm' if os.path.isfile('/sys/devices/virtual/dmi/id/product_name'): try: with salt.utils.files.fopen('/sys/devices/virtual/dmi/id/product_name', 'r') as fhr: output = salt.utils.stringutils.to_unicode(fhr.read(), errors='replace') if 'VirtualBox' in output: grains['virtual'] = 'VirtualBox' elif 'RHEV Hypervisor' in output: grains['virtual'] = 'kvm' grains['virtual_subtype'] = 'rhev' elif 'oVirt Node' in output: grains['virtual'] = 'kvm' grains['virtual_subtype'] = 'ovirt' elif 'Google' in output: grains['virtual'] = 'gce' elif 'BHYVE' in output: grains['virtual'] = 'bhyve' except IOError: pass elif osdata['kernel'] == 'FreeBSD': kenv = salt.utils.path.which('kenv') if kenv: product = __salt__['cmd.run']( '{0} smbios.system.product'.format(kenv) ) maker = __salt__['cmd.run']( '{0} smbios.system.maker'.format(kenv) ) if product.startswith('VMware'): grains['virtual'] = 'VMware' if product.startswith('VirtualBox'): grains['virtual'] = 'VirtualBox' if maker.startswith('Xen'): grains['virtual_subtype'] = '{0} {1}'.format(maker, product) grains['virtual'] = 'xen' if maker.startswith('Microsoft') and product.startswith('Virtual'): grains['virtual'] = 'VirtualPC' if maker.startswith('OpenStack'): grains['virtual'] = 'OpenStack' if maker.startswith('Bochs'): grains['virtual'] = 'kvm' if sysctl: hv_vendor = __salt__['cmd.run']('{0} hw.hv_vendor'.format(sysctl)) model = __salt__['cmd.run']('{0} hw.model'.format(sysctl)) jail = __salt__['cmd.run']( '{0} -n security.jail.jailed'.format(sysctl) ) if 'bhyve' in hv_vendor: grains['virtual'] = 'bhyve' if jail == '1': grains['virtual_subtype'] = 'jail' if 'QEMU Virtual CPU' in model: grains['virtual'] = 'kvm' elif osdata['kernel'] == 'OpenBSD': if 'manufacturer' in osdata: if osdata['manufacturer'] in ['QEMU', 'Red Hat', 'Joyent']: grains['virtual'] = 'kvm' if osdata['manufacturer'] == 'OpenBSD': grains['virtual'] = 'vmm' elif osdata['kernel'] == 'SunOS': if grains['virtual'] == 'LDOM': roles = [] for role in ('control', 'io', 'root', 'service'): subtype_cmd = '{0} -c current get -H -o value {1}-role'.format(cmd, role) ret = __salt__['cmd.run_all']('{0}'.format(subtype_cmd)) if ret['stdout'] == 'true': roles.append(role) if roles: grains['virtual_subtype'] = roles else: # Check if it's a "regular" zone. (i.e. Solaris 10/11 zone) zonename = salt.utils.path.which('zonename') if zonename: zone = __salt__['cmd.run']('{0}'.format(zonename)) if zone != 'global': grains['virtual'] = 'zone' # Check if it's a branded zone (i.e. Solaris 8/9 zone) if isdir('/.SUNWnative'): grains['virtual'] = 'zone' elif osdata['kernel'] == 'NetBSD': if sysctl: if 'QEMU Virtual CPU' in __salt__['cmd.run']( '{0} -n machdep.cpu_brand'.format(sysctl)): grains['virtual'] = 'kvm' elif 'invalid' not in __salt__['cmd.run']( '{0} -n machdep.xen.suspend'.format(sysctl)): grains['virtual'] = 'Xen PV DomU' elif 'VMware' in __salt__['cmd.run']( '{0} -n machdep.dmi.system-vendor'.format(sysctl)): grains['virtual'] = 'VMware' # NetBSD has Xen dom0 support elif __salt__['cmd.run']( '{0} -n machdep.idle-mechanism'.format(sysctl)) == 'xen': if os.path.isfile('/var/run/xenconsoled.pid'): grains['virtual_subtype'] = 'Xen Dom0' for command in failed_commands: log.info( "Although '%s' was found in path, the current user " 'cannot execute it. Grains output might not be ' 'accurate.', command ) return grains def _virtual_hv(osdata): ''' Returns detailed hypervisor information from sysfs Currently this seems to be used only by Xen ''' grains = {} # Bail early if we're not running on Xen try: if 'xen' not in osdata['virtual']: return grains except KeyError: return grains # Try to get the exact hypervisor version from sysfs try: version = {} for fn in ('major', 'minor', 'extra'): with salt.utils.files.fopen('/sys/hypervisor/version/{}'.format(fn), 'r') as fhr: version[fn] = salt.utils.stringutils.to_unicode(fhr.read().strip()) grains['virtual_hv_version'] = '{}.{}{}'.format(version['major'], version['minor'], version['extra']) grains['virtual_hv_version_info'] = [version['major'], version['minor'], version['extra']] except (IOError, OSError, KeyError): pass # Try to read and decode the supported feature set of the hypervisor # Based on https://github.com/brendangregg/Misc/blob/master/xen/xen-features.py # Table data from include/xen/interface/features.h xen_feature_table = {0: 'writable_page_tables', 1: 'writable_descriptor_tables', 2: 'auto_translated_physmap', 3: 'supervisor_mode_kernel', 4: 'pae_pgdir_above_4gb', 5: 'mmu_pt_update_preserve_ad', 7: 'gnttab_map_avail_bits', 8: 'hvm_callback_vector', 9: 'hvm_safe_pvclock', 10: 'hvm_pirqs', 11: 'dom0', 12: 'grant_map_identity', 13: 'memory_op_vnode_supported', 14: 'ARM_SMCCC_supported'} try: with salt.utils.files.fopen('/sys/hypervisor/properties/features', 'r') as fhr: features = salt.utils.stringutils.to_unicode(fhr.read().strip()) enabled_features = [] for bit, feat in six.iteritems(xen_feature_table): if int(features, 16) & (1 << bit): enabled_features.append(feat) grains['virtual_hv_features'] = features grains['virtual_hv_features_list'] = enabled_features except (IOError, OSError, KeyError): pass return grains def _ps(osdata): ''' Return the ps grain ''' grains = {} bsd_choices = ('FreeBSD', 'NetBSD', 'OpenBSD', 'MacOS') if osdata['os'] in bsd_choices: grains['ps'] = 'ps auxwww' elif osdata['os_family'] == 'Solaris': grains['ps'] = '/usr/ucb/ps auxwww' elif osdata['os'] == 'Windows': grains['ps'] = 'tasklist.exe' elif osdata.get('virtual', '') == 'openvzhn': grains['ps'] = ( 'ps -fH -p $(grep -l \"^envID:[[:space:]]*0\\$\" ' '/proc/[0-9]*/status | sed -e \"s=/proc/\\([0-9]*\\)/.*=\\1=\") ' '| awk \'{ $7=\"\"; print }\'' ) elif osdata['os_family'] == 'AIX': grains['ps'] = '/usr/bin/ps auxww' elif osdata['os_family'] == 'NILinuxRT': grains['ps'] = 'ps -o user,pid,ppid,tty,time,comm' else: grains['ps'] = 'ps -efHww' return grains def _clean_value(key, val): ''' Clean out well-known bogus values. If it isn't clean (for example has value 'None'), return None. Otherwise, return the original value. NOTE: This logic also exists in the smbios module. This function is for use when not using smbios to retrieve the value. ''' if (val is None or not val or re.match('none', val, flags=re.IGNORECASE)): return None elif 'uuid' in key: # Try each version (1-5) of RFC4122 to check if it's actually a UUID for uuidver in range(1, 5): try: uuid.UUID(val, version=uuidver) return val except ValueError: continue log.trace('HW %s value %s is an invalid UUID', key, val.replace('\n', ' ')) return None elif re.search('serial|part|version', key): # 'To be filled by O.E.M. # 'Not applicable' etc. # 'Not specified' etc. # 0000000, 1234567 etc. # begone! if (re.match(r'^[0]+$', val) or re.match(r'[0]?1234567[8]?[9]?[0]?', val) or re.search(r'sernum|part[_-]?number|specified|filled|applicable', val, flags=re.IGNORECASE)): return None elif re.search('asset|manufacturer', key): # AssetTag0. Manufacturer04. Begone. if re.search(r'manufacturer|to be filled|available|asset|^no(ne|t)', val, flags=re.IGNORECASE): return None else: # map unspecified, undefined, unknown & whatever to None if (re.search(r'to be filled', val, flags=re.IGNORECASE) or re.search(r'un(known|specified)|no(t|ne)? (asset|provided|defined|available|present|specified)', val, flags=re.IGNORECASE)): return None return val def _windows_platform_data(): ''' Use the platform module for as much as we can. ''' # Provides: # kernelrelease # kernelversion # osversion # osrelease # osservicepack # osmanufacturer # manufacturer # productname # biosversion # serialnumber # osfullname # timezone # windowsdomain # windowsdomaintype # motherboard.productname # motherboard.serialnumber # virtual if not HAS_WMI: return {} with salt.utils.winapi.Com(): wmi_c = wmi.WMI() # http://msdn.microsoft.com/en-us/library/windows/desktop/aa394102%28v=vs.85%29.aspx systeminfo = wmi_c.Win32_ComputerSystem()[0] # https://msdn.microsoft.com/en-us/library/aa394239(v=vs.85).aspx osinfo = wmi_c.Win32_OperatingSystem()[0] # http://msdn.microsoft.com/en-us/library/windows/desktop/aa394077(v=vs.85).aspx biosinfo = wmi_c.Win32_BIOS()[0] # http://msdn.microsoft.com/en-us/library/windows/desktop/aa394498(v=vs.85).aspx timeinfo = wmi_c.Win32_TimeZone()[0] # http://msdn.microsoft.com/en-us/library/windows/desktop/aa394072(v=vs.85).aspx motherboard = {'product': None, 'serial': None} try: motherboardinfo = wmi_c.Win32_BaseBoard()[0] motherboard['product'] = motherboardinfo.Product motherboard['serial'] = motherboardinfo.SerialNumber except IndexError: log.debug('Motherboard info not available on this system') os_release = platform.release() kernel_version = platform.version() info = salt.utils.win_osinfo.get_os_version_info() net_info = salt.utils.win_osinfo.get_join_info() service_pack = None if info['ServicePackMajor'] > 0: service_pack = ''.join(['SP', six.text_type(info['ServicePackMajor'])]) # This creates the osrelease grain based on the Windows Operating # System Product Name. As long as Microsoft maintains a similar format # this should be future proof version = 'Unknown' release = '' if 'Server' in osinfo.Caption: for item in osinfo.Caption.split(' '): # If it's all digits, then it's version if re.match(r'\d+', item): version = item # If it starts with R and then numbers, it's the release # ie: R2 if re.match(r'^R\d+$', item): release = item os_release = '{0}Server{1}'.format(version, release) else: for item in osinfo.Caption.split(' '): # If it's a number, decimal number, Thin or Vista, then it's the # version if re.match(r'^(\d+(\.\d+)?)|Thin|Vista$', item): version = item os_release = version grains = { 'kernelrelease': _clean_value('kernelrelease', osinfo.Version), 'kernelversion': _clean_value('kernelversion', kernel_version), 'osversion': _clean_value('osversion', osinfo.Version), 'osrelease': _clean_value('osrelease', os_release), 'osservicepack': _clean_value('osservicepack', service_pack), 'osmanufacturer': _clean_value('osmanufacturer', osinfo.Manufacturer), 'manufacturer': _clean_value('manufacturer', systeminfo.Manufacturer), 'productname': _clean_value('productname', systeminfo.Model), # bios name had a bunch of whitespace appended to it in my testing # 'PhoenixBIOS 4.0 Release 6.0 ' 'biosversion': _clean_value('biosversion', biosinfo.Name.strip()), 'serialnumber': _clean_value('serialnumber', biosinfo.SerialNumber), 'osfullname': _clean_value('osfullname', osinfo.Caption), 'timezone': _clean_value('timezone', timeinfo.Description), 'windowsdomain': _clean_value('windowsdomain', net_info['Domain']), 'windowsdomaintype': _clean_value('windowsdomaintype', net_info['DomainType']), 'motherboard': { 'productname': _clean_value('motherboard.productname', motherboard['product']), 'serialnumber': _clean_value('motherboard.serialnumber', motherboard['serial']), } } # test for virtualized environments # I only had VMware available so the rest are unvalidated if 'VRTUAL' in biosinfo.Version: # (not a typo) grains['virtual'] = 'HyperV' elif 'A M I' in biosinfo.Version: grains['virtual'] = 'VirtualPC' elif 'VMware' in systeminfo.Model: grains['virtual'] = 'VMware' elif 'VirtualBox' in systeminfo.Model: grains['virtual'] = 'VirtualBox' elif 'Xen' in biosinfo.Version: grains['virtual'] = 'Xen' if 'HVM domU' in systeminfo.Model: grains['virtual_subtype'] = 'HVM domU' elif 'OpenStack' in systeminfo.Model: grains['virtual'] = 'OpenStack' return grains def _osx_platform_data(): ''' Additional data for macOS systems Returns: A dictionary containing values for the following: - model_name - boot_rom_version - smc_version - system_serialnumber ''' cmd = 'system_profiler SPHardwareDataType' hardware = __salt__['cmd.run'](cmd) grains = {} for line in hardware.splitlines(): field_name, _, field_val = line.partition(': ') if field_name.strip() == "Model Name": key = 'model_name' grains[key] = _clean_value(key, field_val) if field_name.strip() == "Boot ROM Version": key = 'boot_rom_version' grains[key] = _clean_value(key, field_val) if field_name.strip() == "SMC Version (system)": key = 'smc_version' grains[key] = _clean_value(key, field_val) if field_name.strip() == "Serial Number (system)": key = 'system_serialnumber' grains[key] = _clean_value(key, field_val) return grains def id_(): ''' Return the id ''' return {'id': __opts__.get('id', '')} _REPLACE_LINUX_RE = re.compile(r'\W(?:gnu/)?linux', re.IGNORECASE) # This maps (at most) the first ten characters (no spaces, lowercased) of # 'osfullname' to the 'os' grain that Salt traditionally uses. # Please see os_data() and _supported_dists. # If your system is not detecting properly it likely needs an entry here. _OS_NAME_MAP = { 'redhatente': 'RedHat', 'gentoobase': 'Gentoo', 'archarm': 'Arch ARM', 'arch': 'Arch', 'debian': 'Debian', 'raspbian': 'Raspbian', 'fedoraremi': 'Fedora', 'chapeau': 'Chapeau', 'korora': 'Korora', 'amazonami': 'Amazon', 'alt': 'ALT', 'enterprise': 'OEL', 'oracleserv': 'OEL', 'cloudserve': 'CloudLinux', 'cloudlinux': 'CloudLinux', 'pidora': 'Fedora', 'scientific': 'ScientificLinux', 'synology': 'Synology', 'nilrt': 'NILinuxRT', 'poky': 'Poky', 'manjaro': 'Manjaro', 'manjarolin': 'Manjaro', 'univention': 'Univention', 'antergos': 'Antergos', 'sles': 'SUSE', 'void': 'Void', 'slesexpand': 'RES', 'linuxmint': 'Mint', 'neon': 'KDE neon', } # Map the 'os' grain to the 'os_family' grain # These should always be capitalized entries as the lookup comes # post-_OS_NAME_MAP. If your system is having trouble with detection, please # make sure that the 'os' grain is capitalized and working correctly first. _OS_FAMILY_MAP = { 'Ubuntu': 'Debian', 'Fedora': 'RedHat', 'Chapeau': 'RedHat', 'Korora': 'RedHat', 'FedBerry': 'RedHat', 'CentOS': 'RedHat', 'GoOSe': 'RedHat', 'Scientific': 'RedHat', 'Amazon': 'RedHat', 'CloudLinux': 'RedHat', 'OVS': 'RedHat', 'OEL': 'RedHat', 'XCP': 'RedHat', 'XCP-ng': 'RedHat', 'XenServer': 'RedHat', 'RES': 'RedHat', 'Sangoma': 'RedHat', 'Mandrake': 'Mandriva', 'ESXi': 'VMware', 'Mint': 'Debian', 'VMwareESX': 'VMware', 'Bluewhite64': 'Bluewhite', 'Slamd64': 'Slackware', 'SLES': 'Suse', 'SUSE Enterprise Server': 'Suse', 'SUSE Enterprise Server': 'Suse', 'SLED': 'Suse', 'openSUSE': 'Suse', 'SUSE': 'Suse', 'openSUSE Leap': 'Suse', 'openSUSE Tumbleweed': 'Suse', 'SLES_SAP': 'Suse', 'Solaris': 'Solaris', 'SmartOS': 'Solaris', 'OmniOS': 'Solaris', 'OpenIndiana Development': 'Solaris', 'OpenIndiana': 'Solaris', 'OpenSolaris Development': 'Solaris', 'OpenSolaris': 'Solaris', 'Oracle Solaris': 'Solaris', 'Arch ARM': 'Arch', 'Manjaro': 'Arch', 'Antergos': 'Arch', 'ALT': 'RedHat', 'Trisquel': 'Debian', 'GCEL': 'Debian', 'Linaro': 'Debian', 'elementary OS': 'Debian', 'elementary': 'Debian', 'Univention': 'Debian', 'ScientificLinux': 'RedHat', 'Raspbian': 'Debian', 'Devuan': 'Debian', 'antiX': 'Debian', 'Kali': 'Debian', 'neon': 'Debian', 'Cumulus': 'Debian', 'Deepin': 'Debian', 'NILinuxRT': 'NILinuxRT', 'KDE neon': 'Debian', 'Void': 'Void', 'IDMS': 'Debian', 'Funtoo': 'Gentoo', 'AIX': 'AIX', 'TurnKey': 'Debian', } # Matches any possible format: # DISTRIB_ID="Ubuntu" # DISTRIB_ID='Mageia' # DISTRIB_ID=Fedora # DISTRIB_RELEASE='10.10' # DISTRIB_CODENAME='squeeze' # DISTRIB_DESCRIPTION='Ubuntu 10.10' _LSB_REGEX = re.compile(( '^(DISTRIB_(?:ID|RELEASE|CODENAME|DESCRIPTION))=(?:\'|")?' '([\\w\\s\\.\\-_]+)(?:\'|")?' )) def _linux_bin_exists(binary): ''' Does a binary exist in linux (depends on which, type, or whereis) ''' for search_cmd in ('which', 'type -ap'): try: return __salt__['cmd.retcode']( '{0} {1}'.format(search_cmd, binary) ) == 0 except salt.exceptions.CommandExecutionError: pass try: return len(__salt__['cmd.run_all']( 'whereis -b {0}'.format(binary) )['stdout'].split()) > 1 except salt.exceptions.CommandExecutionError: return False def _get_interfaces(): ''' Provide a dict of the connected interfaces and their ip addresses ''' global _INTERFACES if not _INTERFACES: _INTERFACES = salt.utils.network.interfaces() return _INTERFACES def _parse_lsb_release(): ret = {} try: log.trace('Attempting to parse /etc/lsb-release') with salt.utils.files.fopen('/etc/lsb-release') as ifile: for line in ifile: try: key, value = _LSB_REGEX.match(line.rstrip('\n')).groups()[:2] except AttributeError: pass else: # Adds lsb_distrib_{id,release,codename,description} ret['lsb_{0}'.format(key.lower())] = value.rstrip() except (IOError, OSError) as exc: log.trace('Failed to parse /etc/lsb-release: %s', exc) return ret def _parse_os_release(*os_release_files): ''' Parse os-release and return a parameter dictionary See http://www.freedesktop.org/software/systemd/man/os-release.html for specification of the file format. ''' ret = {} for filename in os_release_files: try: with salt.utils.files.fopen(filename) as ifile: regex = re.compile('^([\\w]+)=(?:\'|")?(.*?)(?:\'|")?$') for line in ifile: match = regex.match(line.strip()) if match: # Shell special characters ("$", quotes, backslash, # backtick) are escaped with backslashes ret[match.group(1)] = re.sub( r'\\([$"\'\\`])', r'\1', match.group(2) ) break except (IOError, OSError): pass return ret def _parse_cpe_name(cpe): ''' Parse CPE_NAME data from the os-release Info: https://csrc.nist.gov/projects/security-content-automation-protocol/scap-specifications/cpe :param cpe: :return: ''' part = { 'o': 'operating system', 'h': 'hardware', 'a': 'application', } ret = {} cpe = (cpe or '').split(':') if len(cpe) > 4 and cpe[0] == 'cpe': if cpe[1].startswith('/'): # WFN to URI ret['vendor'], ret['product'], ret['version'] = cpe[2:5] ret['phase'] = cpe[5] if len(cpe) > 5 else None ret['part'] = part.get(cpe[1][1:]) elif len(cpe) == 13 and cpe[1] == '2.3': # WFN to a string ret['vendor'], ret['product'], ret['version'], ret['phase'] = [x if x != '*' else None for x in cpe[3:7]] ret['part'] = part.get(cpe[2]) return ret def os_data(): ''' Return grains pertaining to the operating system ''' grains = { 'num_gpus': 0, 'gpus': [], } # Windows Server 2008 64-bit # ('Windows', 'MINIONNAME', '2008ServerR2', '6.1.7601', 'AMD64', # 'Intel64 Fam ily 6 Model 23 Stepping 6, GenuineIntel') # Ubuntu 10.04 # ('Linux', 'MINIONNAME', '2.6.32-38-server', # '#83-Ubuntu SMP Wed Jan 4 11:26:59 UTC 2012', 'x86_64', '') # pylint: disable=unpacking-non-sequence (grains['kernel'], grains['nodename'], grains['kernelrelease'], grains['kernelversion'], grains['cpuarch'], _) = platform.uname() # pylint: enable=unpacking-non-sequence if salt.utils.platform.is_proxy(): grains['kernel'] = 'proxy' grains['kernelrelease'] = 'proxy' grains['kernelversion'] = 'proxy' grains['osrelease'] = 'proxy' grains['os'] = 'proxy' grains['os_family'] = 'proxy' grains['osfullname'] = 'proxy' elif salt.utils.platform.is_windows(): grains['os'] = 'Windows' grains['os_family'] = 'Windows' grains.update(_memdata(grains)) grains.update(_windows_platform_data()) grains.update(_windows_cpudata()) grains.update(_windows_virtual(grains)) grains.update(_ps(grains)) if 'Server' in grains['osrelease']: osrelease_info = grains['osrelease'].split('Server', 1) osrelease_info[1] = osrelease_info[1].lstrip('R') else: osrelease_info = grains['osrelease'].split('.') for idx, value in enumerate(osrelease_info): if not value.isdigit(): continue osrelease_info[idx] = int(value) grains['osrelease_info'] = tuple(osrelease_info) grains['osfinger'] = '{os}-{ver}'.format( os=grains['os'], ver=grains['osrelease']) grains['init'] = 'Windows' return grains elif salt.utils.platform.is_linux(): # Add SELinux grain, if you have it if _linux_bin_exists('selinuxenabled'): log.trace('Adding selinux grains') grains['selinux'] = {} grains['selinux']['enabled'] = __salt__['cmd.retcode']( 'selinuxenabled' ) == 0 if _linux_bin_exists('getenforce'): grains['selinux']['enforced'] = __salt__['cmd.run']( 'getenforce' ).strip() # Add systemd grain, if you have it if _linux_bin_exists('systemctl') and _linux_bin_exists('localectl'): log.trace('Adding systemd grains') grains['systemd'] = {} systemd_info = __salt__['cmd.run']( 'systemctl --version' ).splitlines() grains['systemd']['version'] = systemd_info[0].split()[1] grains['systemd']['features'] = systemd_info[1] # Add init grain grains['init'] = 'unknown' log.trace('Adding init grain') try: os.stat('/run/systemd/system') grains['init'] = 'systemd' except (OSError, IOError): try: with salt.utils.files.fopen('/proc/1/cmdline') as fhr: init_cmdline = fhr.read().replace('\x00', ' ').split() except (IOError, OSError): pass else: try: init_bin = salt.utils.path.which(init_cmdline[0]) except IndexError: # Emtpy init_cmdline init_bin = None log.warning('Unable to fetch data from /proc/1/cmdline') if init_bin is not None and init_bin.endswith('bin/init'): supported_inits = (b'upstart', b'sysvinit', b'systemd') edge_len = max(len(x) for x in supported_inits) - 1 try: buf_size = __opts__['file_buffer_size'] except KeyError: # Default to the value of file_buffer_size for the minion buf_size = 262144 try: with salt.utils.files.fopen(init_bin, 'rb') as fp_: edge = b'' buf = fp_.read(buf_size).lower() while buf: buf = edge + buf for item in supported_inits: if item in buf: if six.PY3: item = item.decode('utf-8') grains['init'] = item buf = b'' break edge = buf[-edge_len:] buf = fp_.read(buf_size).lower() except (IOError, OSError) as exc: log.error( 'Unable to read from init_bin (%s): %s', init_bin, exc ) elif salt.utils.path.which('supervisord') in init_cmdline: grains['init'] = 'supervisord' elif salt.utils.path.which('dumb-init') in init_cmdline: # https://github.com/Yelp/dumb-init grains['init'] = 'dumb-init' elif salt.utils.path.which('tini') in init_cmdline: # https://github.com/krallin/tini grains['init'] = 'tini' elif init_cmdline == ['runit']: grains['init'] = 'runit' elif '/sbin/my_init' in init_cmdline: # Phusion Base docker container use runit for srv mgmt, but # my_init as pid1 grains['init'] = 'runit' else: log.debug( 'Could not determine init system from command line: (%s)', ' '.join(init_cmdline) ) # Add lsb grains on any distro with lsb-release. Note that this import # can fail on systems with lsb-release installed if the system package # does not install the python package for the python interpreter used by # Salt (i.e. python2 or python3) try: log.trace('Getting lsb_release distro information') import lsb_release # pylint: disable=import-error release = lsb_release.get_distro_information() for key, value in six.iteritems(release): key = key.lower() lsb_param = 'lsb_{0}{1}'.format( '' if key.startswith('distrib_') else 'distrib_', key ) grains[lsb_param] = value # Catch a NameError to workaround possible breakage in lsb_release # See https://github.com/saltstack/salt/issues/37867 except (ImportError, NameError): # if the python library isn't available, try to parse # /etc/lsb-release using regex log.trace('lsb_release python bindings not available') grains.update(_parse_lsb_release()) if grains.get('lsb_distrib_description', '').lower().startswith('antergos'): # Antergos incorrectly configures their /etc/lsb-release, # setting the DISTRIB_ID to "Arch". This causes the "os" grain # to be incorrectly set to "Arch". grains['osfullname'] = 'Antergos Linux' elif 'lsb_distrib_id' not in grains: log.trace( 'Failed to get lsb_distrib_id, trying to parse os-release' ) os_release = _parse_os_release('/etc/os-release', '/usr/lib/os-release') if os_release: if 'NAME' in os_release: grains['lsb_distrib_id'] = os_release['NAME'].strip() if 'VERSION_ID' in os_release: grains['lsb_distrib_release'] = os_release['VERSION_ID'] if 'VERSION_CODENAME' in os_release: grains['lsb_distrib_codename'] = os_release['VERSION_CODENAME'] elif 'PRETTY_NAME' in os_release: codename = os_release['PRETTY_NAME'] # https://github.com/saltstack/salt/issues/44108 if os_release['ID'] == 'debian': codename_match = re.search(r'\((\w+)\)$', codename) if codename_match: codename = codename_match.group(1) grains['lsb_distrib_codename'] = codename if 'CPE_NAME' in os_release: cpe = _parse_cpe_name(os_release['CPE_NAME']) if not cpe: log.error('Broken CPE_NAME format in /etc/os-release!') elif cpe.get('vendor', '').lower() in ['suse', 'opensuse']: grains['os'] = "SUSE" # openSUSE `osfullname` grain normalization if os_release.get("NAME") == "openSUSE Leap": grains['osfullname'] = "Leap" elif os_release.get("VERSION") == "Tumbleweed": grains['osfullname'] = os_release["VERSION"] # Override VERSION_ID, if CPE_NAME around if cpe.get('version') and cpe.get('vendor') == 'opensuse': # Keep VERSION_ID for SLES grains['lsb_distrib_release'] = cpe['version'] elif os.path.isfile('/etc/SuSE-release'): log.trace('Parsing distrib info from /etc/SuSE-release') grains['lsb_distrib_id'] = 'SUSE' version = '' patch = '' with salt.utils.files.fopen('/etc/SuSE-release') as fhr: for line in fhr: if 'enterprise' in line.lower(): grains['lsb_distrib_id'] = 'SLES' grains['lsb_distrib_codename'] = re.sub(r'\(.+\)', '', line).strip() elif 'version' in line.lower(): version = re.sub(r'[^0-9]', '', line) elif 'patchlevel' in line.lower(): patch = re.sub(r'[^0-9]', '', line) grains['lsb_distrib_release'] = version if patch: grains['lsb_distrib_release'] += '.' + patch patchstr = 'SP' + patch if grains['lsb_distrib_codename'] and patchstr not in grains['lsb_distrib_codename']: grains['lsb_distrib_codename'] += ' ' + patchstr if not grains.get('lsb_distrib_codename'): grains['lsb_distrib_codename'] = 'n.a' elif os.path.isfile('/etc/altlinux-release'): log.trace('Parsing distrib info from /etc/altlinux-release') # ALT Linux grains['lsb_distrib_id'] = 'altlinux' with salt.utils.files.fopen('/etc/altlinux-release') as ifile: # This file is symlinked to from: # /etc/fedora-release # /etc/redhat-release # /etc/system-release for line in ifile: # ALT Linux Sisyphus (unstable) comps = line.split() if comps[0] == 'ALT': grains['lsb_distrib_release'] = comps[2] grains['lsb_distrib_codename'] = \ comps[3].replace('(', '').replace(')', '') elif os.path.isfile('/etc/centos-release'): log.trace('Parsing distrib info from /etc/centos-release') # Maybe CentOS Linux; could also be SUSE Expanded Support. # SUSE ES has both, centos-release and redhat-release. if os.path.isfile('/etc/redhat-release'): with salt.utils.files.fopen('/etc/redhat-release') as ifile: for line in ifile: if "red hat enterprise linux server" in line.lower(): # This is a SUSE Expanded Support Rhel installation grains['lsb_distrib_id'] = 'RedHat' break grains.setdefault('lsb_distrib_id', 'CentOS') with salt.utils.files.fopen('/etc/centos-release') as ifile: for line in ifile: # Need to pull out the version and codename # in the case of custom content in /etc/centos-release find_release = re.compile(r'\d+\.\d+') find_codename = re.compile(r'(?<=\()(.*?)(?=\))') release = find_release.search(line) codename = find_codename.search(line) if release is not None: grains['lsb_distrib_release'] = release.group() if codename is not None: grains['lsb_distrib_codename'] = codename.group() elif os.path.isfile('/etc.defaults/VERSION') \ and os.path.isfile('/etc.defaults/synoinfo.conf'): grains['osfullname'] = 'Synology' log.trace( 'Parsing Synology distrib info from /etc/.defaults/VERSION' ) with salt.utils.files.fopen('/etc.defaults/VERSION', 'r') as fp_: synoinfo = {} for line in fp_: try: key, val = line.rstrip('\n').split('=') except ValueError: continue if key in ('majorversion', 'minorversion', 'buildnumber'): synoinfo[key] = val.strip('"') if len(synoinfo) != 3: log.warning( 'Unable to determine Synology version info. ' 'Please report this, as it is likely a bug.' ) else: grains['osrelease'] = ( '{majorversion}.{minorversion}-{buildnumber}' .format(**synoinfo) ) # Use the already intelligent platform module to get distro info # (though apparently it's not intelligent enough to strip quotes) log.trace( 'Getting OS name, release, and codename from ' 'distro.linux_distribution()' ) (osname, osrelease, oscodename) = \ [x.strip('"').strip("'") for x in linux_distribution(supported_dists=_supported_dists)] # Try to assign these three names based on the lsb info, they tend to # be more accurate than what python gets from /etc/DISTRO-release. # It's worth noting that Ubuntu has patched their Python distribution # so that linux_distribution() does the /etc/lsb-release parsing, but # we do it anyway here for the sake for full portability. if 'osfullname' not in grains: # If NI Linux RT distribution, set the grains['osfullname'] to 'nilrt' if grains.get('lsb_distrib_id', '').lower().startswith('nilrt'): grains['osfullname'] = 'nilrt' else: grains['osfullname'] = grains.get('lsb_distrib_id', osname).strip() if 'osrelease' not in grains: # NOTE: This is a workaround for CentOS 7 os-release bug # https://bugs.centos.org/view.php?id=8359 # /etc/os-release contains no minor distro release number so we fall back to parse # /etc/centos-release file instead. # Commit introducing this comment should be reverted after the upstream bug is released. if 'CentOS Linux 7' in grains.get('lsb_distrib_codename', ''): grains.pop('lsb_distrib_release', None) grains['osrelease'] = grains.get('lsb_distrib_release', osrelease).strip() grains['oscodename'] = grains.get('lsb_distrib_codename', '').strip() or oscodename if 'Red Hat' in grains['oscodename']: grains['oscodename'] = oscodename distroname = _REPLACE_LINUX_RE.sub('', grains['osfullname']).strip() # return the first ten characters with no spaces, lowercased shortname = distroname.replace(' ', '').lower()[:10] # this maps the long names from the /etc/DISTRO-release files to the # traditional short names that Salt has used. if 'os' not in grains: grains['os'] = _OS_NAME_MAP.get(shortname, distroname) grains.update(_linux_cpudata()) grains.update(_linux_gpu_data()) elif grains['kernel'] == 'SunOS': if salt.utils.platform.is_smartos(): # See https://github.com/joyent/smartos-live/issues/224 if HAS_UNAME: uname_v = os.uname()[3] # format: joyent_20161101T004406Z else: uname_v = os.name uname_v = uname_v[uname_v.index('_')+1:] grains['os'] = grains['osfullname'] = 'SmartOS' # store a parsed version of YYYY.MM.DD as osrelease grains['osrelease'] = ".".join([ uname_v.split('T')[0][0:4], uname_v.split('T')[0][4:6], uname_v.split('T')[0][6:8], ]) # store a untouched copy of the timestamp in osrelease_stamp grains['osrelease_stamp'] = uname_v elif os.path.isfile('/etc/release'): with salt.utils.files.fopen('/etc/release', 'r') as fp_: rel_data = fp_.read() try: release_re = re.compile( r'((?:Open|Oracle )?Solaris|OpenIndiana|OmniOS) (Development)?' r'\s*(\d+\.?\d*|v\d+)\s?[A-Z]*\s?(r\d+|\d+\/\d+|oi_\S+|snv_\S+)?' ) osname, development, osmajorrelease, osminorrelease = release_re.search(rel_data).groups() except AttributeError: # Set a blank osrelease grain and fallback to 'Solaris' # as the 'os' grain. grains['os'] = grains['osfullname'] = 'Solaris' grains['osrelease'] = '' else: if development is not None: osname = ' '.join((osname, development)) if HAS_UNAME: uname_v = os.uname()[3] else: uname_v = os.name grains['os'] = grains['osfullname'] = osname if osname in ['Oracle Solaris'] and uname_v.startswith(osmajorrelease): # Oracla Solars 11 and up have minor version in uname grains['osrelease'] = uname_v elif osname in ['OmniOS']: # OmniOS osrelease = [] osrelease.append(osmajorrelease[1:]) osrelease.append(osminorrelease[1:]) grains['osrelease'] = ".".join(osrelease) grains['osrelease_stamp'] = uname_v else: # Sun Solaris 10 and earlier/comparable osrelease = [] osrelease.append(osmajorrelease) if osminorrelease: osrelease.append(osminorrelease) grains['osrelease'] = ".".join(osrelease) grains['osrelease_stamp'] = uname_v grains.update(_sunos_cpudata()) elif grains['kernel'] == 'VMkernel': grains['os'] = 'ESXi' elif grains['kernel'] == 'Darwin': osrelease = __salt__['cmd.run']('sw_vers -productVersion') osname = __salt__['cmd.run']('sw_vers -productName') osbuild = __salt__['cmd.run']('sw_vers -buildVersion') grains['os'] = 'MacOS' grains['os_family'] = 'MacOS' grains['osfullname'] = "{0} {1}".format(osname, osrelease) grains['osrelease'] = osrelease grains['osbuild'] = osbuild grains['init'] = 'launchd' grains.update(_bsd_cpudata(grains)) grains.update(_osx_gpudata()) grains.update(_osx_platform_data()) elif grains['kernel'] == 'AIX': osrelease = __salt__['cmd.run']('oslevel') osrelease_techlevel = __salt__['cmd.run']('oslevel -r') osname = __salt__['cmd.run']('uname') grains['os'] = 'AIX' grains['osfullname'] = osname grains['osrelease'] = osrelease grains['osrelease_techlevel'] = osrelease_techlevel grains.update(_aix_cpudata()) else: grains['os'] = grains['kernel'] if grains['kernel'] == 'FreeBSD': try: grains['osrelease'] = __salt__['cmd.run']('freebsd-version -u').split('-')[0] except salt.exceptions.CommandExecutionError: # freebsd-version was introduced in 10.0. # derive osrelease from kernelversion prior to that grains['osrelease'] = grains['kernelrelease'].split('-')[0] grains.update(_bsd_cpudata(grains)) if grains['kernel'] in ('OpenBSD', 'NetBSD'): grains.update(_bsd_cpudata(grains)) grains['osrelease'] = grains['kernelrelease'].split('-')[0] if grains['kernel'] == 'NetBSD': grains.update(_netbsd_gpu_data()) if not grains['os']: grains['os'] = 'Unknown {0}'.format(grains['kernel']) grains['os_family'] = 'Unknown' else: # this assigns family names based on the os name # family defaults to the os name if not found grains['os_family'] = _OS_FAMILY_MAP.get(grains['os'], grains['os']) # Build the osarch grain. This grain will be used for platform-specific # considerations such as package management. Fall back to the CPU # architecture. if grains.get('os_family') == 'Debian': osarch = __salt__['cmd.run']('dpkg --print-architecture').strip() elif grains.get('os_family') in ['RedHat', 'Suse']: osarch = salt.utils.pkg.rpm.get_osarch() elif grains.get('os_family') in ('NILinuxRT', 'Poky'): archinfo = {} for line in __salt__['cmd.run']('opkg print-architecture').splitlines(): if line.startswith('arch'): _, arch, priority = line.split() archinfo[arch.strip()] = int(priority.strip()) # Return osarch in priority order (higher to lower) osarch = sorted(archinfo, key=archinfo.get, reverse=True) else: osarch = grains['cpuarch'] grains['osarch'] = osarch grains.update(_memdata(grains)) # Get the hardware and bios data grains.update(_hw_data(grains)) # Load the virtual machine info grains.update(_virtual(grains)) grains.update(_virtual_hv(grains)) grains.update(_ps(grains)) if grains.get('osrelease', ''): osrelease_info = grains['osrelease'].split('.') for idx, value in enumerate(osrelease_info): if not value.isdigit(): continue osrelease_info[idx] = int(value) grains['osrelease_info'] = tuple(osrelease_info) try: grains['osmajorrelease'] = int(grains['osrelease_info'][0]) except (IndexError, TypeError, ValueError): log.debug( 'Unable to derive osmajorrelease from osrelease_info \'%s\'. ' 'The osmajorrelease grain will not be set.', grains['osrelease_info'] ) os_name = grains['os' if grains.get('os') in ( 'Debian', 'FreeBSD', 'OpenBSD', 'NetBSD', 'Mac', 'Raspbian') else 'osfullname'] grains['osfinger'] = '{0}-{1}'.format( os_name, grains['osrelease'] if os_name in ('Ubuntu',) else grains['osrelease_info'][0]) return grains def locale_info(): ''' Provides defaultlanguage defaultencoding ''' grains = {} grains['locale_info'] = {} if salt.utils.platform.is_proxy(): return grains try: ( grains['locale_info']['defaultlanguage'], grains['locale_info']['defaultencoding'] ) = locale.getdefaultlocale() except Exception: # locale.getdefaultlocale can ValueError!! Catch anything else it # might do, per #2205 grains['locale_info']['defaultlanguage'] = 'unknown' grains['locale_info']['defaultencoding'] = 'unknown' grains['locale_info']['detectedencoding'] = __salt_system_encoding__ if _DATEUTIL_TZ: grains['locale_info']['timezone'] = datetime.datetime.now(dateutil.tz.tzlocal()).tzname() return grains def hostname(): ''' Return fqdn, hostname, domainname ''' # This is going to need some work # Provides: # fqdn # host # localhost # domain global __FQDN__ grains = {} if salt.utils.platform.is_proxy(): return grains grains['localhost'] = socket.gethostname() if __FQDN__ is None: __FQDN__ = salt.utils.network.get_fqhostname() # On some distros (notably FreeBSD) if there is no hostname set # salt.utils.network.get_fqhostname() will return None. # In this case we punt and log a message at error level, but force the # hostname and domain to be localhost.localdomain # Otherwise we would stacktrace below if __FQDN__ is None: # still! log.error('Having trouble getting a hostname. Does this machine have its hostname and domain set properly?') __FQDN__ = 'localhost.localdomain' grains['fqdn'] = __FQDN__ (grains['host'], grains['domain']) = grains['fqdn'].partition('.')[::2] return grains def append_domain(): ''' Return append_domain if set ''' grain = {} if salt.utils.platform.is_proxy(): return grain if 'append_domain' in __opts__: grain['append_domain'] = __opts__['append_domain'] return grain def fqdns(): ''' Return all known FQDNs for the system by enumerating all interfaces and then trying to reverse resolve them (excluding 'lo' interface). ''' # Provides: # fqdns grains = {} fqdns = set() addresses = salt.utils.network.ip_addrs(include_loopback=False, interface_data=_get_interfaces()) addresses.extend(salt.utils.network.ip_addrs6(include_loopback=False, interface_data=_get_interfaces())) err_message = 'Exception during resolving address: %s' for ip in addresses: try: name, aliaslist, addresslist = socket.gethostbyaddr(ip) fqdns.update([socket.getfqdn(name)] + [als for als in aliaslist if salt.utils.network.is_fqdn(als)]) except socket.herror as err: if err.errno == 0: # No FQDN for this IP address, so we don't need to know this all the time. log.debug("Unable to resolve address %s: %s", ip, err) else: log.error(err_message, err) except (socket.error, socket.gaierror, socket.timeout) as err: log.error(err_message, err) return {"fqdns": sorted(list(fqdns))} def ip_fqdn(): ''' Return ip address and FQDN grains ''' if salt.utils.platform.is_proxy(): return {} ret = {} ret['ipv4'] = salt.utils.network.ip_addrs(include_loopback=True) ret['ipv6'] = salt.utils.network.ip_addrs6(include_loopback=True) _fqdn = hostname()['fqdn'] for socket_type, ipv_num in ((socket.AF_INET, '4'), (socket.AF_INET6, '6')): key = 'fqdn_ip' + ipv_num if not ret['ipv' + ipv_num]: ret[key] = [] else: try: start_time = datetime.datetime.utcnow() info = socket.getaddrinfo(_fqdn, None, socket_type) ret[key] = list(set(item[4][0] for item in info)) except socket.error: timediff = datetime.datetime.utcnow() - start_time if timediff.seconds > 5 and __opts__['__role'] == 'master': log.warning( 'Unable to find IPv%s record for "%s" causing a %s ' 'second timeout when rendering grains. Set the dns or ' '/etc/hosts for IPv%s to clear this.', ipv_num, _fqdn, timediff, ipv_num ) ret[key] = [] return ret def ip_interfaces(): ''' Provide a dict of the connected interfaces and their ip addresses The addresses will be passed as a list for each interface ''' # Provides: # ip_interfaces if salt.utils.platform.is_proxy(): return {} ret = {} ifaces = _get_interfaces() for face in ifaces: iface_ips = [] for inet in ifaces[face].get('inet', []): if 'address' in inet: iface_ips.append(inet['address']) for inet in ifaces[face].get('inet6', []): if 'address' in inet: iface_ips.append(inet['address']) for secondary in ifaces[face].get('secondary', []): if 'address' in secondary: iface_ips.append(secondary['address']) ret[face] = iface_ips return {'ip_interfaces': ret} def ip4_interfaces(): ''' Provide a dict of the connected interfaces and their ip4 addresses The addresses will be passed as a list for each interface ''' # Provides: # ip_interfaces if salt.utils.platform.is_proxy(): return {} ret = {} ifaces = _get_interfaces() for face in ifaces: iface_ips = [] for inet in ifaces[face].get('inet', []): if 'address' in inet: iface_ips.append(inet['address']) for secondary in ifaces[face].get('secondary', []): if 'address' in secondary: iface_ips.append(secondary['address']) ret[face] = iface_ips return {'ip4_interfaces': ret} def ip6_interfaces(): ''' Provide a dict of the connected interfaces and their ip6 addresses The addresses will be passed as a list for each interface ''' # Provides: # ip_interfaces if salt.utils.platform.is_proxy(): return {} ret = {} ifaces = _get_interfaces() for face in ifaces: iface_ips = [] for inet in ifaces[face].get('inet6', []): if 'address' in inet: iface_ips.append(inet['address']) for secondary in ifaces[face].get('secondary', []): if 'address' in secondary: iface_ips.append(secondary['address']) ret[face] = iface_ips return {'ip6_interfaces': ret} def hwaddr_interfaces(): ''' Provide a dict of the connected interfaces and their hw addresses (Mac Address) ''' # Provides: # hwaddr_interfaces ret = {} ifaces = _get_interfaces() for face in ifaces: if 'hwaddr' in ifaces[face]: ret[face] = ifaces[face]['hwaddr'] return {'hwaddr_interfaces': ret} def dns(): ''' Parse the resolver configuration file .. versionadded:: 2016.3.0 ''' # Provides: # dns if salt.utils.platform.is_windows() or 'proxyminion' in __opts__: return {} resolv = salt.utils.dns.parse_resolv() for key in ('nameservers', 'ip4_nameservers', 'ip6_nameservers', 'sortlist'): if key in resolv: resolv[key] = [six.text_type(i) for i in resolv[key]] return {'dns': resolv} if resolv else {} def get_machine_id(): ''' Provide the machine-id for machine/virtualization combination ''' # Provides: # machine-id if platform.system() == 'AIX': return _aix_get_machine_id() locations = ['/etc/machine-id', '/var/lib/dbus/machine-id'] existing_locations = [loc for loc in locations if os.path.exists(loc)] if not existing_locations: return {} else: with salt.utils.files.fopen(existing_locations[0]) as machineid: return {'machine_id': machineid.read().strip()} def cwd(): ''' Current working directory ''' return {'cwd': os.getcwd()} def path(): ''' Return the path ''' # Provides: # path return {'path': os.environ.get('PATH', '').strip()} def pythonversion(): ''' Return the Python version ''' # Provides: # pythonversion return {'pythonversion': list(sys.version_info)} def pythonpath(): ''' Return the Python path ''' # Provides: # pythonpath return {'pythonpath': sys.path} def pythonexecutable(): ''' Return the python executable in use ''' # Provides: # pythonexecutable return {'pythonexecutable': sys.executable} def saltversion(): ''' Return the version of salt ''' # Provides: # saltversion from salt.version import __version__ return {'saltversion': __version__} def zmqversion(): ''' Return the zeromq version ''' # Provides: # zmqversion try: import zmq return {'zmqversion': zmq.zmq_version()} # pylint: disable=no-member except ImportError: return {} def saltversioninfo(): ''' Return the version_info of salt .. versionadded:: 0.17.0 ''' # Provides: # saltversioninfo from salt.version import __version_info__ return {'saltversioninfo': list(__version_info__)} def _hw_data(osdata): ''' Get system specific hardware data from dmidecode Provides biosversion productname manufacturer serialnumber biosreleasedate uuid .. versionadded:: 0.9.5 ''' if salt.utils.platform.is_proxy(): return {} grains = {} if osdata['kernel'] == 'Linux' and os.path.exists('/sys/class/dmi/id'): # On many Linux distributions basic firmware information is available via sysfs # requires CONFIG_DMIID to be enabled in the Linux kernel configuration sysfs_firmware_info = { 'biosversion': 'bios_version', 'productname': 'product_name', 'manufacturer': 'sys_vendor', 'biosreleasedate': 'bios_date', 'uuid': 'product_uuid', 'serialnumber': 'product_serial' } for key, fw_file in sysfs_firmware_info.items(): contents_file = os.path.join('/sys/class/dmi/id', fw_file) if os.path.exists(contents_file): try: with salt.utils.files.fopen(contents_file, 'r') as ifile: grains[key] = salt.utils.stringutils.to_unicode(ifile.read().strip(), errors='replace') if key == 'uuid': grains['uuid'] = grains['uuid'].lower() except (IOError, OSError) as err: # PermissionError is new to Python 3, but corresponds to the EACESS and # EPERM error numbers. Use those instead here for PY2 compatibility. if err.errno == EACCES or err.errno == EPERM: # Skip the grain if non-root user has no access to the file. pass elif salt.utils.path.which_bin(['dmidecode', 'smbios']) is not None and not ( salt.utils.platform.is_smartos() or ( # SunOS on SPARC - 'smbios: failed to load SMBIOS: System does not export an SMBIOS table' osdata['kernel'] == 'SunOS' and osdata['cpuarch'].startswith('sparc') )): # On SmartOS (possibly SunOS also) smbios only works in the global zone # smbios is also not compatible with linux's smbios (smbios -s = print summarized) grains = { 'biosversion': __salt__['smbios.get']('bios-version'), 'productname': __salt__['smbios.get']('system-product-name'), 'manufacturer': __salt__['smbios.get']('system-manufacturer'), 'biosreleasedate': __salt__['smbios.get']('bios-release-date'), 'uuid': __salt__['smbios.get']('system-uuid') } grains = dict([(key, val) for key, val in grains.items() if val is not None]) uuid = __salt__['smbios.get']('system-uuid') if uuid is not None: grains['uuid'] = uuid.lower() for serial in ('system-serial-number', 'chassis-serial-number', 'baseboard-serial-number'): serial = __salt__['smbios.get'](serial) if serial is not None: grains['serialnumber'] = serial break elif salt.utils.path.which_bin(['fw_printenv']) is not None: # ARM Linux devices expose UBOOT env variables via fw_printenv hwdata = { 'manufacturer': 'manufacturer', 'serialnumber': 'serial#', 'productname': 'DeviceDesc', } for grain_name, cmd_key in six.iteritems(hwdata): result = __salt__['cmd.run_all']('fw_printenv {0}'.format(cmd_key)) if result['retcode'] == 0: uboot_keyval = result['stdout'].split('=') grains[grain_name] = _clean_value(grain_name, uboot_keyval[1]) elif osdata['kernel'] == 'FreeBSD': # On FreeBSD /bin/kenv (already in base system) # can be used instead of dmidecode kenv = salt.utils.path.which('kenv') if kenv: # In theory, it will be easier to add new fields to this later fbsd_hwdata = { 'biosversion': 'smbios.bios.version', 'manufacturer': 'smbios.system.maker', 'serialnumber': 'smbios.system.serial', 'productname': 'smbios.system.product', 'biosreleasedate': 'smbios.bios.reldate', 'uuid': 'smbios.system.uuid', } for key, val in six.iteritems(fbsd_hwdata): value = __salt__['cmd.run']('{0} {1}'.format(kenv, val)) grains[key] = _clean_value(key, value) elif osdata['kernel'] == 'OpenBSD': sysctl = salt.utils.path.which('sysctl') hwdata = {'biosversion': 'hw.version', 'manufacturer': 'hw.vendor', 'productname': 'hw.product', 'serialnumber': 'hw.serialno', 'uuid': 'hw.uuid'} for key, oid in six.iteritems(hwdata): value = __salt__['cmd.run']('{0} -n {1}'.format(sysctl, oid)) if not value.endswith(' value is not available'): grains[key] = _clean_value(key, value) elif osdata['kernel'] == 'NetBSD': sysctl = salt.utils.path.which('sysctl') nbsd_hwdata = { 'biosversion': 'machdep.dmi.board-version', 'manufacturer': 'machdep.dmi.system-vendor', 'serialnumber': 'machdep.dmi.system-serial', 'productname': 'machdep.dmi.system-product', 'biosreleasedate': 'machdep.dmi.bios-date', 'uuid': 'machdep.dmi.system-uuid', } for key, oid in six.iteritems(nbsd_hwdata): result = __salt__['cmd.run_all']('{0} -n {1}'.format(sysctl, oid)) if result['retcode'] == 0: grains[key] = _clean_value(key, result['stdout']) elif osdata['kernel'] == 'Darwin': grains['manufacturer'] = 'Apple Inc.' sysctl = salt.utils.path.which('sysctl') hwdata = {'productname': 'hw.model'} for key, oid in hwdata.items(): value = __salt__['cmd.run']('{0} -b {1}'.format(sysctl, oid)) if not value.endswith(' is invalid'): grains[key] = _clean_value(key, value) elif osdata['kernel'] == 'SunOS' and osdata['cpuarch'].startswith('sparc'): # Depending on the hardware model, commands can report different bits # of information. With that said, consolidate the output from various # commands and attempt various lookups. data = "" for (cmd, args) in (('/usr/sbin/prtdiag', '-v'), ('/usr/sbin/prtconf', '-vp'), ('/usr/sbin/virtinfo', '-a')): if salt.utils.path.which(cmd): # Also verifies that cmd is executable data += __salt__['cmd.run']('{0} {1}'.format(cmd, args)) data += '\n' sn_regexes = [ re.compile(r) for r in [ r'(?im)^\s*Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag r'(?im)^\s*chassis-sn:\s*(\S+)', # prtconf r'(?im)^\s*Chassis\s+Serial#:\s*(\S+)', # virtinfo ] ] obp_regexes = [ re.compile(r) for r in [ r'(?im)^\s*System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag r'(?im)^\s*version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf ] ] fw_regexes = [ re.compile(r) for r in [ r'(?im)^\s*Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag ] ] uuid_regexes = [ re.compile(r) for r in [ r'(?im)^\s*Domain\s+UUID:\s*(\S+)', # virtinfo ] ] manufacture_regexes = [ re.compile(r) for r in [ r'(?im)^\s*System\s+Configuration:\s*(.*)(?=sun)', # prtdiag ] ] product_regexes = [ re.compile(r) for r in [ r'(?im)^\s*System\s+Configuration:\s*.*?sun\d\S+[^\S\r\n]*(.*)', # prtdiag r'(?im)^[^\S\r\n]*banner-name:[^\S\r\n]*(.*)', # prtconf r'(?im)^[^\S\r\n]*product-name:[^\S\r\n]*(.*)', # prtconf ] ] sn_regexes = [ re.compile(r) for r in [ r'(?im)Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag r'(?i)Chassis\s+Serial#:\s*(\S+)', # virtinfo r'(?i)chassis-sn:\s*(\S+)', # prtconf ] ] obp_regexes = [ re.compile(r) for r in [ r'(?im)System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag r'(?im)version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf ] ] fw_regexes = [ re.compile(r) for r in [ r'(?i)Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag ] ] uuid_regexes = [ re.compile(r) for r in [ r'(?i)Domain\s+UUID:\s+(\S+)', # virtinfo ] ] for regex in sn_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: grains['serialnumber'] = res.group(1).strip().replace("'", "") break for regex in obp_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: obp_rev, obp_date = res.groups()[0:2] # Limit the number in case we found the data in multiple places grains['biosversion'] = obp_rev.strip().replace("'", "") grains['biosreleasedate'] = obp_date.strip().replace("'", "") for regex in fw_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: fw_rev, fw_date = res.groups()[0:2] grains['systemfirmware'] = fw_rev.strip().replace("'", "") grains['systemfirmwaredate'] = fw_date.strip().replace("'", "") break for regex in uuid_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: grains['uuid'] = res.group(1).strip().replace("'", "") break for regex in manufacture_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: grains['manufacture'] = res.group(1).strip().replace("'", "") break for regex in product_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: t_productname = res.group(1).strip().replace("'", "") if t_productname: grains['product'] = t_productname grains['productname'] = t_productname break elif osdata['kernel'] == 'AIX': cmd = salt.utils.path.which('prtconf') if cmd: data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'), ('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')): for regex in [re.compile(r) for r in [regstring]]: res = regex.search(data) if res and len(res.groups()) >= 1: grains[dest] = res.group(1).strip().replace("'", '') product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')] for regex in product_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",") break else: log.error('The \'prtconf\' binary was not found in $PATH.') elif osdata['kernel'] == 'AIX': cmd = salt.utils.path.which('prtconf') if data: data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'), ('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')): for regex in [re.compile(r) for r in [regstring]]: res = regex.search(data) if res and len(res.groups()) >= 1: grains[dest] = res.group(1).strip().replace("'", '') product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')] for regex in product_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",") break else: log.error('The \'prtconf\' binary was not found in $PATH.') return grains def _get_hash_by_shell(): ''' Shell-out Python 3 for compute reliable hash :return: ''' id_ = __opts__.get('id', '') id_hash = None py_ver = sys.version_info[:2] if py_ver >= (3, 3): # Python 3.3 enabled hash randomization, so we need to shell out to get # a reliable hash. id_hash = __salt__['cmd.run']([sys.executable, '-c', 'print(hash("{0}"))'.format(id_)], env={'PYTHONHASHSEED': '0'}) try: id_hash = int(id_hash) except (TypeError, ValueError): log.debug('Failed to hash the ID to get the server_id grain. Result of hash command: %s', id_hash) id_hash = None if id_hash is None: # Python < 3.3 or error encountered above id_hash = hash(id_) return abs(id_hash % (2 ** 31)) def get_server_id(): ''' Provides an integer based on the FQDN of a machine. Useful as server-id in MySQL replication or anywhere else you'll need an ID like this. ''' # Provides: # server_id if salt.utils.platform.is_proxy(): server_id = {} else: use_crc = __opts__.get('server_id_use_crc') if bool(use_crc): id_hash = getattr(zlib, use_crc, zlib.adler32)(__opts__.get('id', '').encode()) & 0xffffffff else: log.debug('This server_id is computed not by Adler32 nor by CRC32. ' 'Please use "server_id_use_crc" option and define algorithm you ' 'prefer (default "Adler32"). Starting with Sodium, the ' 'server_id will be computed with Adler32 by default.') id_hash = _get_hash_by_shell() server_id = {'server_id': id_hash} return server_id def get_master(): ''' Provides the minion with the name of its master. This is useful in states to target other services running on the master. ''' # Provides: # master return {'master': __opts__.get('master', '')} def default_gateway(): ''' Populates grains which describe whether a server has a default gateway configured or not. Uses `ip -4 route show` and `ip -6 route show` and greps for a `default` at the beginning of any line. Assuming the standard `default via <ip>` format for default gateways, it will also parse out the ip address of the default gateway, and put it in ip4_gw or ip6_gw. If the `ip` command is unavailable, no grains will be populated. Currently does not support multiple default gateways. The grains will be set to the first default gateway found. List of grains: ip4_gw: True # ip/True/False if default ipv4 gateway ip6_gw: True # ip/True/False if default ipv6 gateway ip_gw: True # True if either of the above is True, False otherwise ''' grains = {} ip_bin = salt.utils.path.which('ip') if not ip_bin: return {} grains['ip_gw'] = False grains['ip4_gw'] = False grains['ip6_gw'] = False for ip_version in ('4', '6'): try: out = __salt__['cmd.run']([ip_bin, '-' + ip_version, 'route', 'show']) for line in out.splitlines(): if line.startswith('default'): grains['ip_gw'] = True grains['ip{0}_gw'.format(ip_version)] = True try: via, gw_ip = line.split()[1:3] except ValueError: pass else: if via == 'via': grains['ip{0}_gw'.format(ip_version)] = gw_ip break except Exception: continue return grains def kernelparams(): ''' Return the kernel boot parameters ''' if salt.utils.platform.is_windows(): # TODO: add grains using `bcdedit /enum {current}` return {} else: try: with salt.utils.files.fopen('/proc/cmdline', 'r') as fhr: cmdline = fhr.read() grains = {'kernelparams': []} for data in [item.split('=') for item in salt.utils.args.shlex_split(cmdline)]: value = None if len(data) == 2: value = data[1].strip('"') grains['kernelparams'] += [(data[0], value)] except IOError as exc: grains = {} log.debug('Failed to read /proc/cmdline: %s', exc) return grains
saltstack/salt
salt/grains/core.py
_hw_data
python
def _hw_data(osdata): ''' Get system specific hardware data from dmidecode Provides biosversion productname manufacturer serialnumber biosreleasedate uuid .. versionadded:: 0.9.5 ''' if salt.utils.platform.is_proxy(): return {} grains = {} if osdata['kernel'] == 'Linux' and os.path.exists('/sys/class/dmi/id'): # On many Linux distributions basic firmware information is available via sysfs # requires CONFIG_DMIID to be enabled in the Linux kernel configuration sysfs_firmware_info = { 'biosversion': 'bios_version', 'productname': 'product_name', 'manufacturer': 'sys_vendor', 'biosreleasedate': 'bios_date', 'uuid': 'product_uuid', 'serialnumber': 'product_serial' } for key, fw_file in sysfs_firmware_info.items(): contents_file = os.path.join('/sys/class/dmi/id', fw_file) if os.path.exists(contents_file): try: with salt.utils.files.fopen(contents_file, 'r') as ifile: grains[key] = salt.utils.stringutils.to_unicode(ifile.read().strip(), errors='replace') if key == 'uuid': grains['uuid'] = grains['uuid'].lower() except (IOError, OSError) as err: # PermissionError is new to Python 3, but corresponds to the EACESS and # EPERM error numbers. Use those instead here for PY2 compatibility. if err.errno == EACCES or err.errno == EPERM: # Skip the grain if non-root user has no access to the file. pass elif salt.utils.path.which_bin(['dmidecode', 'smbios']) is not None and not ( salt.utils.platform.is_smartos() or ( # SunOS on SPARC - 'smbios: failed to load SMBIOS: System does not export an SMBIOS table' osdata['kernel'] == 'SunOS' and osdata['cpuarch'].startswith('sparc') )): # On SmartOS (possibly SunOS also) smbios only works in the global zone # smbios is also not compatible with linux's smbios (smbios -s = print summarized) grains = { 'biosversion': __salt__['smbios.get']('bios-version'), 'productname': __salt__['smbios.get']('system-product-name'), 'manufacturer': __salt__['smbios.get']('system-manufacturer'), 'biosreleasedate': __salt__['smbios.get']('bios-release-date'), 'uuid': __salt__['smbios.get']('system-uuid') } grains = dict([(key, val) for key, val in grains.items() if val is not None]) uuid = __salt__['smbios.get']('system-uuid') if uuid is not None: grains['uuid'] = uuid.lower() for serial in ('system-serial-number', 'chassis-serial-number', 'baseboard-serial-number'): serial = __salt__['smbios.get'](serial) if serial is not None: grains['serialnumber'] = serial break elif salt.utils.path.which_bin(['fw_printenv']) is not None: # ARM Linux devices expose UBOOT env variables via fw_printenv hwdata = { 'manufacturer': 'manufacturer', 'serialnumber': 'serial#', 'productname': 'DeviceDesc', } for grain_name, cmd_key in six.iteritems(hwdata): result = __salt__['cmd.run_all']('fw_printenv {0}'.format(cmd_key)) if result['retcode'] == 0: uboot_keyval = result['stdout'].split('=') grains[grain_name] = _clean_value(grain_name, uboot_keyval[1]) elif osdata['kernel'] == 'FreeBSD': # On FreeBSD /bin/kenv (already in base system) # can be used instead of dmidecode kenv = salt.utils.path.which('kenv') if kenv: # In theory, it will be easier to add new fields to this later fbsd_hwdata = { 'biosversion': 'smbios.bios.version', 'manufacturer': 'smbios.system.maker', 'serialnumber': 'smbios.system.serial', 'productname': 'smbios.system.product', 'biosreleasedate': 'smbios.bios.reldate', 'uuid': 'smbios.system.uuid', } for key, val in six.iteritems(fbsd_hwdata): value = __salt__['cmd.run']('{0} {1}'.format(kenv, val)) grains[key] = _clean_value(key, value) elif osdata['kernel'] == 'OpenBSD': sysctl = salt.utils.path.which('sysctl') hwdata = {'biosversion': 'hw.version', 'manufacturer': 'hw.vendor', 'productname': 'hw.product', 'serialnumber': 'hw.serialno', 'uuid': 'hw.uuid'} for key, oid in six.iteritems(hwdata): value = __salt__['cmd.run']('{0} -n {1}'.format(sysctl, oid)) if not value.endswith(' value is not available'): grains[key] = _clean_value(key, value) elif osdata['kernel'] == 'NetBSD': sysctl = salt.utils.path.which('sysctl') nbsd_hwdata = { 'biosversion': 'machdep.dmi.board-version', 'manufacturer': 'machdep.dmi.system-vendor', 'serialnumber': 'machdep.dmi.system-serial', 'productname': 'machdep.dmi.system-product', 'biosreleasedate': 'machdep.dmi.bios-date', 'uuid': 'machdep.dmi.system-uuid', } for key, oid in six.iteritems(nbsd_hwdata): result = __salt__['cmd.run_all']('{0} -n {1}'.format(sysctl, oid)) if result['retcode'] == 0: grains[key] = _clean_value(key, result['stdout']) elif osdata['kernel'] == 'Darwin': grains['manufacturer'] = 'Apple Inc.' sysctl = salt.utils.path.which('sysctl') hwdata = {'productname': 'hw.model'} for key, oid in hwdata.items(): value = __salt__['cmd.run']('{0} -b {1}'.format(sysctl, oid)) if not value.endswith(' is invalid'): grains[key] = _clean_value(key, value) elif osdata['kernel'] == 'SunOS' and osdata['cpuarch'].startswith('sparc'): # Depending on the hardware model, commands can report different bits # of information. With that said, consolidate the output from various # commands and attempt various lookups. data = "" for (cmd, args) in (('/usr/sbin/prtdiag', '-v'), ('/usr/sbin/prtconf', '-vp'), ('/usr/sbin/virtinfo', '-a')): if salt.utils.path.which(cmd): # Also verifies that cmd is executable data += __salt__['cmd.run']('{0} {1}'.format(cmd, args)) data += '\n' sn_regexes = [ re.compile(r) for r in [ r'(?im)^\s*Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag r'(?im)^\s*chassis-sn:\s*(\S+)', # prtconf r'(?im)^\s*Chassis\s+Serial#:\s*(\S+)', # virtinfo ] ] obp_regexes = [ re.compile(r) for r in [ r'(?im)^\s*System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag r'(?im)^\s*version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf ] ] fw_regexes = [ re.compile(r) for r in [ r'(?im)^\s*Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag ] ] uuid_regexes = [ re.compile(r) for r in [ r'(?im)^\s*Domain\s+UUID:\s*(\S+)', # virtinfo ] ] manufacture_regexes = [ re.compile(r) for r in [ r'(?im)^\s*System\s+Configuration:\s*(.*)(?=sun)', # prtdiag ] ] product_regexes = [ re.compile(r) for r in [ r'(?im)^\s*System\s+Configuration:\s*.*?sun\d\S+[^\S\r\n]*(.*)', # prtdiag r'(?im)^[^\S\r\n]*banner-name:[^\S\r\n]*(.*)', # prtconf r'(?im)^[^\S\r\n]*product-name:[^\S\r\n]*(.*)', # prtconf ] ] sn_regexes = [ re.compile(r) for r in [ r'(?im)Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag r'(?i)Chassis\s+Serial#:\s*(\S+)', # virtinfo r'(?i)chassis-sn:\s*(\S+)', # prtconf ] ] obp_regexes = [ re.compile(r) for r in [ r'(?im)System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag r'(?im)version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf ] ] fw_regexes = [ re.compile(r) for r in [ r'(?i)Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag ] ] uuid_regexes = [ re.compile(r) for r in [ r'(?i)Domain\s+UUID:\s+(\S+)', # virtinfo ] ] for regex in sn_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: grains['serialnumber'] = res.group(1).strip().replace("'", "") break for regex in obp_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: obp_rev, obp_date = res.groups()[0:2] # Limit the number in case we found the data in multiple places grains['biosversion'] = obp_rev.strip().replace("'", "") grains['biosreleasedate'] = obp_date.strip().replace("'", "") for regex in fw_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: fw_rev, fw_date = res.groups()[0:2] grains['systemfirmware'] = fw_rev.strip().replace("'", "") grains['systemfirmwaredate'] = fw_date.strip().replace("'", "") break for regex in uuid_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: grains['uuid'] = res.group(1).strip().replace("'", "") break for regex in manufacture_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: grains['manufacture'] = res.group(1).strip().replace("'", "") break for regex in product_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: t_productname = res.group(1).strip().replace("'", "") if t_productname: grains['product'] = t_productname grains['productname'] = t_productname break elif osdata['kernel'] == 'AIX': cmd = salt.utils.path.which('prtconf') if cmd: data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'), ('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')): for regex in [re.compile(r) for r in [regstring]]: res = regex.search(data) if res and len(res.groups()) >= 1: grains[dest] = res.group(1).strip().replace("'", '') product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')] for regex in product_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",") break else: log.error('The \'prtconf\' binary was not found in $PATH.') elif osdata['kernel'] == 'AIX': cmd = salt.utils.path.which('prtconf') if data: data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'), ('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')): for regex in [re.compile(r) for r in [regstring]]: res = regex.search(data) if res and len(res.groups()) >= 1: grains[dest] = res.group(1).strip().replace("'", '') product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')] for regex in product_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",") break else: log.error('The \'prtconf\' binary was not found in $PATH.') return grains
Get system specific hardware data from dmidecode Provides biosversion productname manufacturer serialnumber biosreleasedate uuid .. versionadded:: 0.9.5
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/grains/core.py#L2448-L2737
null
# -*- coding: utf-8 -*- ''' The static grains, these are the core, or built in grains. When grains are loaded they are not loaded in the same way that modules are loaded, grain functions are detected and executed, the functions MUST return a dict which will be applied to the main grains dict. This module will always be executed first, so that any grains loaded here in the core module can be overwritten just by returning dict keys with the same value as those returned here ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import socket import sys import re import platform import logging import locale import uuid import zlib from errno import EACCES, EPERM import datetime import warnings # pylint: disable=import-error try: import dateutil.tz _DATEUTIL_TZ = True except ImportError: _DATEUTIL_TZ = False __proxyenabled__ = ['*'] __FQDN__ = None # Extend the default list of supported distros. This will be used for the # /etc/DISTRO-release checking that is part of linux_distribution() from platform import _supported_dists _supported_dists += ('arch', 'mageia', 'meego', 'vmware', 'bluewhite64', 'slamd64', 'ovs', 'system', 'mint', 'oracle', 'void') # linux_distribution deprecated in py3.7 try: from platform import linux_distribution as _deprecated_linux_distribution def linux_distribution(**kwargs): with warnings.catch_warnings(): warnings.simplefilter("ignore") return _deprecated_linux_distribution(**kwargs) except ImportError: from distro import linux_distribution # Import salt libs import salt.exceptions import salt.log import salt.utils.args import salt.utils.dns import salt.utils.files import salt.utils.network import salt.utils.path import salt.utils.pkg.rpm import salt.utils.platform import salt.utils.stringutils import salt.utils.versions from salt.ext import six from salt.ext.six.moves import range if salt.utils.platform.is_windows(): import salt.utils.win_osinfo # Solve the Chicken and egg problem where grains need to run before any # of the modules are loaded and are generally available for any usage. import salt.modules.cmdmod import salt.modules.smbios __salt__ = { 'cmd.run': salt.modules.cmdmod._run_quiet, 'cmd.retcode': salt.modules.cmdmod._retcode_quiet, 'cmd.run_all': salt.modules.cmdmod._run_all_quiet, 'smbios.records': salt.modules.smbios.records, 'smbios.get': salt.modules.smbios.get, } log = logging.getLogger(__name__) HAS_WMI = False if salt.utils.platform.is_windows(): # attempt to import the python wmi module # the Windows minion uses WMI for some of its grains try: import wmi # pylint: disable=import-error import salt.utils.winapi import win32api import salt.utils.win_reg HAS_WMI = True except ImportError: log.exception( 'Unable to import Python wmi module, some core grains ' 'will be missing' ) HAS_UNAME = True if not hasattr(os, 'uname'): HAS_UNAME = False _INTERFACES = {} def _windows_cpudata(): ''' Return some CPU information on Windows minions ''' # Provides: # num_cpus # cpu_model grains = {} if 'NUMBER_OF_PROCESSORS' in os.environ: # Cast to int so that the logic isn't broken when used as a # conditional in templating. Also follows _linux_cpudata() try: grains['num_cpus'] = int(os.environ['NUMBER_OF_PROCESSORS']) except ValueError: grains['num_cpus'] = 1 grains['cpu_model'] = salt.utils.win_reg.read_value( hive="HKEY_LOCAL_MACHINE", key="HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", vname="ProcessorNameString").get('vdata') return grains def _linux_cpudata(): ''' Return some CPU information for Linux minions ''' # Provides: # num_cpus # cpu_model # cpu_flags grains = {} cpuinfo = '/proc/cpuinfo' # Parse over the cpuinfo file if os.path.isfile(cpuinfo): with salt.utils.files.fopen(cpuinfo, 'r') as _fp: grains['num_cpus'] = 0 for line in _fp: comps = line.split(':') if not len(comps) > 1: continue key = comps[0].strip() val = comps[1].strip() if key == 'processor': grains['num_cpus'] += 1 elif key == 'model name': grains['cpu_model'] = val elif key == 'flags': grains['cpu_flags'] = val.split() elif key == 'Features': grains['cpu_flags'] = val.split() # ARM support - /proc/cpuinfo # # Processor : ARMv6-compatible processor rev 7 (v6l) # BogoMIPS : 697.95 # Features : swp half thumb fastmult vfp edsp java tls # CPU implementer : 0x41 # CPU architecture: 7 # CPU variant : 0x0 # CPU part : 0xb76 # CPU revision : 7 # # Hardware : BCM2708 # Revision : 0002 # Serial : 00000000 elif key == 'Processor': grains['cpu_model'] = val.split('-')[0] grains['num_cpus'] = 1 if 'num_cpus' not in grains: grains['num_cpus'] = 0 if 'cpu_model' not in grains: grains['cpu_model'] = 'Unknown' if 'cpu_flags' not in grains: grains['cpu_flags'] = [] return grains def _linux_gpu_data(): ''' num_gpus: int gpus: - vendor: nvidia|amd|ati|... model: string ''' if __opts__.get('enable_lspci', True) is False: return {} if __opts__.get('enable_gpu_grains', True) is False: return {} lspci = salt.utils.path.which('lspci') if not lspci: log.debug( 'The `lspci` binary is not available on the system. GPU grains ' 'will not be available.' ) return {} # dominant gpu vendors to search for (MUST be lowercase for matching below) known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed'] gpu_classes = ('vga compatible controller', '3d controller') devs = [] try: lspci_out = __salt__['cmd.run']('{0} -vmm'.format(lspci)) cur_dev = {} error = False # Add a blank element to the lspci_out.splitlines() list, # otherwise the last device is not evaluated as a cur_dev and ignored. lspci_list = lspci_out.splitlines() lspci_list.append('') for line in lspci_list: # check for record-separating empty lines if line == '': if cur_dev.get('Class', '').lower() in gpu_classes: devs.append(cur_dev) cur_dev = {} continue if re.match(r'^\w+:\s+.*', line): key, val = line.split(':', 1) cur_dev[key.strip()] = val.strip() else: error = True log.debug('Unexpected lspci output: \'%s\'', line) if error: log.warning( 'Error loading grains, unexpected linux_gpu_data output, ' 'check that you have a valid shell configured and ' 'permissions to run lspci command' ) except OSError: pass gpus = [] for gpu in devs: vendor_strings = re.split('[^A-Za-z0-9]', gpu['Vendor'].lower()) # default vendor to 'unknown', overwrite if we match a known one vendor = 'unknown' for name in known_vendors: # search for an 'expected' vendor name in the list of strings if name in vendor_strings: vendor = name break gpus.append({'vendor': vendor, 'model': gpu['Device']}) grains = {} grains['num_gpus'] = len(gpus) grains['gpus'] = gpus return grains def _netbsd_gpu_data(): ''' num_gpus: int gpus: - vendor: nvidia|amd|ati|... model: string ''' known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed'] gpus = [] try: pcictl_out = __salt__['cmd.run']('pcictl pci0 list') for line in pcictl_out.splitlines(): for vendor in known_vendors: vendor_match = re.match( r'[0-9:]+ ({0}) (.+) \(VGA .+\)'.format(vendor), line, re.IGNORECASE ) if vendor_match: gpus.append({'vendor': vendor_match.group(1), 'model': vendor_match.group(2)}) except OSError: pass grains = {} grains['num_gpus'] = len(gpus) grains['gpus'] = gpus return grains def _osx_gpudata(): ''' num_gpus: int gpus: - vendor: nvidia|amd|ati|... model: string ''' gpus = [] try: pcictl_out = __salt__['cmd.run']('system_profiler SPDisplaysDataType') for line in pcictl_out.splitlines(): fieldname, _, fieldval = line.partition(': ') if fieldname.strip() == "Chipset Model": vendor, _, model = fieldval.partition(' ') vendor = vendor.lower() gpus.append({'vendor': vendor, 'model': model}) except OSError: pass grains = {} grains['num_gpus'] = len(gpus) grains['gpus'] = gpus return grains def _bsd_cpudata(osdata): ''' Return CPU information for BSD-like systems ''' # Provides: # cpuarch # num_cpus # cpu_model # cpu_flags sysctl = salt.utils.path.which('sysctl') arch = salt.utils.path.which('arch') cmds = {} if sysctl: cmds.update({ 'num_cpus': '{0} -n hw.ncpu'.format(sysctl), 'cpuarch': '{0} -n hw.machine'.format(sysctl), 'cpu_model': '{0} -n hw.model'.format(sysctl), }) if arch and osdata['kernel'] == 'OpenBSD': cmds['cpuarch'] = '{0} -s'.format(arch) if osdata['kernel'] == 'Darwin': cmds['cpu_model'] = '{0} -n machdep.cpu.brand_string'.format(sysctl) cmds['cpu_flags'] = '{0} -n machdep.cpu.features'.format(sysctl) grains = dict([(k, __salt__['cmd.run'](v)) for k, v in six.iteritems(cmds)]) if 'cpu_flags' in grains and isinstance(grains['cpu_flags'], six.string_types): grains['cpu_flags'] = grains['cpu_flags'].split(' ') if osdata['kernel'] == 'NetBSD': grains['cpu_flags'] = [] for line in __salt__['cmd.run']('cpuctl identify 0').splitlines(): cpu_match = re.match(r'cpu[0-9]:\ features[0-9]?\ .+<(.+)>', line) if cpu_match: flag = cpu_match.group(1).split(',') grains['cpu_flags'].extend(flag) if osdata['kernel'] == 'FreeBSD' and os.path.isfile('/var/run/dmesg.boot'): grains['cpu_flags'] = [] # TODO: at least it needs to be tested for BSD other then FreeBSD with salt.utils.files.fopen('/var/run/dmesg.boot', 'r') as _fp: cpu_here = False for line in _fp: if line.startswith('CPU: '): cpu_here = True # starts CPU descr continue if cpu_here: if not line.startswith(' '): break # game over if 'Features' in line: start = line.find('<') end = line.find('>') if start > 0 and end > 0: flag = line[start + 1:end].split(',') grains['cpu_flags'].extend(flag) try: grains['num_cpus'] = int(grains['num_cpus']) except ValueError: grains['num_cpus'] = 1 return grains def _sunos_cpudata(): ''' Return the CPU information for Solaris-like systems ''' # Provides: # cpuarch # num_cpus # cpu_model # cpu_flags grains = {} grains['cpu_flags'] = [] grains['cpuarch'] = __salt__['cmd.run']('isainfo -k') psrinfo = '/usr/sbin/psrinfo 2>/dev/null' grains['num_cpus'] = len(__salt__['cmd.run'](psrinfo, python_shell=True).splitlines()) kstat_info = 'kstat -p cpu_info:*:*:brand' for line in __salt__['cmd.run'](kstat_info).splitlines(): match = re.match(r'(\w+:\d+:\w+\d+:\w+)\s+(.+)', line) if match: grains['cpu_model'] = match.group(2) isainfo = 'isainfo -n -v' for line in __salt__['cmd.run'](isainfo).splitlines(): match = re.match(r'^\s+(.+)', line) if match: cpu_flags = match.group(1).split() grains['cpu_flags'].extend(cpu_flags) return grains def _aix_cpudata(): ''' Return CPU information for AIX systems ''' # Provides: # cpuarch # num_cpus # cpu_model # cpu_flags grains = {} cmd = salt.utils.path.which('prtconf') if cmd: data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep for dest, regstring in (('cpuarch', r'(?im)^\s*Processor\s+Type:\s+(\S+)'), ('cpu_flags', r'(?im)^\s*Processor\s+Version:\s+(\S+)'), ('cpu_model', r'(?im)^\s*Processor\s+Implementation\s+Mode:\s+(.*)'), ('num_cpus', r'(?im)^\s*Number\s+Of\s+Processors:\s+(\S+)')): for regex in [re.compile(r) for r in [regstring]]: res = regex.search(data) if res and len(res.groups()) >= 1: grains[dest] = res.group(1).strip().replace("'", '') else: log.error('The \'prtconf\' binary was not found in $PATH.') return grains def _linux_memdata(): ''' Return the memory information for Linux-like systems ''' grains = {'mem_total': 0, 'swap_total': 0} meminfo = '/proc/meminfo' if os.path.isfile(meminfo): with salt.utils.files.fopen(meminfo, 'r') as ifile: for line in ifile: comps = line.rstrip('\n').split(':') if not len(comps) > 1: continue if comps[0].strip() == 'MemTotal': # Use floor division to force output to be an integer grains['mem_total'] = int(comps[1].split()[0]) // 1024 if comps[0].strip() == 'SwapTotal': # Use floor division to force output to be an integer grains['swap_total'] = int(comps[1].split()[0]) // 1024 return grains def _osx_memdata(): ''' Return the memory information for BSD-like systems ''' grains = {'mem_total': 0, 'swap_total': 0} sysctl = salt.utils.path.which('sysctl') if sysctl: mem = __salt__['cmd.run']('{0} -n hw.memsize'.format(sysctl)) swap_total = __salt__['cmd.run']('{0} -n vm.swapusage'.format(sysctl)).split()[2].replace(',', '.') if swap_total.endswith('K'): _power = 2**10 elif swap_total.endswith('M'): _power = 2**20 elif swap_total.endswith('G'): _power = 2**30 swap_total = float(swap_total[:-1]) * _power grains['mem_total'] = int(mem) // 1024 // 1024 grains['swap_total'] = int(swap_total) // 1024 // 1024 return grains def _bsd_memdata(osdata): ''' Return the memory information for BSD-like systems ''' grains = {'mem_total': 0, 'swap_total': 0} sysctl = salt.utils.path.which('sysctl') if sysctl: mem = __salt__['cmd.run']('{0} -n hw.physmem'.format(sysctl)) if osdata['kernel'] == 'NetBSD' and mem.startswith('-'): mem = __salt__['cmd.run']('{0} -n hw.physmem64'.format(sysctl)) grains['mem_total'] = int(mem) // 1024 // 1024 if osdata['kernel'] in ['OpenBSD', 'NetBSD']: swapctl = salt.utils.path.which('swapctl') swap_data = __salt__['cmd.run']('{0} -sk'.format(swapctl)) if swap_data == 'no swap devices configured': swap_total = 0 else: swap_total = swap_data.split(' ')[1] else: swap_total = __salt__['cmd.run']('{0} -n vm.swap_total'.format(sysctl)) grains['swap_total'] = int(swap_total) // 1024 // 1024 return grains def _sunos_memdata(): ''' Return the memory information for SunOS-like systems ''' grains = {'mem_total': 0, 'swap_total': 0} prtconf = '/usr/sbin/prtconf 2>/dev/null' for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines(): comps = line.split(' ') if comps[0].strip() == 'Memory' and comps[1].strip() == 'size:': grains['mem_total'] = int(comps[2].strip()) swap_cmd = salt.utils.path.which('swap') swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split() try: swap_avail = int(swap_data[-2][:-1]) swap_used = int(swap_data[-4][:-1]) swap_total = (swap_avail + swap_used) // 1024 except ValueError: swap_total = None grains['swap_total'] = swap_total return grains def _aix_memdata(): ''' Return the memory information for AIX systems ''' grains = {'mem_total': 0, 'swap_total': 0} prtconf = salt.utils.path.which('prtconf') if prtconf: for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines(): comps = [x for x in line.strip().split(' ') if x] if len(comps) > 2 and 'Memory' in comps[0] and 'Size' in comps[1]: grains['mem_total'] = int(comps[2]) break else: log.error('The \'prtconf\' binary was not found in $PATH.') swap_cmd = salt.utils.path.which('swap') if swap_cmd: swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split() try: swap_total = (int(swap_data[-2]) + int(swap_data[-6])) * 4 except ValueError: swap_total = None grains['swap_total'] = swap_total else: log.error('The \'swap\' binary was not found in $PATH.') return grains def _windows_memdata(): ''' Return the memory information for Windows systems ''' grains = {'mem_total': 0} # get the Total Physical memory as reported by msinfo32 tot_bytes = win32api.GlobalMemoryStatusEx()['TotalPhys'] # return memory info in gigabytes grains['mem_total'] = int(tot_bytes / (1024 ** 2)) return grains def _memdata(osdata): ''' Gather information about the system memory ''' # Provides: # mem_total # swap_total, for supported systems. grains = {'mem_total': 0} if osdata['kernel'] == 'Linux': grains.update(_linux_memdata()) elif osdata['kernel'] in ('FreeBSD', 'OpenBSD', 'NetBSD'): grains.update(_bsd_memdata(osdata)) elif osdata['kernel'] == 'Darwin': grains.update(_osx_memdata()) elif osdata['kernel'] == 'SunOS': grains.update(_sunos_memdata()) elif osdata['kernel'] == 'AIX': grains.update(_aix_memdata()) elif osdata['kernel'] == 'Windows' and HAS_WMI: grains.update(_windows_memdata()) return grains def _aix_get_machine_id(): ''' Parse the output of lsattr -El sys0 for os_uuid ''' grains = {} cmd = salt.utils.path.which('lsattr') if cmd: data = __salt__['cmd.run']('{0} -El sys0'.format(cmd)) + os.linesep uuid_regexes = [re.compile(r'(?im)^\s*os_uuid\s+(\S+)\s+(.*)')] for regex in uuid_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: grains['machine_id'] = res.group(1).strip() break else: log.error('The \'lsattr\' binary was not found in $PATH.') return grains def _windows_virtual(osdata): ''' Returns what type of virtual hardware is under the hood, kvm or physical ''' # Provides: # virtual # virtual_subtype grains = dict() if osdata['kernel'] != 'Windows': return grains grains['virtual'] = 'physical' # It is possible that the 'manufacturer' and/or 'productname' grains # exist but have a value of None. manufacturer = osdata.get('manufacturer', '') if manufacturer is None: manufacturer = '' productname = osdata.get('productname', '') if productname is None: productname = '' if 'QEMU' in manufacturer: # FIXME: Make this detect between kvm or qemu grains['virtual'] = 'kvm' if 'Bochs' in manufacturer: grains['virtual'] = 'kvm' # Product Name: (oVirt) www.ovirt.org # Red Hat Community virtualization Project based on kvm elif 'oVirt' in productname: grains['virtual'] = 'kvm' grains['virtual_subtype'] = 'oVirt' # Red Hat Enterprise Virtualization elif 'RHEV Hypervisor' in productname: grains['virtual'] = 'kvm' grains['virtual_subtype'] = 'rhev' # Product Name: VirtualBox elif 'VirtualBox' in productname: grains['virtual'] = 'VirtualBox' # Product Name: VMware Virtual Platform elif 'VMware Virtual Platform' in productname: grains['virtual'] = 'VMware' # Manufacturer: Microsoft Corporation # Product Name: Virtual Machine elif 'Microsoft' in manufacturer and \ 'Virtual Machine' in productname: grains['virtual'] = 'VirtualPC' # Manufacturer: Parallels Software International Inc. elif 'Parallels Software' in manufacturer: grains['virtual'] = 'Parallels' # Apache CloudStack elif 'CloudStack KVM Hypervisor' in productname: grains['virtual'] = 'kvm' grains['virtual_subtype'] = 'cloudstack' return grains def _virtual(osdata): ''' Returns what type of virtual hardware is under the hood, kvm or physical ''' # This is going to be a monster, if you are running a vm you can test this # grain with please submit patches! # Provides: # virtual # virtual_subtype grains = {'virtual': 'physical'} # Skip the below loop on platforms which have none of the desired cmds # This is a temporary measure until we can write proper virtual hardware # detection. skip_cmds = ('AIX',) # list of commands to be executed to determine the 'virtual' grain _cmds = ['systemd-detect-virt', 'virt-what', 'dmidecode'] # test first for virt-what, which covers most of the desired functionality # on most platforms if not salt.utils.platform.is_windows() and osdata['kernel'] not in skip_cmds: if salt.utils.path.which('virt-what'): _cmds = ['virt-what'] # Check if enable_lspci is True or False if __opts__.get('enable_lspci', True) is True: # /proc/bus/pci does not exists, lspci will fail if os.path.exists('/proc/bus/pci'): _cmds += ['lspci'] # Add additional last resort commands if osdata['kernel'] in skip_cmds: _cmds = () # Quick backout for BrandZ (Solaris LX Branded zones) # Don't waste time trying other commands to detect the virtual grain if HAS_UNAME and osdata['kernel'] == 'Linux' and 'BrandZ virtual linux' in os.uname(): grains['virtual'] = 'zone' return grains failed_commands = set() for command in _cmds: args = [] if osdata['kernel'] == 'Darwin': command = 'system_profiler' args = ['SPDisplaysDataType'] elif osdata['kernel'] == 'SunOS': virtinfo = salt.utils.path.which('virtinfo') if virtinfo: try: ret = __salt__['cmd.run_all']('{0} -a'.format(virtinfo)) except salt.exceptions.CommandExecutionError: if salt.log.is_logging_configured(): failed_commands.add(virtinfo) else: if ret['stdout'].endswith('not supported'): command = 'prtdiag' else: command = 'virtinfo' else: command = 'prtdiag' cmd = salt.utils.path.which(command) if not cmd: continue cmd = '{0} {1}'.format(cmd, ' '.join(args)) try: ret = __salt__['cmd.run_all'](cmd) if ret['retcode'] > 0: if salt.log.is_logging_configured(): # systemd-detect-virt always returns > 0 on non-virtualized # systems # prtdiag only works in the global zone, skip if it fails if salt.utils.platform.is_windows() or 'systemd-detect-virt' in cmd or 'prtdiag' in cmd: continue failed_commands.add(command) continue except salt.exceptions.CommandExecutionError: if salt.log.is_logging_configured(): if salt.utils.platform.is_windows(): continue failed_commands.add(command) continue output = ret['stdout'] if command == "system_profiler": macoutput = output.lower() if '0x1ab8' in macoutput: grains['virtual'] = 'Parallels' if 'parallels' in macoutput: grains['virtual'] = 'Parallels' if 'vmware' in macoutput: grains['virtual'] = 'VMware' if '0x15ad' in macoutput: grains['virtual'] = 'VMware' if 'virtualbox' in macoutput: grains['virtual'] = 'VirtualBox' # Break out of the loop so the next log message is not issued break elif command == 'systemd-detect-virt': if output in ('qemu', 'kvm', 'oracle', 'xen', 'bochs', 'chroot', 'uml', 'systemd-nspawn'): grains['virtual'] = output break elif 'vmware' in output: grains['virtual'] = 'VMware' break elif 'microsoft' in output: grains['virtual'] = 'VirtualPC' break elif 'lxc' in output: grains['virtual'] = 'LXC' break elif 'systemd-nspawn' in output: grains['virtual'] = 'LXC' break elif command == 'virt-what': try: output = output.splitlines()[-1] except IndexError: pass if output in ('kvm', 'qemu', 'uml', 'xen', 'lxc'): grains['virtual'] = output break elif 'vmware' in output: grains['virtual'] = 'VMware' break elif 'parallels' in output: grains['virtual'] = 'Parallels' break elif 'hyperv' in output: grains['virtual'] = 'HyperV' break elif command == 'dmidecode': # Product Name: VirtualBox if 'Vendor: QEMU' in output: # FIXME: Make this detect between kvm or qemu grains['virtual'] = 'kvm' if 'Manufacturer: QEMU' in output: grains['virtual'] = 'kvm' if 'Vendor: Bochs' in output: grains['virtual'] = 'kvm' if 'Manufacturer: Bochs' in output: grains['virtual'] = 'kvm' if 'BHYVE' in output: grains['virtual'] = 'bhyve' # Product Name: (oVirt) www.ovirt.org # Red Hat Community virtualization Project based on kvm elif 'Manufacturer: oVirt' in output: grains['virtual'] = 'kvm' grains['virtual_subtype'] = 'ovirt' # Red Hat Enterprise Virtualization elif 'Product Name: RHEV Hypervisor' in output: grains['virtual'] = 'kvm' grains['virtual_subtype'] = 'rhev' elif 'VirtualBox' in output: grains['virtual'] = 'VirtualBox' # Product Name: VMware Virtual Platform elif 'VMware' in output: grains['virtual'] = 'VMware' # Manufacturer: Microsoft Corporation # Product Name: Virtual Machine elif ': Microsoft' in output and 'Virtual Machine' in output: grains['virtual'] = 'VirtualPC' # Manufacturer: Parallels Software International Inc. elif 'Parallels Software' in output: grains['virtual'] = 'Parallels' elif 'Manufacturer: Google' in output: grains['virtual'] = 'kvm' # Proxmox KVM elif 'Vendor: SeaBIOS' in output: grains['virtual'] = 'kvm' # Break out of the loop, lspci parsing is not necessary break elif command == 'lspci': # dmidecode not available or the user does not have the necessary # permissions model = output.lower() if 'vmware' in model: grains['virtual'] = 'VMware' # 00:04.0 System peripheral: InnoTek Systemberatung GmbH # VirtualBox Guest Service elif 'virtualbox' in model: grains['virtual'] = 'VirtualBox' elif 'qemu' in model: grains['virtual'] = 'kvm' elif 'virtio' in model: grains['virtual'] = 'kvm' # Break out of the loop so the next log message is not issued break elif command == 'prtdiag': model = output.lower().split("\n")[0] if 'vmware' in model: grains['virtual'] = 'VMware' elif 'virtualbox' in model: grains['virtual'] = 'VirtualBox' elif 'qemu' in model: grains['virtual'] = 'kvm' elif 'joyent smartdc hvm' in model: grains['virtual'] = 'kvm' break elif command == 'virtinfo': grains['virtual'] = 'LDOM' break choices = ('Linux', 'HP-UX') isdir = os.path.isdir sysctl = salt.utils.path.which('sysctl') if osdata['kernel'] in choices: if os.path.isdir('/proc'): try: self_root = os.stat('/') init_root = os.stat('/proc/1/root/.') if self_root != init_root: grains['virtual_subtype'] = 'chroot' except (IOError, OSError): pass if isdir('/proc/vz'): if os.path.isfile('/proc/vz/version'): grains['virtual'] = 'openvzhn' elif os.path.isfile('/proc/vz/veinfo'): grains['virtual'] = 'openvzve' # a posteriori, it's expected for these to have failed: failed_commands.discard('lspci') failed_commands.discard('dmidecode') # Provide additional detection for OpenVZ if os.path.isfile('/proc/self/status'): with salt.utils.files.fopen('/proc/self/status') as status_file: vz_re = re.compile(r'^envID:\s+(\d+)$') for line in status_file: vz_match = vz_re.match(line.rstrip('\n')) if vz_match and int(vz_match.groups()[0]) != 0: grains['virtual'] = 'openvzve' elif vz_match and int(vz_match.groups()[0]) == 0: grains['virtual'] = 'openvzhn' if isdir('/proc/sys/xen') or \ isdir('/sys/bus/xen') or isdir('/proc/xen'): if os.path.isfile('/proc/xen/xsd_kva'): # Tested on CentOS 5.3 / 2.6.18-194.26.1.el5xen # Tested on CentOS 5.4 / 2.6.18-164.15.1.el5xen grains['virtual_subtype'] = 'Xen Dom0' else: if osdata.get('productname', '') == 'HVM domU': # Requires dmidecode! grains['virtual_subtype'] = 'Xen HVM DomU' elif os.path.isfile('/proc/xen/capabilities') and \ os.access('/proc/xen/capabilities', os.R_OK): with salt.utils.files.fopen('/proc/xen/capabilities') as fhr: if 'control_d' not in fhr.read(): # Tested on CentOS 5.5 / 2.6.18-194.3.1.el5xen grains['virtual_subtype'] = 'Xen PV DomU' else: # Shouldn't get to this, but just in case grains['virtual_subtype'] = 'Xen Dom0' # Tested on Fedora 10 / 2.6.27.30-170.2.82 with xen # Tested on Fedora 15 / 2.6.41.4-1 without running xen elif isdir('/sys/bus/xen'): if 'xen:' in __salt__['cmd.run']('dmesg').lower(): grains['virtual_subtype'] = 'Xen PV DomU' elif os.path.isfile('/sys/bus/xen/drivers/xenconsole'): # An actual DomU will have the xenconsole driver grains['virtual_subtype'] = 'Xen PV DomU' # If a Dom0 or DomU was detected, obviously this is xen if 'dom' in grains.get('virtual_subtype', '').lower(): grains['virtual'] = 'xen' # Check container type after hypervisors, to avoid variable overwrite on containers running in virtual environment. if os.path.isfile('/proc/1/cgroup'): try: with salt.utils.files.fopen('/proc/1/cgroup', 'r') as fhr: fhr_contents = fhr.read() if ':/lxc/' in fhr_contents: grains['virtual_subtype'] = 'LXC' elif ':/kubepods/' in fhr_contents: grains['virtual_subtype'] = 'kubernetes' elif ':/libpod_parent/' in fhr_contents: grains['virtual_subtype'] = 'libpod' else: if any(x in fhr_contents for x in (':/system.slice/docker', ':/docker/', ':/docker-ce/')): grains['virtual_subtype'] = 'Docker' except IOError: pass if os.path.isfile('/proc/cpuinfo'): with salt.utils.files.fopen('/proc/cpuinfo', 'r') as fhr: if 'QEMU Virtual CPU' in fhr.read(): grains['virtual'] = 'kvm' if os.path.isfile('/sys/devices/virtual/dmi/id/product_name'): try: with salt.utils.files.fopen('/sys/devices/virtual/dmi/id/product_name', 'r') as fhr: output = salt.utils.stringutils.to_unicode(fhr.read(), errors='replace') if 'VirtualBox' in output: grains['virtual'] = 'VirtualBox' elif 'RHEV Hypervisor' in output: grains['virtual'] = 'kvm' grains['virtual_subtype'] = 'rhev' elif 'oVirt Node' in output: grains['virtual'] = 'kvm' grains['virtual_subtype'] = 'ovirt' elif 'Google' in output: grains['virtual'] = 'gce' elif 'BHYVE' in output: grains['virtual'] = 'bhyve' except IOError: pass elif osdata['kernel'] == 'FreeBSD': kenv = salt.utils.path.which('kenv') if kenv: product = __salt__['cmd.run']( '{0} smbios.system.product'.format(kenv) ) maker = __salt__['cmd.run']( '{0} smbios.system.maker'.format(kenv) ) if product.startswith('VMware'): grains['virtual'] = 'VMware' if product.startswith('VirtualBox'): grains['virtual'] = 'VirtualBox' if maker.startswith('Xen'): grains['virtual_subtype'] = '{0} {1}'.format(maker, product) grains['virtual'] = 'xen' if maker.startswith('Microsoft') and product.startswith('Virtual'): grains['virtual'] = 'VirtualPC' if maker.startswith('OpenStack'): grains['virtual'] = 'OpenStack' if maker.startswith('Bochs'): grains['virtual'] = 'kvm' if sysctl: hv_vendor = __salt__['cmd.run']('{0} hw.hv_vendor'.format(sysctl)) model = __salt__['cmd.run']('{0} hw.model'.format(sysctl)) jail = __salt__['cmd.run']( '{0} -n security.jail.jailed'.format(sysctl) ) if 'bhyve' in hv_vendor: grains['virtual'] = 'bhyve' if jail == '1': grains['virtual_subtype'] = 'jail' if 'QEMU Virtual CPU' in model: grains['virtual'] = 'kvm' elif osdata['kernel'] == 'OpenBSD': if 'manufacturer' in osdata: if osdata['manufacturer'] in ['QEMU', 'Red Hat', 'Joyent']: grains['virtual'] = 'kvm' if osdata['manufacturer'] == 'OpenBSD': grains['virtual'] = 'vmm' elif osdata['kernel'] == 'SunOS': if grains['virtual'] == 'LDOM': roles = [] for role in ('control', 'io', 'root', 'service'): subtype_cmd = '{0} -c current get -H -o value {1}-role'.format(cmd, role) ret = __salt__['cmd.run_all']('{0}'.format(subtype_cmd)) if ret['stdout'] == 'true': roles.append(role) if roles: grains['virtual_subtype'] = roles else: # Check if it's a "regular" zone. (i.e. Solaris 10/11 zone) zonename = salt.utils.path.which('zonename') if zonename: zone = __salt__['cmd.run']('{0}'.format(zonename)) if zone != 'global': grains['virtual'] = 'zone' # Check if it's a branded zone (i.e. Solaris 8/9 zone) if isdir('/.SUNWnative'): grains['virtual'] = 'zone' elif osdata['kernel'] == 'NetBSD': if sysctl: if 'QEMU Virtual CPU' in __salt__['cmd.run']( '{0} -n machdep.cpu_brand'.format(sysctl)): grains['virtual'] = 'kvm' elif 'invalid' not in __salt__['cmd.run']( '{0} -n machdep.xen.suspend'.format(sysctl)): grains['virtual'] = 'Xen PV DomU' elif 'VMware' in __salt__['cmd.run']( '{0} -n machdep.dmi.system-vendor'.format(sysctl)): grains['virtual'] = 'VMware' # NetBSD has Xen dom0 support elif __salt__['cmd.run']( '{0} -n machdep.idle-mechanism'.format(sysctl)) == 'xen': if os.path.isfile('/var/run/xenconsoled.pid'): grains['virtual_subtype'] = 'Xen Dom0' for command in failed_commands: log.info( "Although '%s' was found in path, the current user " 'cannot execute it. Grains output might not be ' 'accurate.', command ) return grains def _virtual_hv(osdata): ''' Returns detailed hypervisor information from sysfs Currently this seems to be used only by Xen ''' grains = {} # Bail early if we're not running on Xen try: if 'xen' not in osdata['virtual']: return grains except KeyError: return grains # Try to get the exact hypervisor version from sysfs try: version = {} for fn in ('major', 'minor', 'extra'): with salt.utils.files.fopen('/sys/hypervisor/version/{}'.format(fn), 'r') as fhr: version[fn] = salt.utils.stringutils.to_unicode(fhr.read().strip()) grains['virtual_hv_version'] = '{}.{}{}'.format(version['major'], version['minor'], version['extra']) grains['virtual_hv_version_info'] = [version['major'], version['minor'], version['extra']] except (IOError, OSError, KeyError): pass # Try to read and decode the supported feature set of the hypervisor # Based on https://github.com/brendangregg/Misc/blob/master/xen/xen-features.py # Table data from include/xen/interface/features.h xen_feature_table = {0: 'writable_page_tables', 1: 'writable_descriptor_tables', 2: 'auto_translated_physmap', 3: 'supervisor_mode_kernel', 4: 'pae_pgdir_above_4gb', 5: 'mmu_pt_update_preserve_ad', 7: 'gnttab_map_avail_bits', 8: 'hvm_callback_vector', 9: 'hvm_safe_pvclock', 10: 'hvm_pirqs', 11: 'dom0', 12: 'grant_map_identity', 13: 'memory_op_vnode_supported', 14: 'ARM_SMCCC_supported'} try: with salt.utils.files.fopen('/sys/hypervisor/properties/features', 'r') as fhr: features = salt.utils.stringutils.to_unicode(fhr.read().strip()) enabled_features = [] for bit, feat in six.iteritems(xen_feature_table): if int(features, 16) & (1 << bit): enabled_features.append(feat) grains['virtual_hv_features'] = features grains['virtual_hv_features_list'] = enabled_features except (IOError, OSError, KeyError): pass return grains def _ps(osdata): ''' Return the ps grain ''' grains = {} bsd_choices = ('FreeBSD', 'NetBSD', 'OpenBSD', 'MacOS') if osdata['os'] in bsd_choices: grains['ps'] = 'ps auxwww' elif osdata['os_family'] == 'Solaris': grains['ps'] = '/usr/ucb/ps auxwww' elif osdata['os'] == 'Windows': grains['ps'] = 'tasklist.exe' elif osdata.get('virtual', '') == 'openvzhn': grains['ps'] = ( 'ps -fH -p $(grep -l \"^envID:[[:space:]]*0\\$\" ' '/proc/[0-9]*/status | sed -e \"s=/proc/\\([0-9]*\\)/.*=\\1=\") ' '| awk \'{ $7=\"\"; print }\'' ) elif osdata['os_family'] == 'AIX': grains['ps'] = '/usr/bin/ps auxww' elif osdata['os_family'] == 'NILinuxRT': grains['ps'] = 'ps -o user,pid,ppid,tty,time,comm' else: grains['ps'] = 'ps -efHww' return grains def _clean_value(key, val): ''' Clean out well-known bogus values. If it isn't clean (for example has value 'None'), return None. Otherwise, return the original value. NOTE: This logic also exists in the smbios module. This function is for use when not using smbios to retrieve the value. ''' if (val is None or not val or re.match('none', val, flags=re.IGNORECASE)): return None elif 'uuid' in key: # Try each version (1-5) of RFC4122 to check if it's actually a UUID for uuidver in range(1, 5): try: uuid.UUID(val, version=uuidver) return val except ValueError: continue log.trace('HW %s value %s is an invalid UUID', key, val.replace('\n', ' ')) return None elif re.search('serial|part|version', key): # 'To be filled by O.E.M. # 'Not applicable' etc. # 'Not specified' etc. # 0000000, 1234567 etc. # begone! if (re.match(r'^[0]+$', val) or re.match(r'[0]?1234567[8]?[9]?[0]?', val) or re.search(r'sernum|part[_-]?number|specified|filled|applicable', val, flags=re.IGNORECASE)): return None elif re.search('asset|manufacturer', key): # AssetTag0. Manufacturer04. Begone. if re.search(r'manufacturer|to be filled|available|asset|^no(ne|t)', val, flags=re.IGNORECASE): return None else: # map unspecified, undefined, unknown & whatever to None if (re.search(r'to be filled', val, flags=re.IGNORECASE) or re.search(r'un(known|specified)|no(t|ne)? (asset|provided|defined|available|present|specified)', val, flags=re.IGNORECASE)): return None return val def _windows_platform_data(): ''' Use the platform module for as much as we can. ''' # Provides: # kernelrelease # kernelversion # osversion # osrelease # osservicepack # osmanufacturer # manufacturer # productname # biosversion # serialnumber # osfullname # timezone # windowsdomain # windowsdomaintype # motherboard.productname # motherboard.serialnumber # virtual if not HAS_WMI: return {} with salt.utils.winapi.Com(): wmi_c = wmi.WMI() # http://msdn.microsoft.com/en-us/library/windows/desktop/aa394102%28v=vs.85%29.aspx systeminfo = wmi_c.Win32_ComputerSystem()[0] # https://msdn.microsoft.com/en-us/library/aa394239(v=vs.85).aspx osinfo = wmi_c.Win32_OperatingSystem()[0] # http://msdn.microsoft.com/en-us/library/windows/desktop/aa394077(v=vs.85).aspx biosinfo = wmi_c.Win32_BIOS()[0] # http://msdn.microsoft.com/en-us/library/windows/desktop/aa394498(v=vs.85).aspx timeinfo = wmi_c.Win32_TimeZone()[0] # http://msdn.microsoft.com/en-us/library/windows/desktop/aa394072(v=vs.85).aspx motherboard = {'product': None, 'serial': None} try: motherboardinfo = wmi_c.Win32_BaseBoard()[0] motherboard['product'] = motherboardinfo.Product motherboard['serial'] = motherboardinfo.SerialNumber except IndexError: log.debug('Motherboard info not available on this system') os_release = platform.release() kernel_version = platform.version() info = salt.utils.win_osinfo.get_os_version_info() net_info = salt.utils.win_osinfo.get_join_info() service_pack = None if info['ServicePackMajor'] > 0: service_pack = ''.join(['SP', six.text_type(info['ServicePackMajor'])]) # This creates the osrelease grain based on the Windows Operating # System Product Name. As long as Microsoft maintains a similar format # this should be future proof version = 'Unknown' release = '' if 'Server' in osinfo.Caption: for item in osinfo.Caption.split(' '): # If it's all digits, then it's version if re.match(r'\d+', item): version = item # If it starts with R and then numbers, it's the release # ie: R2 if re.match(r'^R\d+$', item): release = item os_release = '{0}Server{1}'.format(version, release) else: for item in osinfo.Caption.split(' '): # If it's a number, decimal number, Thin or Vista, then it's the # version if re.match(r'^(\d+(\.\d+)?)|Thin|Vista$', item): version = item os_release = version grains = { 'kernelrelease': _clean_value('kernelrelease', osinfo.Version), 'kernelversion': _clean_value('kernelversion', kernel_version), 'osversion': _clean_value('osversion', osinfo.Version), 'osrelease': _clean_value('osrelease', os_release), 'osservicepack': _clean_value('osservicepack', service_pack), 'osmanufacturer': _clean_value('osmanufacturer', osinfo.Manufacturer), 'manufacturer': _clean_value('manufacturer', systeminfo.Manufacturer), 'productname': _clean_value('productname', systeminfo.Model), # bios name had a bunch of whitespace appended to it in my testing # 'PhoenixBIOS 4.0 Release 6.0 ' 'biosversion': _clean_value('biosversion', biosinfo.Name.strip()), 'serialnumber': _clean_value('serialnumber', biosinfo.SerialNumber), 'osfullname': _clean_value('osfullname', osinfo.Caption), 'timezone': _clean_value('timezone', timeinfo.Description), 'windowsdomain': _clean_value('windowsdomain', net_info['Domain']), 'windowsdomaintype': _clean_value('windowsdomaintype', net_info['DomainType']), 'motherboard': { 'productname': _clean_value('motherboard.productname', motherboard['product']), 'serialnumber': _clean_value('motherboard.serialnumber', motherboard['serial']), } } # test for virtualized environments # I only had VMware available so the rest are unvalidated if 'VRTUAL' in biosinfo.Version: # (not a typo) grains['virtual'] = 'HyperV' elif 'A M I' in biosinfo.Version: grains['virtual'] = 'VirtualPC' elif 'VMware' in systeminfo.Model: grains['virtual'] = 'VMware' elif 'VirtualBox' in systeminfo.Model: grains['virtual'] = 'VirtualBox' elif 'Xen' in biosinfo.Version: grains['virtual'] = 'Xen' if 'HVM domU' in systeminfo.Model: grains['virtual_subtype'] = 'HVM domU' elif 'OpenStack' in systeminfo.Model: grains['virtual'] = 'OpenStack' return grains def _osx_platform_data(): ''' Additional data for macOS systems Returns: A dictionary containing values for the following: - model_name - boot_rom_version - smc_version - system_serialnumber ''' cmd = 'system_profiler SPHardwareDataType' hardware = __salt__['cmd.run'](cmd) grains = {} for line in hardware.splitlines(): field_name, _, field_val = line.partition(': ') if field_name.strip() == "Model Name": key = 'model_name' grains[key] = _clean_value(key, field_val) if field_name.strip() == "Boot ROM Version": key = 'boot_rom_version' grains[key] = _clean_value(key, field_val) if field_name.strip() == "SMC Version (system)": key = 'smc_version' grains[key] = _clean_value(key, field_val) if field_name.strip() == "Serial Number (system)": key = 'system_serialnumber' grains[key] = _clean_value(key, field_val) return grains def id_(): ''' Return the id ''' return {'id': __opts__.get('id', '')} _REPLACE_LINUX_RE = re.compile(r'\W(?:gnu/)?linux', re.IGNORECASE) # This maps (at most) the first ten characters (no spaces, lowercased) of # 'osfullname' to the 'os' grain that Salt traditionally uses. # Please see os_data() and _supported_dists. # If your system is not detecting properly it likely needs an entry here. _OS_NAME_MAP = { 'redhatente': 'RedHat', 'gentoobase': 'Gentoo', 'archarm': 'Arch ARM', 'arch': 'Arch', 'debian': 'Debian', 'raspbian': 'Raspbian', 'fedoraremi': 'Fedora', 'chapeau': 'Chapeau', 'korora': 'Korora', 'amazonami': 'Amazon', 'alt': 'ALT', 'enterprise': 'OEL', 'oracleserv': 'OEL', 'cloudserve': 'CloudLinux', 'cloudlinux': 'CloudLinux', 'pidora': 'Fedora', 'scientific': 'ScientificLinux', 'synology': 'Synology', 'nilrt': 'NILinuxRT', 'poky': 'Poky', 'manjaro': 'Manjaro', 'manjarolin': 'Manjaro', 'univention': 'Univention', 'antergos': 'Antergos', 'sles': 'SUSE', 'void': 'Void', 'slesexpand': 'RES', 'linuxmint': 'Mint', 'neon': 'KDE neon', } # Map the 'os' grain to the 'os_family' grain # These should always be capitalized entries as the lookup comes # post-_OS_NAME_MAP. If your system is having trouble with detection, please # make sure that the 'os' grain is capitalized and working correctly first. _OS_FAMILY_MAP = { 'Ubuntu': 'Debian', 'Fedora': 'RedHat', 'Chapeau': 'RedHat', 'Korora': 'RedHat', 'FedBerry': 'RedHat', 'CentOS': 'RedHat', 'GoOSe': 'RedHat', 'Scientific': 'RedHat', 'Amazon': 'RedHat', 'CloudLinux': 'RedHat', 'OVS': 'RedHat', 'OEL': 'RedHat', 'XCP': 'RedHat', 'XCP-ng': 'RedHat', 'XenServer': 'RedHat', 'RES': 'RedHat', 'Sangoma': 'RedHat', 'Mandrake': 'Mandriva', 'ESXi': 'VMware', 'Mint': 'Debian', 'VMwareESX': 'VMware', 'Bluewhite64': 'Bluewhite', 'Slamd64': 'Slackware', 'SLES': 'Suse', 'SUSE Enterprise Server': 'Suse', 'SUSE Enterprise Server': 'Suse', 'SLED': 'Suse', 'openSUSE': 'Suse', 'SUSE': 'Suse', 'openSUSE Leap': 'Suse', 'openSUSE Tumbleweed': 'Suse', 'SLES_SAP': 'Suse', 'Solaris': 'Solaris', 'SmartOS': 'Solaris', 'OmniOS': 'Solaris', 'OpenIndiana Development': 'Solaris', 'OpenIndiana': 'Solaris', 'OpenSolaris Development': 'Solaris', 'OpenSolaris': 'Solaris', 'Oracle Solaris': 'Solaris', 'Arch ARM': 'Arch', 'Manjaro': 'Arch', 'Antergos': 'Arch', 'ALT': 'RedHat', 'Trisquel': 'Debian', 'GCEL': 'Debian', 'Linaro': 'Debian', 'elementary OS': 'Debian', 'elementary': 'Debian', 'Univention': 'Debian', 'ScientificLinux': 'RedHat', 'Raspbian': 'Debian', 'Devuan': 'Debian', 'antiX': 'Debian', 'Kali': 'Debian', 'neon': 'Debian', 'Cumulus': 'Debian', 'Deepin': 'Debian', 'NILinuxRT': 'NILinuxRT', 'KDE neon': 'Debian', 'Void': 'Void', 'IDMS': 'Debian', 'Funtoo': 'Gentoo', 'AIX': 'AIX', 'TurnKey': 'Debian', } # Matches any possible format: # DISTRIB_ID="Ubuntu" # DISTRIB_ID='Mageia' # DISTRIB_ID=Fedora # DISTRIB_RELEASE='10.10' # DISTRIB_CODENAME='squeeze' # DISTRIB_DESCRIPTION='Ubuntu 10.10' _LSB_REGEX = re.compile(( '^(DISTRIB_(?:ID|RELEASE|CODENAME|DESCRIPTION))=(?:\'|")?' '([\\w\\s\\.\\-_]+)(?:\'|")?' )) def _linux_bin_exists(binary): ''' Does a binary exist in linux (depends on which, type, or whereis) ''' for search_cmd in ('which', 'type -ap'): try: return __salt__['cmd.retcode']( '{0} {1}'.format(search_cmd, binary) ) == 0 except salt.exceptions.CommandExecutionError: pass try: return len(__salt__['cmd.run_all']( 'whereis -b {0}'.format(binary) )['stdout'].split()) > 1 except salt.exceptions.CommandExecutionError: return False def _get_interfaces(): ''' Provide a dict of the connected interfaces and their ip addresses ''' global _INTERFACES if not _INTERFACES: _INTERFACES = salt.utils.network.interfaces() return _INTERFACES def _parse_lsb_release(): ret = {} try: log.trace('Attempting to parse /etc/lsb-release') with salt.utils.files.fopen('/etc/lsb-release') as ifile: for line in ifile: try: key, value = _LSB_REGEX.match(line.rstrip('\n')).groups()[:2] except AttributeError: pass else: # Adds lsb_distrib_{id,release,codename,description} ret['lsb_{0}'.format(key.lower())] = value.rstrip() except (IOError, OSError) as exc: log.trace('Failed to parse /etc/lsb-release: %s', exc) return ret def _parse_os_release(*os_release_files): ''' Parse os-release and return a parameter dictionary See http://www.freedesktop.org/software/systemd/man/os-release.html for specification of the file format. ''' ret = {} for filename in os_release_files: try: with salt.utils.files.fopen(filename) as ifile: regex = re.compile('^([\\w]+)=(?:\'|")?(.*?)(?:\'|")?$') for line in ifile: match = regex.match(line.strip()) if match: # Shell special characters ("$", quotes, backslash, # backtick) are escaped with backslashes ret[match.group(1)] = re.sub( r'\\([$"\'\\`])', r'\1', match.group(2) ) break except (IOError, OSError): pass return ret def _parse_cpe_name(cpe): ''' Parse CPE_NAME data from the os-release Info: https://csrc.nist.gov/projects/security-content-automation-protocol/scap-specifications/cpe :param cpe: :return: ''' part = { 'o': 'operating system', 'h': 'hardware', 'a': 'application', } ret = {} cpe = (cpe or '').split(':') if len(cpe) > 4 and cpe[0] == 'cpe': if cpe[1].startswith('/'): # WFN to URI ret['vendor'], ret['product'], ret['version'] = cpe[2:5] ret['phase'] = cpe[5] if len(cpe) > 5 else None ret['part'] = part.get(cpe[1][1:]) elif len(cpe) == 13 and cpe[1] == '2.3': # WFN to a string ret['vendor'], ret['product'], ret['version'], ret['phase'] = [x if x != '*' else None for x in cpe[3:7]] ret['part'] = part.get(cpe[2]) return ret def os_data(): ''' Return grains pertaining to the operating system ''' grains = { 'num_gpus': 0, 'gpus': [], } # Windows Server 2008 64-bit # ('Windows', 'MINIONNAME', '2008ServerR2', '6.1.7601', 'AMD64', # 'Intel64 Fam ily 6 Model 23 Stepping 6, GenuineIntel') # Ubuntu 10.04 # ('Linux', 'MINIONNAME', '2.6.32-38-server', # '#83-Ubuntu SMP Wed Jan 4 11:26:59 UTC 2012', 'x86_64', '') # pylint: disable=unpacking-non-sequence (grains['kernel'], grains['nodename'], grains['kernelrelease'], grains['kernelversion'], grains['cpuarch'], _) = platform.uname() # pylint: enable=unpacking-non-sequence if salt.utils.platform.is_proxy(): grains['kernel'] = 'proxy' grains['kernelrelease'] = 'proxy' grains['kernelversion'] = 'proxy' grains['osrelease'] = 'proxy' grains['os'] = 'proxy' grains['os_family'] = 'proxy' grains['osfullname'] = 'proxy' elif salt.utils.platform.is_windows(): grains['os'] = 'Windows' grains['os_family'] = 'Windows' grains.update(_memdata(grains)) grains.update(_windows_platform_data()) grains.update(_windows_cpudata()) grains.update(_windows_virtual(grains)) grains.update(_ps(grains)) if 'Server' in grains['osrelease']: osrelease_info = grains['osrelease'].split('Server', 1) osrelease_info[1] = osrelease_info[1].lstrip('R') else: osrelease_info = grains['osrelease'].split('.') for idx, value in enumerate(osrelease_info): if not value.isdigit(): continue osrelease_info[idx] = int(value) grains['osrelease_info'] = tuple(osrelease_info) grains['osfinger'] = '{os}-{ver}'.format( os=grains['os'], ver=grains['osrelease']) grains['init'] = 'Windows' return grains elif salt.utils.platform.is_linux(): # Add SELinux grain, if you have it if _linux_bin_exists('selinuxenabled'): log.trace('Adding selinux grains') grains['selinux'] = {} grains['selinux']['enabled'] = __salt__['cmd.retcode']( 'selinuxenabled' ) == 0 if _linux_bin_exists('getenforce'): grains['selinux']['enforced'] = __salt__['cmd.run']( 'getenforce' ).strip() # Add systemd grain, if you have it if _linux_bin_exists('systemctl') and _linux_bin_exists('localectl'): log.trace('Adding systemd grains') grains['systemd'] = {} systemd_info = __salt__['cmd.run']( 'systemctl --version' ).splitlines() grains['systemd']['version'] = systemd_info[0].split()[1] grains['systemd']['features'] = systemd_info[1] # Add init grain grains['init'] = 'unknown' log.trace('Adding init grain') try: os.stat('/run/systemd/system') grains['init'] = 'systemd' except (OSError, IOError): try: with salt.utils.files.fopen('/proc/1/cmdline') as fhr: init_cmdline = fhr.read().replace('\x00', ' ').split() except (IOError, OSError): pass else: try: init_bin = salt.utils.path.which(init_cmdline[0]) except IndexError: # Emtpy init_cmdline init_bin = None log.warning('Unable to fetch data from /proc/1/cmdline') if init_bin is not None and init_bin.endswith('bin/init'): supported_inits = (b'upstart', b'sysvinit', b'systemd') edge_len = max(len(x) for x in supported_inits) - 1 try: buf_size = __opts__['file_buffer_size'] except KeyError: # Default to the value of file_buffer_size for the minion buf_size = 262144 try: with salt.utils.files.fopen(init_bin, 'rb') as fp_: edge = b'' buf = fp_.read(buf_size).lower() while buf: buf = edge + buf for item in supported_inits: if item in buf: if six.PY3: item = item.decode('utf-8') grains['init'] = item buf = b'' break edge = buf[-edge_len:] buf = fp_.read(buf_size).lower() except (IOError, OSError) as exc: log.error( 'Unable to read from init_bin (%s): %s', init_bin, exc ) elif salt.utils.path.which('supervisord') in init_cmdline: grains['init'] = 'supervisord' elif salt.utils.path.which('dumb-init') in init_cmdline: # https://github.com/Yelp/dumb-init grains['init'] = 'dumb-init' elif salt.utils.path.which('tini') in init_cmdline: # https://github.com/krallin/tini grains['init'] = 'tini' elif init_cmdline == ['runit']: grains['init'] = 'runit' elif '/sbin/my_init' in init_cmdline: # Phusion Base docker container use runit for srv mgmt, but # my_init as pid1 grains['init'] = 'runit' else: log.debug( 'Could not determine init system from command line: (%s)', ' '.join(init_cmdline) ) # Add lsb grains on any distro with lsb-release. Note that this import # can fail on systems with lsb-release installed if the system package # does not install the python package for the python interpreter used by # Salt (i.e. python2 or python3) try: log.trace('Getting lsb_release distro information') import lsb_release # pylint: disable=import-error release = lsb_release.get_distro_information() for key, value in six.iteritems(release): key = key.lower() lsb_param = 'lsb_{0}{1}'.format( '' if key.startswith('distrib_') else 'distrib_', key ) grains[lsb_param] = value # Catch a NameError to workaround possible breakage in lsb_release # See https://github.com/saltstack/salt/issues/37867 except (ImportError, NameError): # if the python library isn't available, try to parse # /etc/lsb-release using regex log.trace('lsb_release python bindings not available') grains.update(_parse_lsb_release()) if grains.get('lsb_distrib_description', '').lower().startswith('antergos'): # Antergos incorrectly configures their /etc/lsb-release, # setting the DISTRIB_ID to "Arch". This causes the "os" grain # to be incorrectly set to "Arch". grains['osfullname'] = 'Antergos Linux' elif 'lsb_distrib_id' not in grains: log.trace( 'Failed to get lsb_distrib_id, trying to parse os-release' ) os_release = _parse_os_release('/etc/os-release', '/usr/lib/os-release') if os_release: if 'NAME' in os_release: grains['lsb_distrib_id'] = os_release['NAME'].strip() if 'VERSION_ID' in os_release: grains['lsb_distrib_release'] = os_release['VERSION_ID'] if 'VERSION_CODENAME' in os_release: grains['lsb_distrib_codename'] = os_release['VERSION_CODENAME'] elif 'PRETTY_NAME' in os_release: codename = os_release['PRETTY_NAME'] # https://github.com/saltstack/salt/issues/44108 if os_release['ID'] == 'debian': codename_match = re.search(r'\((\w+)\)$', codename) if codename_match: codename = codename_match.group(1) grains['lsb_distrib_codename'] = codename if 'CPE_NAME' in os_release: cpe = _parse_cpe_name(os_release['CPE_NAME']) if not cpe: log.error('Broken CPE_NAME format in /etc/os-release!') elif cpe.get('vendor', '').lower() in ['suse', 'opensuse']: grains['os'] = "SUSE" # openSUSE `osfullname` grain normalization if os_release.get("NAME") == "openSUSE Leap": grains['osfullname'] = "Leap" elif os_release.get("VERSION") == "Tumbleweed": grains['osfullname'] = os_release["VERSION"] # Override VERSION_ID, if CPE_NAME around if cpe.get('version') and cpe.get('vendor') == 'opensuse': # Keep VERSION_ID for SLES grains['lsb_distrib_release'] = cpe['version'] elif os.path.isfile('/etc/SuSE-release'): log.trace('Parsing distrib info from /etc/SuSE-release') grains['lsb_distrib_id'] = 'SUSE' version = '' patch = '' with salt.utils.files.fopen('/etc/SuSE-release') as fhr: for line in fhr: if 'enterprise' in line.lower(): grains['lsb_distrib_id'] = 'SLES' grains['lsb_distrib_codename'] = re.sub(r'\(.+\)', '', line).strip() elif 'version' in line.lower(): version = re.sub(r'[^0-9]', '', line) elif 'patchlevel' in line.lower(): patch = re.sub(r'[^0-9]', '', line) grains['lsb_distrib_release'] = version if patch: grains['lsb_distrib_release'] += '.' + patch patchstr = 'SP' + patch if grains['lsb_distrib_codename'] and patchstr not in grains['lsb_distrib_codename']: grains['lsb_distrib_codename'] += ' ' + patchstr if not grains.get('lsb_distrib_codename'): grains['lsb_distrib_codename'] = 'n.a' elif os.path.isfile('/etc/altlinux-release'): log.trace('Parsing distrib info from /etc/altlinux-release') # ALT Linux grains['lsb_distrib_id'] = 'altlinux' with salt.utils.files.fopen('/etc/altlinux-release') as ifile: # This file is symlinked to from: # /etc/fedora-release # /etc/redhat-release # /etc/system-release for line in ifile: # ALT Linux Sisyphus (unstable) comps = line.split() if comps[0] == 'ALT': grains['lsb_distrib_release'] = comps[2] grains['lsb_distrib_codename'] = \ comps[3].replace('(', '').replace(')', '') elif os.path.isfile('/etc/centos-release'): log.trace('Parsing distrib info from /etc/centos-release') # Maybe CentOS Linux; could also be SUSE Expanded Support. # SUSE ES has both, centos-release and redhat-release. if os.path.isfile('/etc/redhat-release'): with salt.utils.files.fopen('/etc/redhat-release') as ifile: for line in ifile: if "red hat enterprise linux server" in line.lower(): # This is a SUSE Expanded Support Rhel installation grains['lsb_distrib_id'] = 'RedHat' break grains.setdefault('lsb_distrib_id', 'CentOS') with salt.utils.files.fopen('/etc/centos-release') as ifile: for line in ifile: # Need to pull out the version and codename # in the case of custom content in /etc/centos-release find_release = re.compile(r'\d+\.\d+') find_codename = re.compile(r'(?<=\()(.*?)(?=\))') release = find_release.search(line) codename = find_codename.search(line) if release is not None: grains['lsb_distrib_release'] = release.group() if codename is not None: grains['lsb_distrib_codename'] = codename.group() elif os.path.isfile('/etc.defaults/VERSION') \ and os.path.isfile('/etc.defaults/synoinfo.conf'): grains['osfullname'] = 'Synology' log.trace( 'Parsing Synology distrib info from /etc/.defaults/VERSION' ) with salt.utils.files.fopen('/etc.defaults/VERSION', 'r') as fp_: synoinfo = {} for line in fp_: try: key, val = line.rstrip('\n').split('=') except ValueError: continue if key in ('majorversion', 'minorversion', 'buildnumber'): synoinfo[key] = val.strip('"') if len(synoinfo) != 3: log.warning( 'Unable to determine Synology version info. ' 'Please report this, as it is likely a bug.' ) else: grains['osrelease'] = ( '{majorversion}.{minorversion}-{buildnumber}' .format(**synoinfo) ) # Use the already intelligent platform module to get distro info # (though apparently it's not intelligent enough to strip quotes) log.trace( 'Getting OS name, release, and codename from ' 'distro.linux_distribution()' ) (osname, osrelease, oscodename) = \ [x.strip('"').strip("'") for x in linux_distribution(supported_dists=_supported_dists)] # Try to assign these three names based on the lsb info, they tend to # be more accurate than what python gets from /etc/DISTRO-release. # It's worth noting that Ubuntu has patched their Python distribution # so that linux_distribution() does the /etc/lsb-release parsing, but # we do it anyway here for the sake for full portability. if 'osfullname' not in grains: # If NI Linux RT distribution, set the grains['osfullname'] to 'nilrt' if grains.get('lsb_distrib_id', '').lower().startswith('nilrt'): grains['osfullname'] = 'nilrt' else: grains['osfullname'] = grains.get('lsb_distrib_id', osname).strip() if 'osrelease' not in grains: # NOTE: This is a workaround for CentOS 7 os-release bug # https://bugs.centos.org/view.php?id=8359 # /etc/os-release contains no minor distro release number so we fall back to parse # /etc/centos-release file instead. # Commit introducing this comment should be reverted after the upstream bug is released. if 'CentOS Linux 7' in grains.get('lsb_distrib_codename', ''): grains.pop('lsb_distrib_release', None) grains['osrelease'] = grains.get('lsb_distrib_release', osrelease).strip() grains['oscodename'] = grains.get('lsb_distrib_codename', '').strip() or oscodename if 'Red Hat' in grains['oscodename']: grains['oscodename'] = oscodename distroname = _REPLACE_LINUX_RE.sub('', grains['osfullname']).strip() # return the first ten characters with no spaces, lowercased shortname = distroname.replace(' ', '').lower()[:10] # this maps the long names from the /etc/DISTRO-release files to the # traditional short names that Salt has used. if 'os' not in grains: grains['os'] = _OS_NAME_MAP.get(shortname, distroname) grains.update(_linux_cpudata()) grains.update(_linux_gpu_data()) elif grains['kernel'] == 'SunOS': if salt.utils.platform.is_smartos(): # See https://github.com/joyent/smartos-live/issues/224 if HAS_UNAME: uname_v = os.uname()[3] # format: joyent_20161101T004406Z else: uname_v = os.name uname_v = uname_v[uname_v.index('_')+1:] grains['os'] = grains['osfullname'] = 'SmartOS' # store a parsed version of YYYY.MM.DD as osrelease grains['osrelease'] = ".".join([ uname_v.split('T')[0][0:4], uname_v.split('T')[0][4:6], uname_v.split('T')[0][6:8], ]) # store a untouched copy of the timestamp in osrelease_stamp grains['osrelease_stamp'] = uname_v elif os.path.isfile('/etc/release'): with salt.utils.files.fopen('/etc/release', 'r') as fp_: rel_data = fp_.read() try: release_re = re.compile( r'((?:Open|Oracle )?Solaris|OpenIndiana|OmniOS) (Development)?' r'\s*(\d+\.?\d*|v\d+)\s?[A-Z]*\s?(r\d+|\d+\/\d+|oi_\S+|snv_\S+)?' ) osname, development, osmajorrelease, osminorrelease = release_re.search(rel_data).groups() except AttributeError: # Set a blank osrelease grain and fallback to 'Solaris' # as the 'os' grain. grains['os'] = grains['osfullname'] = 'Solaris' grains['osrelease'] = '' else: if development is not None: osname = ' '.join((osname, development)) if HAS_UNAME: uname_v = os.uname()[3] else: uname_v = os.name grains['os'] = grains['osfullname'] = osname if osname in ['Oracle Solaris'] and uname_v.startswith(osmajorrelease): # Oracla Solars 11 and up have minor version in uname grains['osrelease'] = uname_v elif osname in ['OmniOS']: # OmniOS osrelease = [] osrelease.append(osmajorrelease[1:]) osrelease.append(osminorrelease[1:]) grains['osrelease'] = ".".join(osrelease) grains['osrelease_stamp'] = uname_v else: # Sun Solaris 10 and earlier/comparable osrelease = [] osrelease.append(osmajorrelease) if osminorrelease: osrelease.append(osminorrelease) grains['osrelease'] = ".".join(osrelease) grains['osrelease_stamp'] = uname_v grains.update(_sunos_cpudata()) elif grains['kernel'] == 'VMkernel': grains['os'] = 'ESXi' elif grains['kernel'] == 'Darwin': osrelease = __salt__['cmd.run']('sw_vers -productVersion') osname = __salt__['cmd.run']('sw_vers -productName') osbuild = __salt__['cmd.run']('sw_vers -buildVersion') grains['os'] = 'MacOS' grains['os_family'] = 'MacOS' grains['osfullname'] = "{0} {1}".format(osname, osrelease) grains['osrelease'] = osrelease grains['osbuild'] = osbuild grains['init'] = 'launchd' grains.update(_bsd_cpudata(grains)) grains.update(_osx_gpudata()) grains.update(_osx_platform_data()) elif grains['kernel'] == 'AIX': osrelease = __salt__['cmd.run']('oslevel') osrelease_techlevel = __salt__['cmd.run']('oslevel -r') osname = __salt__['cmd.run']('uname') grains['os'] = 'AIX' grains['osfullname'] = osname grains['osrelease'] = osrelease grains['osrelease_techlevel'] = osrelease_techlevel grains.update(_aix_cpudata()) else: grains['os'] = grains['kernel'] if grains['kernel'] == 'FreeBSD': try: grains['osrelease'] = __salt__['cmd.run']('freebsd-version -u').split('-')[0] except salt.exceptions.CommandExecutionError: # freebsd-version was introduced in 10.0. # derive osrelease from kernelversion prior to that grains['osrelease'] = grains['kernelrelease'].split('-')[0] grains.update(_bsd_cpudata(grains)) if grains['kernel'] in ('OpenBSD', 'NetBSD'): grains.update(_bsd_cpudata(grains)) grains['osrelease'] = grains['kernelrelease'].split('-')[0] if grains['kernel'] == 'NetBSD': grains.update(_netbsd_gpu_data()) if not grains['os']: grains['os'] = 'Unknown {0}'.format(grains['kernel']) grains['os_family'] = 'Unknown' else: # this assigns family names based on the os name # family defaults to the os name if not found grains['os_family'] = _OS_FAMILY_MAP.get(grains['os'], grains['os']) # Build the osarch grain. This grain will be used for platform-specific # considerations such as package management. Fall back to the CPU # architecture. if grains.get('os_family') == 'Debian': osarch = __salt__['cmd.run']('dpkg --print-architecture').strip() elif grains.get('os_family') in ['RedHat', 'Suse']: osarch = salt.utils.pkg.rpm.get_osarch() elif grains.get('os_family') in ('NILinuxRT', 'Poky'): archinfo = {} for line in __salt__['cmd.run']('opkg print-architecture').splitlines(): if line.startswith('arch'): _, arch, priority = line.split() archinfo[arch.strip()] = int(priority.strip()) # Return osarch in priority order (higher to lower) osarch = sorted(archinfo, key=archinfo.get, reverse=True) else: osarch = grains['cpuarch'] grains['osarch'] = osarch grains.update(_memdata(grains)) # Get the hardware and bios data grains.update(_hw_data(grains)) # Load the virtual machine info grains.update(_virtual(grains)) grains.update(_virtual_hv(grains)) grains.update(_ps(grains)) if grains.get('osrelease', ''): osrelease_info = grains['osrelease'].split('.') for idx, value in enumerate(osrelease_info): if not value.isdigit(): continue osrelease_info[idx] = int(value) grains['osrelease_info'] = tuple(osrelease_info) try: grains['osmajorrelease'] = int(grains['osrelease_info'][0]) except (IndexError, TypeError, ValueError): log.debug( 'Unable to derive osmajorrelease from osrelease_info \'%s\'. ' 'The osmajorrelease grain will not be set.', grains['osrelease_info'] ) os_name = grains['os' if grains.get('os') in ( 'Debian', 'FreeBSD', 'OpenBSD', 'NetBSD', 'Mac', 'Raspbian') else 'osfullname'] grains['osfinger'] = '{0}-{1}'.format( os_name, grains['osrelease'] if os_name in ('Ubuntu',) else grains['osrelease_info'][0]) return grains def locale_info(): ''' Provides defaultlanguage defaultencoding ''' grains = {} grains['locale_info'] = {} if salt.utils.platform.is_proxy(): return grains try: ( grains['locale_info']['defaultlanguage'], grains['locale_info']['defaultencoding'] ) = locale.getdefaultlocale() except Exception: # locale.getdefaultlocale can ValueError!! Catch anything else it # might do, per #2205 grains['locale_info']['defaultlanguage'] = 'unknown' grains['locale_info']['defaultencoding'] = 'unknown' grains['locale_info']['detectedencoding'] = __salt_system_encoding__ if _DATEUTIL_TZ: grains['locale_info']['timezone'] = datetime.datetime.now(dateutil.tz.tzlocal()).tzname() return grains def hostname(): ''' Return fqdn, hostname, domainname ''' # This is going to need some work # Provides: # fqdn # host # localhost # domain global __FQDN__ grains = {} if salt.utils.platform.is_proxy(): return grains grains['localhost'] = socket.gethostname() if __FQDN__ is None: __FQDN__ = salt.utils.network.get_fqhostname() # On some distros (notably FreeBSD) if there is no hostname set # salt.utils.network.get_fqhostname() will return None. # In this case we punt and log a message at error level, but force the # hostname and domain to be localhost.localdomain # Otherwise we would stacktrace below if __FQDN__ is None: # still! log.error('Having trouble getting a hostname. Does this machine have its hostname and domain set properly?') __FQDN__ = 'localhost.localdomain' grains['fqdn'] = __FQDN__ (grains['host'], grains['domain']) = grains['fqdn'].partition('.')[::2] return grains def append_domain(): ''' Return append_domain if set ''' grain = {} if salt.utils.platform.is_proxy(): return grain if 'append_domain' in __opts__: grain['append_domain'] = __opts__['append_domain'] return grain def fqdns(): ''' Return all known FQDNs for the system by enumerating all interfaces and then trying to reverse resolve them (excluding 'lo' interface). ''' # Provides: # fqdns grains = {} fqdns = set() addresses = salt.utils.network.ip_addrs(include_loopback=False, interface_data=_get_interfaces()) addresses.extend(salt.utils.network.ip_addrs6(include_loopback=False, interface_data=_get_interfaces())) err_message = 'Exception during resolving address: %s' for ip in addresses: try: name, aliaslist, addresslist = socket.gethostbyaddr(ip) fqdns.update([socket.getfqdn(name)] + [als for als in aliaslist if salt.utils.network.is_fqdn(als)]) except socket.herror as err: if err.errno == 0: # No FQDN for this IP address, so we don't need to know this all the time. log.debug("Unable to resolve address %s: %s", ip, err) else: log.error(err_message, err) except (socket.error, socket.gaierror, socket.timeout) as err: log.error(err_message, err) return {"fqdns": sorted(list(fqdns))} def ip_fqdn(): ''' Return ip address and FQDN grains ''' if salt.utils.platform.is_proxy(): return {} ret = {} ret['ipv4'] = salt.utils.network.ip_addrs(include_loopback=True) ret['ipv6'] = salt.utils.network.ip_addrs6(include_loopback=True) _fqdn = hostname()['fqdn'] for socket_type, ipv_num in ((socket.AF_INET, '4'), (socket.AF_INET6, '6')): key = 'fqdn_ip' + ipv_num if not ret['ipv' + ipv_num]: ret[key] = [] else: try: start_time = datetime.datetime.utcnow() info = socket.getaddrinfo(_fqdn, None, socket_type) ret[key] = list(set(item[4][0] for item in info)) except socket.error: timediff = datetime.datetime.utcnow() - start_time if timediff.seconds > 5 and __opts__['__role'] == 'master': log.warning( 'Unable to find IPv%s record for "%s" causing a %s ' 'second timeout when rendering grains. Set the dns or ' '/etc/hosts for IPv%s to clear this.', ipv_num, _fqdn, timediff, ipv_num ) ret[key] = [] return ret def ip_interfaces(): ''' Provide a dict of the connected interfaces and their ip addresses The addresses will be passed as a list for each interface ''' # Provides: # ip_interfaces if salt.utils.platform.is_proxy(): return {} ret = {} ifaces = _get_interfaces() for face in ifaces: iface_ips = [] for inet in ifaces[face].get('inet', []): if 'address' in inet: iface_ips.append(inet['address']) for inet in ifaces[face].get('inet6', []): if 'address' in inet: iface_ips.append(inet['address']) for secondary in ifaces[face].get('secondary', []): if 'address' in secondary: iface_ips.append(secondary['address']) ret[face] = iface_ips return {'ip_interfaces': ret} def ip4_interfaces(): ''' Provide a dict of the connected interfaces and their ip4 addresses The addresses will be passed as a list for each interface ''' # Provides: # ip_interfaces if salt.utils.platform.is_proxy(): return {} ret = {} ifaces = _get_interfaces() for face in ifaces: iface_ips = [] for inet in ifaces[face].get('inet', []): if 'address' in inet: iface_ips.append(inet['address']) for secondary in ifaces[face].get('secondary', []): if 'address' in secondary: iface_ips.append(secondary['address']) ret[face] = iface_ips return {'ip4_interfaces': ret} def ip6_interfaces(): ''' Provide a dict of the connected interfaces and their ip6 addresses The addresses will be passed as a list for each interface ''' # Provides: # ip_interfaces if salt.utils.platform.is_proxy(): return {} ret = {} ifaces = _get_interfaces() for face in ifaces: iface_ips = [] for inet in ifaces[face].get('inet6', []): if 'address' in inet: iface_ips.append(inet['address']) for secondary in ifaces[face].get('secondary', []): if 'address' in secondary: iface_ips.append(secondary['address']) ret[face] = iface_ips return {'ip6_interfaces': ret} def hwaddr_interfaces(): ''' Provide a dict of the connected interfaces and their hw addresses (Mac Address) ''' # Provides: # hwaddr_interfaces ret = {} ifaces = _get_interfaces() for face in ifaces: if 'hwaddr' in ifaces[face]: ret[face] = ifaces[face]['hwaddr'] return {'hwaddr_interfaces': ret} def dns(): ''' Parse the resolver configuration file .. versionadded:: 2016.3.0 ''' # Provides: # dns if salt.utils.platform.is_windows() or 'proxyminion' in __opts__: return {} resolv = salt.utils.dns.parse_resolv() for key in ('nameservers', 'ip4_nameservers', 'ip6_nameservers', 'sortlist'): if key in resolv: resolv[key] = [six.text_type(i) for i in resolv[key]] return {'dns': resolv} if resolv else {} def get_machine_id(): ''' Provide the machine-id for machine/virtualization combination ''' # Provides: # machine-id if platform.system() == 'AIX': return _aix_get_machine_id() locations = ['/etc/machine-id', '/var/lib/dbus/machine-id'] existing_locations = [loc for loc in locations if os.path.exists(loc)] if not existing_locations: return {} else: with salt.utils.files.fopen(existing_locations[0]) as machineid: return {'machine_id': machineid.read().strip()} def cwd(): ''' Current working directory ''' return {'cwd': os.getcwd()} def path(): ''' Return the path ''' # Provides: # path return {'path': os.environ.get('PATH', '').strip()} def pythonversion(): ''' Return the Python version ''' # Provides: # pythonversion return {'pythonversion': list(sys.version_info)} def pythonpath(): ''' Return the Python path ''' # Provides: # pythonpath return {'pythonpath': sys.path} def pythonexecutable(): ''' Return the python executable in use ''' # Provides: # pythonexecutable return {'pythonexecutable': sys.executable} def saltpath(): ''' Return the path of the salt module ''' # Provides: # saltpath salt_path = os.path.abspath(os.path.join(__file__, os.path.pardir)) return {'saltpath': os.path.dirname(salt_path)} def saltversion(): ''' Return the version of salt ''' # Provides: # saltversion from salt.version import __version__ return {'saltversion': __version__} def zmqversion(): ''' Return the zeromq version ''' # Provides: # zmqversion try: import zmq return {'zmqversion': zmq.zmq_version()} # pylint: disable=no-member except ImportError: return {} def saltversioninfo(): ''' Return the version_info of salt .. versionadded:: 0.17.0 ''' # Provides: # saltversioninfo from salt.version import __version_info__ return {'saltversioninfo': list(__version_info__)} def _get_hash_by_shell(): ''' Shell-out Python 3 for compute reliable hash :return: ''' id_ = __opts__.get('id', '') id_hash = None py_ver = sys.version_info[:2] if py_ver >= (3, 3): # Python 3.3 enabled hash randomization, so we need to shell out to get # a reliable hash. id_hash = __salt__['cmd.run']([sys.executable, '-c', 'print(hash("{0}"))'.format(id_)], env={'PYTHONHASHSEED': '0'}) try: id_hash = int(id_hash) except (TypeError, ValueError): log.debug('Failed to hash the ID to get the server_id grain. Result of hash command: %s', id_hash) id_hash = None if id_hash is None: # Python < 3.3 or error encountered above id_hash = hash(id_) return abs(id_hash % (2 ** 31)) def get_server_id(): ''' Provides an integer based on the FQDN of a machine. Useful as server-id in MySQL replication or anywhere else you'll need an ID like this. ''' # Provides: # server_id if salt.utils.platform.is_proxy(): server_id = {} else: use_crc = __opts__.get('server_id_use_crc') if bool(use_crc): id_hash = getattr(zlib, use_crc, zlib.adler32)(__opts__.get('id', '').encode()) & 0xffffffff else: log.debug('This server_id is computed not by Adler32 nor by CRC32. ' 'Please use "server_id_use_crc" option and define algorithm you ' 'prefer (default "Adler32"). Starting with Sodium, the ' 'server_id will be computed with Adler32 by default.') id_hash = _get_hash_by_shell() server_id = {'server_id': id_hash} return server_id def get_master(): ''' Provides the minion with the name of its master. This is useful in states to target other services running on the master. ''' # Provides: # master return {'master': __opts__.get('master', '')} def default_gateway(): ''' Populates grains which describe whether a server has a default gateway configured or not. Uses `ip -4 route show` and `ip -6 route show` and greps for a `default` at the beginning of any line. Assuming the standard `default via <ip>` format for default gateways, it will also parse out the ip address of the default gateway, and put it in ip4_gw or ip6_gw. If the `ip` command is unavailable, no grains will be populated. Currently does not support multiple default gateways. The grains will be set to the first default gateway found. List of grains: ip4_gw: True # ip/True/False if default ipv4 gateway ip6_gw: True # ip/True/False if default ipv6 gateway ip_gw: True # True if either of the above is True, False otherwise ''' grains = {} ip_bin = salt.utils.path.which('ip') if not ip_bin: return {} grains['ip_gw'] = False grains['ip4_gw'] = False grains['ip6_gw'] = False for ip_version in ('4', '6'): try: out = __salt__['cmd.run']([ip_bin, '-' + ip_version, 'route', 'show']) for line in out.splitlines(): if line.startswith('default'): grains['ip_gw'] = True grains['ip{0}_gw'.format(ip_version)] = True try: via, gw_ip = line.split()[1:3] except ValueError: pass else: if via == 'via': grains['ip{0}_gw'.format(ip_version)] = gw_ip break except Exception: continue return grains def kernelparams(): ''' Return the kernel boot parameters ''' if salt.utils.platform.is_windows(): # TODO: add grains using `bcdedit /enum {current}` return {} else: try: with salt.utils.files.fopen('/proc/cmdline', 'r') as fhr: cmdline = fhr.read() grains = {'kernelparams': []} for data in [item.split('=') for item in salt.utils.args.shlex_split(cmdline)]: value = None if len(data) == 2: value = data[1].strip('"') grains['kernelparams'] += [(data[0], value)] except IOError as exc: grains = {} log.debug('Failed to read /proc/cmdline: %s', exc) return grains
saltstack/salt
salt/grains/core.py
_get_hash_by_shell
python
def _get_hash_by_shell(): ''' Shell-out Python 3 for compute reliable hash :return: ''' id_ = __opts__.get('id', '') id_hash = None py_ver = sys.version_info[:2] if py_ver >= (3, 3): # Python 3.3 enabled hash randomization, so we need to shell out to get # a reliable hash. id_hash = __salt__['cmd.run']([sys.executable, '-c', 'print(hash("{0}"))'.format(id_)], env={'PYTHONHASHSEED': '0'}) try: id_hash = int(id_hash) except (TypeError, ValueError): log.debug('Failed to hash the ID to get the server_id grain. Result of hash command: %s', id_hash) id_hash = None if id_hash is None: # Python < 3.3 or error encountered above id_hash = hash(id_) return abs(id_hash % (2 ** 31))
Shell-out Python 3 for compute reliable hash :return:
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/grains/core.py#L2740-L2762
null
# -*- coding: utf-8 -*- ''' The static grains, these are the core, or built in grains. When grains are loaded they are not loaded in the same way that modules are loaded, grain functions are detected and executed, the functions MUST return a dict which will be applied to the main grains dict. This module will always be executed first, so that any grains loaded here in the core module can be overwritten just by returning dict keys with the same value as those returned here ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import socket import sys import re import platform import logging import locale import uuid import zlib from errno import EACCES, EPERM import datetime import warnings # pylint: disable=import-error try: import dateutil.tz _DATEUTIL_TZ = True except ImportError: _DATEUTIL_TZ = False __proxyenabled__ = ['*'] __FQDN__ = None # Extend the default list of supported distros. This will be used for the # /etc/DISTRO-release checking that is part of linux_distribution() from platform import _supported_dists _supported_dists += ('arch', 'mageia', 'meego', 'vmware', 'bluewhite64', 'slamd64', 'ovs', 'system', 'mint', 'oracle', 'void') # linux_distribution deprecated in py3.7 try: from platform import linux_distribution as _deprecated_linux_distribution def linux_distribution(**kwargs): with warnings.catch_warnings(): warnings.simplefilter("ignore") return _deprecated_linux_distribution(**kwargs) except ImportError: from distro import linux_distribution # Import salt libs import salt.exceptions import salt.log import salt.utils.args import salt.utils.dns import salt.utils.files import salt.utils.network import salt.utils.path import salt.utils.pkg.rpm import salt.utils.platform import salt.utils.stringutils import salt.utils.versions from salt.ext import six from salt.ext.six.moves import range if salt.utils.platform.is_windows(): import salt.utils.win_osinfo # Solve the Chicken and egg problem where grains need to run before any # of the modules are loaded and are generally available for any usage. import salt.modules.cmdmod import salt.modules.smbios __salt__ = { 'cmd.run': salt.modules.cmdmod._run_quiet, 'cmd.retcode': salt.modules.cmdmod._retcode_quiet, 'cmd.run_all': salt.modules.cmdmod._run_all_quiet, 'smbios.records': salt.modules.smbios.records, 'smbios.get': salt.modules.smbios.get, } log = logging.getLogger(__name__) HAS_WMI = False if salt.utils.platform.is_windows(): # attempt to import the python wmi module # the Windows minion uses WMI for some of its grains try: import wmi # pylint: disable=import-error import salt.utils.winapi import win32api import salt.utils.win_reg HAS_WMI = True except ImportError: log.exception( 'Unable to import Python wmi module, some core grains ' 'will be missing' ) HAS_UNAME = True if not hasattr(os, 'uname'): HAS_UNAME = False _INTERFACES = {} def _windows_cpudata(): ''' Return some CPU information on Windows minions ''' # Provides: # num_cpus # cpu_model grains = {} if 'NUMBER_OF_PROCESSORS' in os.environ: # Cast to int so that the logic isn't broken when used as a # conditional in templating. Also follows _linux_cpudata() try: grains['num_cpus'] = int(os.environ['NUMBER_OF_PROCESSORS']) except ValueError: grains['num_cpus'] = 1 grains['cpu_model'] = salt.utils.win_reg.read_value( hive="HKEY_LOCAL_MACHINE", key="HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", vname="ProcessorNameString").get('vdata') return grains def _linux_cpudata(): ''' Return some CPU information for Linux minions ''' # Provides: # num_cpus # cpu_model # cpu_flags grains = {} cpuinfo = '/proc/cpuinfo' # Parse over the cpuinfo file if os.path.isfile(cpuinfo): with salt.utils.files.fopen(cpuinfo, 'r') as _fp: grains['num_cpus'] = 0 for line in _fp: comps = line.split(':') if not len(comps) > 1: continue key = comps[0].strip() val = comps[1].strip() if key == 'processor': grains['num_cpus'] += 1 elif key == 'model name': grains['cpu_model'] = val elif key == 'flags': grains['cpu_flags'] = val.split() elif key == 'Features': grains['cpu_flags'] = val.split() # ARM support - /proc/cpuinfo # # Processor : ARMv6-compatible processor rev 7 (v6l) # BogoMIPS : 697.95 # Features : swp half thumb fastmult vfp edsp java tls # CPU implementer : 0x41 # CPU architecture: 7 # CPU variant : 0x0 # CPU part : 0xb76 # CPU revision : 7 # # Hardware : BCM2708 # Revision : 0002 # Serial : 00000000 elif key == 'Processor': grains['cpu_model'] = val.split('-')[0] grains['num_cpus'] = 1 if 'num_cpus' not in grains: grains['num_cpus'] = 0 if 'cpu_model' not in grains: grains['cpu_model'] = 'Unknown' if 'cpu_flags' not in grains: grains['cpu_flags'] = [] return grains def _linux_gpu_data(): ''' num_gpus: int gpus: - vendor: nvidia|amd|ati|... model: string ''' if __opts__.get('enable_lspci', True) is False: return {} if __opts__.get('enable_gpu_grains', True) is False: return {} lspci = salt.utils.path.which('lspci') if not lspci: log.debug( 'The `lspci` binary is not available on the system. GPU grains ' 'will not be available.' ) return {} # dominant gpu vendors to search for (MUST be lowercase for matching below) known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed'] gpu_classes = ('vga compatible controller', '3d controller') devs = [] try: lspci_out = __salt__['cmd.run']('{0} -vmm'.format(lspci)) cur_dev = {} error = False # Add a blank element to the lspci_out.splitlines() list, # otherwise the last device is not evaluated as a cur_dev and ignored. lspci_list = lspci_out.splitlines() lspci_list.append('') for line in lspci_list: # check for record-separating empty lines if line == '': if cur_dev.get('Class', '').lower() in gpu_classes: devs.append(cur_dev) cur_dev = {} continue if re.match(r'^\w+:\s+.*', line): key, val = line.split(':', 1) cur_dev[key.strip()] = val.strip() else: error = True log.debug('Unexpected lspci output: \'%s\'', line) if error: log.warning( 'Error loading grains, unexpected linux_gpu_data output, ' 'check that you have a valid shell configured and ' 'permissions to run lspci command' ) except OSError: pass gpus = [] for gpu in devs: vendor_strings = re.split('[^A-Za-z0-9]', gpu['Vendor'].lower()) # default vendor to 'unknown', overwrite if we match a known one vendor = 'unknown' for name in known_vendors: # search for an 'expected' vendor name in the list of strings if name in vendor_strings: vendor = name break gpus.append({'vendor': vendor, 'model': gpu['Device']}) grains = {} grains['num_gpus'] = len(gpus) grains['gpus'] = gpus return grains def _netbsd_gpu_data(): ''' num_gpus: int gpus: - vendor: nvidia|amd|ati|... model: string ''' known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed'] gpus = [] try: pcictl_out = __salt__['cmd.run']('pcictl pci0 list') for line in pcictl_out.splitlines(): for vendor in known_vendors: vendor_match = re.match( r'[0-9:]+ ({0}) (.+) \(VGA .+\)'.format(vendor), line, re.IGNORECASE ) if vendor_match: gpus.append({'vendor': vendor_match.group(1), 'model': vendor_match.group(2)}) except OSError: pass grains = {} grains['num_gpus'] = len(gpus) grains['gpus'] = gpus return grains def _osx_gpudata(): ''' num_gpus: int gpus: - vendor: nvidia|amd|ati|... model: string ''' gpus = [] try: pcictl_out = __salt__['cmd.run']('system_profiler SPDisplaysDataType') for line in pcictl_out.splitlines(): fieldname, _, fieldval = line.partition(': ') if fieldname.strip() == "Chipset Model": vendor, _, model = fieldval.partition(' ') vendor = vendor.lower() gpus.append({'vendor': vendor, 'model': model}) except OSError: pass grains = {} grains['num_gpus'] = len(gpus) grains['gpus'] = gpus return grains def _bsd_cpudata(osdata): ''' Return CPU information for BSD-like systems ''' # Provides: # cpuarch # num_cpus # cpu_model # cpu_flags sysctl = salt.utils.path.which('sysctl') arch = salt.utils.path.which('arch') cmds = {} if sysctl: cmds.update({ 'num_cpus': '{0} -n hw.ncpu'.format(sysctl), 'cpuarch': '{0} -n hw.machine'.format(sysctl), 'cpu_model': '{0} -n hw.model'.format(sysctl), }) if arch and osdata['kernel'] == 'OpenBSD': cmds['cpuarch'] = '{0} -s'.format(arch) if osdata['kernel'] == 'Darwin': cmds['cpu_model'] = '{0} -n machdep.cpu.brand_string'.format(sysctl) cmds['cpu_flags'] = '{0} -n machdep.cpu.features'.format(sysctl) grains = dict([(k, __salt__['cmd.run'](v)) for k, v in six.iteritems(cmds)]) if 'cpu_flags' in grains and isinstance(grains['cpu_flags'], six.string_types): grains['cpu_flags'] = grains['cpu_flags'].split(' ') if osdata['kernel'] == 'NetBSD': grains['cpu_flags'] = [] for line in __salt__['cmd.run']('cpuctl identify 0').splitlines(): cpu_match = re.match(r'cpu[0-9]:\ features[0-9]?\ .+<(.+)>', line) if cpu_match: flag = cpu_match.group(1).split(',') grains['cpu_flags'].extend(flag) if osdata['kernel'] == 'FreeBSD' and os.path.isfile('/var/run/dmesg.boot'): grains['cpu_flags'] = [] # TODO: at least it needs to be tested for BSD other then FreeBSD with salt.utils.files.fopen('/var/run/dmesg.boot', 'r') as _fp: cpu_here = False for line in _fp: if line.startswith('CPU: '): cpu_here = True # starts CPU descr continue if cpu_here: if not line.startswith(' '): break # game over if 'Features' in line: start = line.find('<') end = line.find('>') if start > 0 and end > 0: flag = line[start + 1:end].split(',') grains['cpu_flags'].extend(flag) try: grains['num_cpus'] = int(grains['num_cpus']) except ValueError: grains['num_cpus'] = 1 return grains def _sunos_cpudata(): ''' Return the CPU information for Solaris-like systems ''' # Provides: # cpuarch # num_cpus # cpu_model # cpu_flags grains = {} grains['cpu_flags'] = [] grains['cpuarch'] = __salt__['cmd.run']('isainfo -k') psrinfo = '/usr/sbin/psrinfo 2>/dev/null' grains['num_cpus'] = len(__salt__['cmd.run'](psrinfo, python_shell=True).splitlines()) kstat_info = 'kstat -p cpu_info:*:*:brand' for line in __salt__['cmd.run'](kstat_info).splitlines(): match = re.match(r'(\w+:\d+:\w+\d+:\w+)\s+(.+)', line) if match: grains['cpu_model'] = match.group(2) isainfo = 'isainfo -n -v' for line in __salt__['cmd.run'](isainfo).splitlines(): match = re.match(r'^\s+(.+)', line) if match: cpu_flags = match.group(1).split() grains['cpu_flags'].extend(cpu_flags) return grains def _aix_cpudata(): ''' Return CPU information for AIX systems ''' # Provides: # cpuarch # num_cpus # cpu_model # cpu_flags grains = {} cmd = salt.utils.path.which('prtconf') if cmd: data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep for dest, regstring in (('cpuarch', r'(?im)^\s*Processor\s+Type:\s+(\S+)'), ('cpu_flags', r'(?im)^\s*Processor\s+Version:\s+(\S+)'), ('cpu_model', r'(?im)^\s*Processor\s+Implementation\s+Mode:\s+(.*)'), ('num_cpus', r'(?im)^\s*Number\s+Of\s+Processors:\s+(\S+)')): for regex in [re.compile(r) for r in [regstring]]: res = regex.search(data) if res and len(res.groups()) >= 1: grains[dest] = res.group(1).strip().replace("'", '') else: log.error('The \'prtconf\' binary was not found in $PATH.') return grains def _linux_memdata(): ''' Return the memory information for Linux-like systems ''' grains = {'mem_total': 0, 'swap_total': 0} meminfo = '/proc/meminfo' if os.path.isfile(meminfo): with salt.utils.files.fopen(meminfo, 'r') as ifile: for line in ifile: comps = line.rstrip('\n').split(':') if not len(comps) > 1: continue if comps[0].strip() == 'MemTotal': # Use floor division to force output to be an integer grains['mem_total'] = int(comps[1].split()[0]) // 1024 if comps[0].strip() == 'SwapTotal': # Use floor division to force output to be an integer grains['swap_total'] = int(comps[1].split()[0]) // 1024 return grains def _osx_memdata(): ''' Return the memory information for BSD-like systems ''' grains = {'mem_total': 0, 'swap_total': 0} sysctl = salt.utils.path.which('sysctl') if sysctl: mem = __salt__['cmd.run']('{0} -n hw.memsize'.format(sysctl)) swap_total = __salt__['cmd.run']('{0} -n vm.swapusage'.format(sysctl)).split()[2].replace(',', '.') if swap_total.endswith('K'): _power = 2**10 elif swap_total.endswith('M'): _power = 2**20 elif swap_total.endswith('G'): _power = 2**30 swap_total = float(swap_total[:-1]) * _power grains['mem_total'] = int(mem) // 1024 // 1024 grains['swap_total'] = int(swap_total) // 1024 // 1024 return grains def _bsd_memdata(osdata): ''' Return the memory information for BSD-like systems ''' grains = {'mem_total': 0, 'swap_total': 0} sysctl = salt.utils.path.which('sysctl') if sysctl: mem = __salt__['cmd.run']('{0} -n hw.physmem'.format(sysctl)) if osdata['kernel'] == 'NetBSD' and mem.startswith('-'): mem = __salt__['cmd.run']('{0} -n hw.physmem64'.format(sysctl)) grains['mem_total'] = int(mem) // 1024 // 1024 if osdata['kernel'] in ['OpenBSD', 'NetBSD']: swapctl = salt.utils.path.which('swapctl') swap_data = __salt__['cmd.run']('{0} -sk'.format(swapctl)) if swap_data == 'no swap devices configured': swap_total = 0 else: swap_total = swap_data.split(' ')[1] else: swap_total = __salt__['cmd.run']('{0} -n vm.swap_total'.format(sysctl)) grains['swap_total'] = int(swap_total) // 1024 // 1024 return grains def _sunos_memdata(): ''' Return the memory information for SunOS-like systems ''' grains = {'mem_total': 0, 'swap_total': 0} prtconf = '/usr/sbin/prtconf 2>/dev/null' for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines(): comps = line.split(' ') if comps[0].strip() == 'Memory' and comps[1].strip() == 'size:': grains['mem_total'] = int(comps[2].strip()) swap_cmd = salt.utils.path.which('swap') swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split() try: swap_avail = int(swap_data[-2][:-1]) swap_used = int(swap_data[-4][:-1]) swap_total = (swap_avail + swap_used) // 1024 except ValueError: swap_total = None grains['swap_total'] = swap_total return grains def _aix_memdata(): ''' Return the memory information for AIX systems ''' grains = {'mem_total': 0, 'swap_total': 0} prtconf = salt.utils.path.which('prtconf') if prtconf: for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines(): comps = [x for x in line.strip().split(' ') if x] if len(comps) > 2 and 'Memory' in comps[0] and 'Size' in comps[1]: grains['mem_total'] = int(comps[2]) break else: log.error('The \'prtconf\' binary was not found in $PATH.') swap_cmd = salt.utils.path.which('swap') if swap_cmd: swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split() try: swap_total = (int(swap_data[-2]) + int(swap_data[-6])) * 4 except ValueError: swap_total = None grains['swap_total'] = swap_total else: log.error('The \'swap\' binary was not found in $PATH.') return grains def _windows_memdata(): ''' Return the memory information for Windows systems ''' grains = {'mem_total': 0} # get the Total Physical memory as reported by msinfo32 tot_bytes = win32api.GlobalMemoryStatusEx()['TotalPhys'] # return memory info in gigabytes grains['mem_total'] = int(tot_bytes / (1024 ** 2)) return grains def _memdata(osdata): ''' Gather information about the system memory ''' # Provides: # mem_total # swap_total, for supported systems. grains = {'mem_total': 0} if osdata['kernel'] == 'Linux': grains.update(_linux_memdata()) elif osdata['kernel'] in ('FreeBSD', 'OpenBSD', 'NetBSD'): grains.update(_bsd_memdata(osdata)) elif osdata['kernel'] == 'Darwin': grains.update(_osx_memdata()) elif osdata['kernel'] == 'SunOS': grains.update(_sunos_memdata()) elif osdata['kernel'] == 'AIX': grains.update(_aix_memdata()) elif osdata['kernel'] == 'Windows' and HAS_WMI: grains.update(_windows_memdata()) return grains def _aix_get_machine_id(): ''' Parse the output of lsattr -El sys0 for os_uuid ''' grains = {} cmd = salt.utils.path.which('lsattr') if cmd: data = __salt__['cmd.run']('{0} -El sys0'.format(cmd)) + os.linesep uuid_regexes = [re.compile(r'(?im)^\s*os_uuid\s+(\S+)\s+(.*)')] for regex in uuid_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: grains['machine_id'] = res.group(1).strip() break else: log.error('The \'lsattr\' binary was not found in $PATH.') return grains def _windows_virtual(osdata): ''' Returns what type of virtual hardware is under the hood, kvm or physical ''' # Provides: # virtual # virtual_subtype grains = dict() if osdata['kernel'] != 'Windows': return grains grains['virtual'] = 'physical' # It is possible that the 'manufacturer' and/or 'productname' grains # exist but have a value of None. manufacturer = osdata.get('manufacturer', '') if manufacturer is None: manufacturer = '' productname = osdata.get('productname', '') if productname is None: productname = '' if 'QEMU' in manufacturer: # FIXME: Make this detect between kvm or qemu grains['virtual'] = 'kvm' if 'Bochs' in manufacturer: grains['virtual'] = 'kvm' # Product Name: (oVirt) www.ovirt.org # Red Hat Community virtualization Project based on kvm elif 'oVirt' in productname: grains['virtual'] = 'kvm' grains['virtual_subtype'] = 'oVirt' # Red Hat Enterprise Virtualization elif 'RHEV Hypervisor' in productname: grains['virtual'] = 'kvm' grains['virtual_subtype'] = 'rhev' # Product Name: VirtualBox elif 'VirtualBox' in productname: grains['virtual'] = 'VirtualBox' # Product Name: VMware Virtual Platform elif 'VMware Virtual Platform' in productname: grains['virtual'] = 'VMware' # Manufacturer: Microsoft Corporation # Product Name: Virtual Machine elif 'Microsoft' in manufacturer and \ 'Virtual Machine' in productname: grains['virtual'] = 'VirtualPC' # Manufacturer: Parallels Software International Inc. elif 'Parallels Software' in manufacturer: grains['virtual'] = 'Parallels' # Apache CloudStack elif 'CloudStack KVM Hypervisor' in productname: grains['virtual'] = 'kvm' grains['virtual_subtype'] = 'cloudstack' return grains def _virtual(osdata): ''' Returns what type of virtual hardware is under the hood, kvm or physical ''' # This is going to be a monster, if you are running a vm you can test this # grain with please submit patches! # Provides: # virtual # virtual_subtype grains = {'virtual': 'physical'} # Skip the below loop on platforms which have none of the desired cmds # This is a temporary measure until we can write proper virtual hardware # detection. skip_cmds = ('AIX',) # list of commands to be executed to determine the 'virtual' grain _cmds = ['systemd-detect-virt', 'virt-what', 'dmidecode'] # test first for virt-what, which covers most of the desired functionality # on most platforms if not salt.utils.platform.is_windows() and osdata['kernel'] not in skip_cmds: if salt.utils.path.which('virt-what'): _cmds = ['virt-what'] # Check if enable_lspci is True or False if __opts__.get('enable_lspci', True) is True: # /proc/bus/pci does not exists, lspci will fail if os.path.exists('/proc/bus/pci'): _cmds += ['lspci'] # Add additional last resort commands if osdata['kernel'] in skip_cmds: _cmds = () # Quick backout for BrandZ (Solaris LX Branded zones) # Don't waste time trying other commands to detect the virtual grain if HAS_UNAME and osdata['kernel'] == 'Linux' and 'BrandZ virtual linux' in os.uname(): grains['virtual'] = 'zone' return grains failed_commands = set() for command in _cmds: args = [] if osdata['kernel'] == 'Darwin': command = 'system_profiler' args = ['SPDisplaysDataType'] elif osdata['kernel'] == 'SunOS': virtinfo = salt.utils.path.which('virtinfo') if virtinfo: try: ret = __salt__['cmd.run_all']('{0} -a'.format(virtinfo)) except salt.exceptions.CommandExecutionError: if salt.log.is_logging_configured(): failed_commands.add(virtinfo) else: if ret['stdout'].endswith('not supported'): command = 'prtdiag' else: command = 'virtinfo' else: command = 'prtdiag' cmd = salt.utils.path.which(command) if not cmd: continue cmd = '{0} {1}'.format(cmd, ' '.join(args)) try: ret = __salt__['cmd.run_all'](cmd) if ret['retcode'] > 0: if salt.log.is_logging_configured(): # systemd-detect-virt always returns > 0 on non-virtualized # systems # prtdiag only works in the global zone, skip if it fails if salt.utils.platform.is_windows() or 'systemd-detect-virt' in cmd or 'prtdiag' in cmd: continue failed_commands.add(command) continue except salt.exceptions.CommandExecutionError: if salt.log.is_logging_configured(): if salt.utils.platform.is_windows(): continue failed_commands.add(command) continue output = ret['stdout'] if command == "system_profiler": macoutput = output.lower() if '0x1ab8' in macoutput: grains['virtual'] = 'Parallels' if 'parallels' in macoutput: grains['virtual'] = 'Parallels' if 'vmware' in macoutput: grains['virtual'] = 'VMware' if '0x15ad' in macoutput: grains['virtual'] = 'VMware' if 'virtualbox' in macoutput: grains['virtual'] = 'VirtualBox' # Break out of the loop so the next log message is not issued break elif command == 'systemd-detect-virt': if output in ('qemu', 'kvm', 'oracle', 'xen', 'bochs', 'chroot', 'uml', 'systemd-nspawn'): grains['virtual'] = output break elif 'vmware' in output: grains['virtual'] = 'VMware' break elif 'microsoft' in output: grains['virtual'] = 'VirtualPC' break elif 'lxc' in output: grains['virtual'] = 'LXC' break elif 'systemd-nspawn' in output: grains['virtual'] = 'LXC' break elif command == 'virt-what': try: output = output.splitlines()[-1] except IndexError: pass if output in ('kvm', 'qemu', 'uml', 'xen', 'lxc'): grains['virtual'] = output break elif 'vmware' in output: grains['virtual'] = 'VMware' break elif 'parallels' in output: grains['virtual'] = 'Parallels' break elif 'hyperv' in output: grains['virtual'] = 'HyperV' break elif command == 'dmidecode': # Product Name: VirtualBox if 'Vendor: QEMU' in output: # FIXME: Make this detect between kvm or qemu grains['virtual'] = 'kvm' if 'Manufacturer: QEMU' in output: grains['virtual'] = 'kvm' if 'Vendor: Bochs' in output: grains['virtual'] = 'kvm' if 'Manufacturer: Bochs' in output: grains['virtual'] = 'kvm' if 'BHYVE' in output: grains['virtual'] = 'bhyve' # Product Name: (oVirt) www.ovirt.org # Red Hat Community virtualization Project based on kvm elif 'Manufacturer: oVirt' in output: grains['virtual'] = 'kvm' grains['virtual_subtype'] = 'ovirt' # Red Hat Enterprise Virtualization elif 'Product Name: RHEV Hypervisor' in output: grains['virtual'] = 'kvm' grains['virtual_subtype'] = 'rhev' elif 'VirtualBox' in output: grains['virtual'] = 'VirtualBox' # Product Name: VMware Virtual Platform elif 'VMware' in output: grains['virtual'] = 'VMware' # Manufacturer: Microsoft Corporation # Product Name: Virtual Machine elif ': Microsoft' in output and 'Virtual Machine' in output: grains['virtual'] = 'VirtualPC' # Manufacturer: Parallels Software International Inc. elif 'Parallels Software' in output: grains['virtual'] = 'Parallels' elif 'Manufacturer: Google' in output: grains['virtual'] = 'kvm' # Proxmox KVM elif 'Vendor: SeaBIOS' in output: grains['virtual'] = 'kvm' # Break out of the loop, lspci parsing is not necessary break elif command == 'lspci': # dmidecode not available or the user does not have the necessary # permissions model = output.lower() if 'vmware' in model: grains['virtual'] = 'VMware' # 00:04.0 System peripheral: InnoTek Systemberatung GmbH # VirtualBox Guest Service elif 'virtualbox' in model: grains['virtual'] = 'VirtualBox' elif 'qemu' in model: grains['virtual'] = 'kvm' elif 'virtio' in model: grains['virtual'] = 'kvm' # Break out of the loop so the next log message is not issued break elif command == 'prtdiag': model = output.lower().split("\n")[0] if 'vmware' in model: grains['virtual'] = 'VMware' elif 'virtualbox' in model: grains['virtual'] = 'VirtualBox' elif 'qemu' in model: grains['virtual'] = 'kvm' elif 'joyent smartdc hvm' in model: grains['virtual'] = 'kvm' break elif command == 'virtinfo': grains['virtual'] = 'LDOM' break choices = ('Linux', 'HP-UX') isdir = os.path.isdir sysctl = salt.utils.path.which('sysctl') if osdata['kernel'] in choices: if os.path.isdir('/proc'): try: self_root = os.stat('/') init_root = os.stat('/proc/1/root/.') if self_root != init_root: grains['virtual_subtype'] = 'chroot' except (IOError, OSError): pass if isdir('/proc/vz'): if os.path.isfile('/proc/vz/version'): grains['virtual'] = 'openvzhn' elif os.path.isfile('/proc/vz/veinfo'): grains['virtual'] = 'openvzve' # a posteriori, it's expected for these to have failed: failed_commands.discard('lspci') failed_commands.discard('dmidecode') # Provide additional detection for OpenVZ if os.path.isfile('/proc/self/status'): with salt.utils.files.fopen('/proc/self/status') as status_file: vz_re = re.compile(r'^envID:\s+(\d+)$') for line in status_file: vz_match = vz_re.match(line.rstrip('\n')) if vz_match and int(vz_match.groups()[0]) != 0: grains['virtual'] = 'openvzve' elif vz_match and int(vz_match.groups()[0]) == 0: grains['virtual'] = 'openvzhn' if isdir('/proc/sys/xen') or \ isdir('/sys/bus/xen') or isdir('/proc/xen'): if os.path.isfile('/proc/xen/xsd_kva'): # Tested on CentOS 5.3 / 2.6.18-194.26.1.el5xen # Tested on CentOS 5.4 / 2.6.18-164.15.1.el5xen grains['virtual_subtype'] = 'Xen Dom0' else: if osdata.get('productname', '') == 'HVM domU': # Requires dmidecode! grains['virtual_subtype'] = 'Xen HVM DomU' elif os.path.isfile('/proc/xen/capabilities') and \ os.access('/proc/xen/capabilities', os.R_OK): with salt.utils.files.fopen('/proc/xen/capabilities') as fhr: if 'control_d' not in fhr.read(): # Tested on CentOS 5.5 / 2.6.18-194.3.1.el5xen grains['virtual_subtype'] = 'Xen PV DomU' else: # Shouldn't get to this, but just in case grains['virtual_subtype'] = 'Xen Dom0' # Tested on Fedora 10 / 2.6.27.30-170.2.82 with xen # Tested on Fedora 15 / 2.6.41.4-1 without running xen elif isdir('/sys/bus/xen'): if 'xen:' in __salt__['cmd.run']('dmesg').lower(): grains['virtual_subtype'] = 'Xen PV DomU' elif os.path.isfile('/sys/bus/xen/drivers/xenconsole'): # An actual DomU will have the xenconsole driver grains['virtual_subtype'] = 'Xen PV DomU' # If a Dom0 or DomU was detected, obviously this is xen if 'dom' in grains.get('virtual_subtype', '').lower(): grains['virtual'] = 'xen' # Check container type after hypervisors, to avoid variable overwrite on containers running in virtual environment. if os.path.isfile('/proc/1/cgroup'): try: with salt.utils.files.fopen('/proc/1/cgroup', 'r') as fhr: fhr_contents = fhr.read() if ':/lxc/' in fhr_contents: grains['virtual_subtype'] = 'LXC' elif ':/kubepods/' in fhr_contents: grains['virtual_subtype'] = 'kubernetes' elif ':/libpod_parent/' in fhr_contents: grains['virtual_subtype'] = 'libpod' else: if any(x in fhr_contents for x in (':/system.slice/docker', ':/docker/', ':/docker-ce/')): grains['virtual_subtype'] = 'Docker' except IOError: pass if os.path.isfile('/proc/cpuinfo'): with salt.utils.files.fopen('/proc/cpuinfo', 'r') as fhr: if 'QEMU Virtual CPU' in fhr.read(): grains['virtual'] = 'kvm' if os.path.isfile('/sys/devices/virtual/dmi/id/product_name'): try: with salt.utils.files.fopen('/sys/devices/virtual/dmi/id/product_name', 'r') as fhr: output = salt.utils.stringutils.to_unicode(fhr.read(), errors='replace') if 'VirtualBox' in output: grains['virtual'] = 'VirtualBox' elif 'RHEV Hypervisor' in output: grains['virtual'] = 'kvm' grains['virtual_subtype'] = 'rhev' elif 'oVirt Node' in output: grains['virtual'] = 'kvm' grains['virtual_subtype'] = 'ovirt' elif 'Google' in output: grains['virtual'] = 'gce' elif 'BHYVE' in output: grains['virtual'] = 'bhyve' except IOError: pass elif osdata['kernel'] == 'FreeBSD': kenv = salt.utils.path.which('kenv') if kenv: product = __salt__['cmd.run']( '{0} smbios.system.product'.format(kenv) ) maker = __salt__['cmd.run']( '{0} smbios.system.maker'.format(kenv) ) if product.startswith('VMware'): grains['virtual'] = 'VMware' if product.startswith('VirtualBox'): grains['virtual'] = 'VirtualBox' if maker.startswith('Xen'): grains['virtual_subtype'] = '{0} {1}'.format(maker, product) grains['virtual'] = 'xen' if maker.startswith('Microsoft') and product.startswith('Virtual'): grains['virtual'] = 'VirtualPC' if maker.startswith('OpenStack'): grains['virtual'] = 'OpenStack' if maker.startswith('Bochs'): grains['virtual'] = 'kvm' if sysctl: hv_vendor = __salt__['cmd.run']('{0} hw.hv_vendor'.format(sysctl)) model = __salt__['cmd.run']('{0} hw.model'.format(sysctl)) jail = __salt__['cmd.run']( '{0} -n security.jail.jailed'.format(sysctl) ) if 'bhyve' in hv_vendor: grains['virtual'] = 'bhyve' if jail == '1': grains['virtual_subtype'] = 'jail' if 'QEMU Virtual CPU' in model: grains['virtual'] = 'kvm' elif osdata['kernel'] == 'OpenBSD': if 'manufacturer' in osdata: if osdata['manufacturer'] in ['QEMU', 'Red Hat', 'Joyent']: grains['virtual'] = 'kvm' if osdata['manufacturer'] == 'OpenBSD': grains['virtual'] = 'vmm' elif osdata['kernel'] == 'SunOS': if grains['virtual'] == 'LDOM': roles = [] for role in ('control', 'io', 'root', 'service'): subtype_cmd = '{0} -c current get -H -o value {1}-role'.format(cmd, role) ret = __salt__['cmd.run_all']('{0}'.format(subtype_cmd)) if ret['stdout'] == 'true': roles.append(role) if roles: grains['virtual_subtype'] = roles else: # Check if it's a "regular" zone. (i.e. Solaris 10/11 zone) zonename = salt.utils.path.which('zonename') if zonename: zone = __salt__['cmd.run']('{0}'.format(zonename)) if zone != 'global': grains['virtual'] = 'zone' # Check if it's a branded zone (i.e. Solaris 8/9 zone) if isdir('/.SUNWnative'): grains['virtual'] = 'zone' elif osdata['kernel'] == 'NetBSD': if sysctl: if 'QEMU Virtual CPU' in __salt__['cmd.run']( '{0} -n machdep.cpu_brand'.format(sysctl)): grains['virtual'] = 'kvm' elif 'invalid' not in __salt__['cmd.run']( '{0} -n machdep.xen.suspend'.format(sysctl)): grains['virtual'] = 'Xen PV DomU' elif 'VMware' in __salt__['cmd.run']( '{0} -n machdep.dmi.system-vendor'.format(sysctl)): grains['virtual'] = 'VMware' # NetBSD has Xen dom0 support elif __salt__['cmd.run']( '{0} -n machdep.idle-mechanism'.format(sysctl)) == 'xen': if os.path.isfile('/var/run/xenconsoled.pid'): grains['virtual_subtype'] = 'Xen Dom0' for command in failed_commands: log.info( "Although '%s' was found in path, the current user " 'cannot execute it. Grains output might not be ' 'accurate.', command ) return grains def _virtual_hv(osdata): ''' Returns detailed hypervisor information from sysfs Currently this seems to be used only by Xen ''' grains = {} # Bail early if we're not running on Xen try: if 'xen' not in osdata['virtual']: return grains except KeyError: return grains # Try to get the exact hypervisor version from sysfs try: version = {} for fn in ('major', 'minor', 'extra'): with salt.utils.files.fopen('/sys/hypervisor/version/{}'.format(fn), 'r') as fhr: version[fn] = salt.utils.stringutils.to_unicode(fhr.read().strip()) grains['virtual_hv_version'] = '{}.{}{}'.format(version['major'], version['minor'], version['extra']) grains['virtual_hv_version_info'] = [version['major'], version['minor'], version['extra']] except (IOError, OSError, KeyError): pass # Try to read and decode the supported feature set of the hypervisor # Based on https://github.com/brendangregg/Misc/blob/master/xen/xen-features.py # Table data from include/xen/interface/features.h xen_feature_table = {0: 'writable_page_tables', 1: 'writable_descriptor_tables', 2: 'auto_translated_physmap', 3: 'supervisor_mode_kernel', 4: 'pae_pgdir_above_4gb', 5: 'mmu_pt_update_preserve_ad', 7: 'gnttab_map_avail_bits', 8: 'hvm_callback_vector', 9: 'hvm_safe_pvclock', 10: 'hvm_pirqs', 11: 'dom0', 12: 'grant_map_identity', 13: 'memory_op_vnode_supported', 14: 'ARM_SMCCC_supported'} try: with salt.utils.files.fopen('/sys/hypervisor/properties/features', 'r') as fhr: features = salt.utils.stringutils.to_unicode(fhr.read().strip()) enabled_features = [] for bit, feat in six.iteritems(xen_feature_table): if int(features, 16) & (1 << bit): enabled_features.append(feat) grains['virtual_hv_features'] = features grains['virtual_hv_features_list'] = enabled_features except (IOError, OSError, KeyError): pass return grains def _ps(osdata): ''' Return the ps grain ''' grains = {} bsd_choices = ('FreeBSD', 'NetBSD', 'OpenBSD', 'MacOS') if osdata['os'] in bsd_choices: grains['ps'] = 'ps auxwww' elif osdata['os_family'] == 'Solaris': grains['ps'] = '/usr/ucb/ps auxwww' elif osdata['os'] == 'Windows': grains['ps'] = 'tasklist.exe' elif osdata.get('virtual', '') == 'openvzhn': grains['ps'] = ( 'ps -fH -p $(grep -l \"^envID:[[:space:]]*0\\$\" ' '/proc/[0-9]*/status | sed -e \"s=/proc/\\([0-9]*\\)/.*=\\1=\") ' '| awk \'{ $7=\"\"; print }\'' ) elif osdata['os_family'] == 'AIX': grains['ps'] = '/usr/bin/ps auxww' elif osdata['os_family'] == 'NILinuxRT': grains['ps'] = 'ps -o user,pid,ppid,tty,time,comm' else: grains['ps'] = 'ps -efHww' return grains def _clean_value(key, val): ''' Clean out well-known bogus values. If it isn't clean (for example has value 'None'), return None. Otherwise, return the original value. NOTE: This logic also exists in the smbios module. This function is for use when not using smbios to retrieve the value. ''' if (val is None or not val or re.match('none', val, flags=re.IGNORECASE)): return None elif 'uuid' in key: # Try each version (1-5) of RFC4122 to check if it's actually a UUID for uuidver in range(1, 5): try: uuid.UUID(val, version=uuidver) return val except ValueError: continue log.trace('HW %s value %s is an invalid UUID', key, val.replace('\n', ' ')) return None elif re.search('serial|part|version', key): # 'To be filled by O.E.M. # 'Not applicable' etc. # 'Not specified' etc. # 0000000, 1234567 etc. # begone! if (re.match(r'^[0]+$', val) or re.match(r'[0]?1234567[8]?[9]?[0]?', val) or re.search(r'sernum|part[_-]?number|specified|filled|applicable', val, flags=re.IGNORECASE)): return None elif re.search('asset|manufacturer', key): # AssetTag0. Manufacturer04. Begone. if re.search(r'manufacturer|to be filled|available|asset|^no(ne|t)', val, flags=re.IGNORECASE): return None else: # map unspecified, undefined, unknown & whatever to None if (re.search(r'to be filled', val, flags=re.IGNORECASE) or re.search(r'un(known|specified)|no(t|ne)? (asset|provided|defined|available|present|specified)', val, flags=re.IGNORECASE)): return None return val def _windows_platform_data(): ''' Use the platform module for as much as we can. ''' # Provides: # kernelrelease # kernelversion # osversion # osrelease # osservicepack # osmanufacturer # manufacturer # productname # biosversion # serialnumber # osfullname # timezone # windowsdomain # windowsdomaintype # motherboard.productname # motherboard.serialnumber # virtual if not HAS_WMI: return {} with salt.utils.winapi.Com(): wmi_c = wmi.WMI() # http://msdn.microsoft.com/en-us/library/windows/desktop/aa394102%28v=vs.85%29.aspx systeminfo = wmi_c.Win32_ComputerSystem()[0] # https://msdn.microsoft.com/en-us/library/aa394239(v=vs.85).aspx osinfo = wmi_c.Win32_OperatingSystem()[0] # http://msdn.microsoft.com/en-us/library/windows/desktop/aa394077(v=vs.85).aspx biosinfo = wmi_c.Win32_BIOS()[0] # http://msdn.microsoft.com/en-us/library/windows/desktop/aa394498(v=vs.85).aspx timeinfo = wmi_c.Win32_TimeZone()[0] # http://msdn.microsoft.com/en-us/library/windows/desktop/aa394072(v=vs.85).aspx motherboard = {'product': None, 'serial': None} try: motherboardinfo = wmi_c.Win32_BaseBoard()[0] motherboard['product'] = motherboardinfo.Product motherboard['serial'] = motherboardinfo.SerialNumber except IndexError: log.debug('Motherboard info not available on this system') os_release = platform.release() kernel_version = platform.version() info = salt.utils.win_osinfo.get_os_version_info() net_info = salt.utils.win_osinfo.get_join_info() service_pack = None if info['ServicePackMajor'] > 0: service_pack = ''.join(['SP', six.text_type(info['ServicePackMajor'])]) # This creates the osrelease grain based on the Windows Operating # System Product Name. As long as Microsoft maintains a similar format # this should be future proof version = 'Unknown' release = '' if 'Server' in osinfo.Caption: for item in osinfo.Caption.split(' '): # If it's all digits, then it's version if re.match(r'\d+', item): version = item # If it starts with R and then numbers, it's the release # ie: R2 if re.match(r'^R\d+$', item): release = item os_release = '{0}Server{1}'.format(version, release) else: for item in osinfo.Caption.split(' '): # If it's a number, decimal number, Thin or Vista, then it's the # version if re.match(r'^(\d+(\.\d+)?)|Thin|Vista$', item): version = item os_release = version grains = { 'kernelrelease': _clean_value('kernelrelease', osinfo.Version), 'kernelversion': _clean_value('kernelversion', kernel_version), 'osversion': _clean_value('osversion', osinfo.Version), 'osrelease': _clean_value('osrelease', os_release), 'osservicepack': _clean_value('osservicepack', service_pack), 'osmanufacturer': _clean_value('osmanufacturer', osinfo.Manufacturer), 'manufacturer': _clean_value('manufacturer', systeminfo.Manufacturer), 'productname': _clean_value('productname', systeminfo.Model), # bios name had a bunch of whitespace appended to it in my testing # 'PhoenixBIOS 4.0 Release 6.0 ' 'biosversion': _clean_value('biosversion', biosinfo.Name.strip()), 'serialnumber': _clean_value('serialnumber', biosinfo.SerialNumber), 'osfullname': _clean_value('osfullname', osinfo.Caption), 'timezone': _clean_value('timezone', timeinfo.Description), 'windowsdomain': _clean_value('windowsdomain', net_info['Domain']), 'windowsdomaintype': _clean_value('windowsdomaintype', net_info['DomainType']), 'motherboard': { 'productname': _clean_value('motherboard.productname', motherboard['product']), 'serialnumber': _clean_value('motherboard.serialnumber', motherboard['serial']), } } # test for virtualized environments # I only had VMware available so the rest are unvalidated if 'VRTUAL' in biosinfo.Version: # (not a typo) grains['virtual'] = 'HyperV' elif 'A M I' in biosinfo.Version: grains['virtual'] = 'VirtualPC' elif 'VMware' in systeminfo.Model: grains['virtual'] = 'VMware' elif 'VirtualBox' in systeminfo.Model: grains['virtual'] = 'VirtualBox' elif 'Xen' in biosinfo.Version: grains['virtual'] = 'Xen' if 'HVM domU' in systeminfo.Model: grains['virtual_subtype'] = 'HVM domU' elif 'OpenStack' in systeminfo.Model: grains['virtual'] = 'OpenStack' return grains def _osx_platform_data(): ''' Additional data for macOS systems Returns: A dictionary containing values for the following: - model_name - boot_rom_version - smc_version - system_serialnumber ''' cmd = 'system_profiler SPHardwareDataType' hardware = __salt__['cmd.run'](cmd) grains = {} for line in hardware.splitlines(): field_name, _, field_val = line.partition(': ') if field_name.strip() == "Model Name": key = 'model_name' grains[key] = _clean_value(key, field_val) if field_name.strip() == "Boot ROM Version": key = 'boot_rom_version' grains[key] = _clean_value(key, field_val) if field_name.strip() == "SMC Version (system)": key = 'smc_version' grains[key] = _clean_value(key, field_val) if field_name.strip() == "Serial Number (system)": key = 'system_serialnumber' grains[key] = _clean_value(key, field_val) return grains def id_(): ''' Return the id ''' return {'id': __opts__.get('id', '')} _REPLACE_LINUX_RE = re.compile(r'\W(?:gnu/)?linux', re.IGNORECASE) # This maps (at most) the first ten characters (no spaces, lowercased) of # 'osfullname' to the 'os' grain that Salt traditionally uses. # Please see os_data() and _supported_dists. # If your system is not detecting properly it likely needs an entry here. _OS_NAME_MAP = { 'redhatente': 'RedHat', 'gentoobase': 'Gentoo', 'archarm': 'Arch ARM', 'arch': 'Arch', 'debian': 'Debian', 'raspbian': 'Raspbian', 'fedoraremi': 'Fedora', 'chapeau': 'Chapeau', 'korora': 'Korora', 'amazonami': 'Amazon', 'alt': 'ALT', 'enterprise': 'OEL', 'oracleserv': 'OEL', 'cloudserve': 'CloudLinux', 'cloudlinux': 'CloudLinux', 'pidora': 'Fedora', 'scientific': 'ScientificLinux', 'synology': 'Synology', 'nilrt': 'NILinuxRT', 'poky': 'Poky', 'manjaro': 'Manjaro', 'manjarolin': 'Manjaro', 'univention': 'Univention', 'antergos': 'Antergos', 'sles': 'SUSE', 'void': 'Void', 'slesexpand': 'RES', 'linuxmint': 'Mint', 'neon': 'KDE neon', } # Map the 'os' grain to the 'os_family' grain # These should always be capitalized entries as the lookup comes # post-_OS_NAME_MAP. If your system is having trouble with detection, please # make sure that the 'os' grain is capitalized and working correctly first. _OS_FAMILY_MAP = { 'Ubuntu': 'Debian', 'Fedora': 'RedHat', 'Chapeau': 'RedHat', 'Korora': 'RedHat', 'FedBerry': 'RedHat', 'CentOS': 'RedHat', 'GoOSe': 'RedHat', 'Scientific': 'RedHat', 'Amazon': 'RedHat', 'CloudLinux': 'RedHat', 'OVS': 'RedHat', 'OEL': 'RedHat', 'XCP': 'RedHat', 'XCP-ng': 'RedHat', 'XenServer': 'RedHat', 'RES': 'RedHat', 'Sangoma': 'RedHat', 'Mandrake': 'Mandriva', 'ESXi': 'VMware', 'Mint': 'Debian', 'VMwareESX': 'VMware', 'Bluewhite64': 'Bluewhite', 'Slamd64': 'Slackware', 'SLES': 'Suse', 'SUSE Enterprise Server': 'Suse', 'SUSE Enterprise Server': 'Suse', 'SLED': 'Suse', 'openSUSE': 'Suse', 'SUSE': 'Suse', 'openSUSE Leap': 'Suse', 'openSUSE Tumbleweed': 'Suse', 'SLES_SAP': 'Suse', 'Solaris': 'Solaris', 'SmartOS': 'Solaris', 'OmniOS': 'Solaris', 'OpenIndiana Development': 'Solaris', 'OpenIndiana': 'Solaris', 'OpenSolaris Development': 'Solaris', 'OpenSolaris': 'Solaris', 'Oracle Solaris': 'Solaris', 'Arch ARM': 'Arch', 'Manjaro': 'Arch', 'Antergos': 'Arch', 'ALT': 'RedHat', 'Trisquel': 'Debian', 'GCEL': 'Debian', 'Linaro': 'Debian', 'elementary OS': 'Debian', 'elementary': 'Debian', 'Univention': 'Debian', 'ScientificLinux': 'RedHat', 'Raspbian': 'Debian', 'Devuan': 'Debian', 'antiX': 'Debian', 'Kali': 'Debian', 'neon': 'Debian', 'Cumulus': 'Debian', 'Deepin': 'Debian', 'NILinuxRT': 'NILinuxRT', 'KDE neon': 'Debian', 'Void': 'Void', 'IDMS': 'Debian', 'Funtoo': 'Gentoo', 'AIX': 'AIX', 'TurnKey': 'Debian', } # Matches any possible format: # DISTRIB_ID="Ubuntu" # DISTRIB_ID='Mageia' # DISTRIB_ID=Fedora # DISTRIB_RELEASE='10.10' # DISTRIB_CODENAME='squeeze' # DISTRIB_DESCRIPTION='Ubuntu 10.10' _LSB_REGEX = re.compile(( '^(DISTRIB_(?:ID|RELEASE|CODENAME|DESCRIPTION))=(?:\'|")?' '([\\w\\s\\.\\-_]+)(?:\'|")?' )) def _linux_bin_exists(binary): ''' Does a binary exist in linux (depends on which, type, or whereis) ''' for search_cmd in ('which', 'type -ap'): try: return __salt__['cmd.retcode']( '{0} {1}'.format(search_cmd, binary) ) == 0 except salt.exceptions.CommandExecutionError: pass try: return len(__salt__['cmd.run_all']( 'whereis -b {0}'.format(binary) )['stdout'].split()) > 1 except salt.exceptions.CommandExecutionError: return False def _get_interfaces(): ''' Provide a dict of the connected interfaces and their ip addresses ''' global _INTERFACES if not _INTERFACES: _INTERFACES = salt.utils.network.interfaces() return _INTERFACES def _parse_lsb_release(): ret = {} try: log.trace('Attempting to parse /etc/lsb-release') with salt.utils.files.fopen('/etc/lsb-release') as ifile: for line in ifile: try: key, value = _LSB_REGEX.match(line.rstrip('\n')).groups()[:2] except AttributeError: pass else: # Adds lsb_distrib_{id,release,codename,description} ret['lsb_{0}'.format(key.lower())] = value.rstrip() except (IOError, OSError) as exc: log.trace('Failed to parse /etc/lsb-release: %s', exc) return ret def _parse_os_release(*os_release_files): ''' Parse os-release and return a parameter dictionary See http://www.freedesktop.org/software/systemd/man/os-release.html for specification of the file format. ''' ret = {} for filename in os_release_files: try: with salt.utils.files.fopen(filename) as ifile: regex = re.compile('^([\\w]+)=(?:\'|")?(.*?)(?:\'|")?$') for line in ifile: match = regex.match(line.strip()) if match: # Shell special characters ("$", quotes, backslash, # backtick) are escaped with backslashes ret[match.group(1)] = re.sub( r'\\([$"\'\\`])', r'\1', match.group(2) ) break except (IOError, OSError): pass return ret def _parse_cpe_name(cpe): ''' Parse CPE_NAME data from the os-release Info: https://csrc.nist.gov/projects/security-content-automation-protocol/scap-specifications/cpe :param cpe: :return: ''' part = { 'o': 'operating system', 'h': 'hardware', 'a': 'application', } ret = {} cpe = (cpe or '').split(':') if len(cpe) > 4 and cpe[0] == 'cpe': if cpe[1].startswith('/'): # WFN to URI ret['vendor'], ret['product'], ret['version'] = cpe[2:5] ret['phase'] = cpe[5] if len(cpe) > 5 else None ret['part'] = part.get(cpe[1][1:]) elif len(cpe) == 13 and cpe[1] == '2.3': # WFN to a string ret['vendor'], ret['product'], ret['version'], ret['phase'] = [x if x != '*' else None for x in cpe[3:7]] ret['part'] = part.get(cpe[2]) return ret def os_data(): ''' Return grains pertaining to the operating system ''' grains = { 'num_gpus': 0, 'gpus': [], } # Windows Server 2008 64-bit # ('Windows', 'MINIONNAME', '2008ServerR2', '6.1.7601', 'AMD64', # 'Intel64 Fam ily 6 Model 23 Stepping 6, GenuineIntel') # Ubuntu 10.04 # ('Linux', 'MINIONNAME', '2.6.32-38-server', # '#83-Ubuntu SMP Wed Jan 4 11:26:59 UTC 2012', 'x86_64', '') # pylint: disable=unpacking-non-sequence (grains['kernel'], grains['nodename'], grains['kernelrelease'], grains['kernelversion'], grains['cpuarch'], _) = platform.uname() # pylint: enable=unpacking-non-sequence if salt.utils.platform.is_proxy(): grains['kernel'] = 'proxy' grains['kernelrelease'] = 'proxy' grains['kernelversion'] = 'proxy' grains['osrelease'] = 'proxy' grains['os'] = 'proxy' grains['os_family'] = 'proxy' grains['osfullname'] = 'proxy' elif salt.utils.platform.is_windows(): grains['os'] = 'Windows' grains['os_family'] = 'Windows' grains.update(_memdata(grains)) grains.update(_windows_platform_data()) grains.update(_windows_cpudata()) grains.update(_windows_virtual(grains)) grains.update(_ps(grains)) if 'Server' in grains['osrelease']: osrelease_info = grains['osrelease'].split('Server', 1) osrelease_info[1] = osrelease_info[1].lstrip('R') else: osrelease_info = grains['osrelease'].split('.') for idx, value in enumerate(osrelease_info): if not value.isdigit(): continue osrelease_info[idx] = int(value) grains['osrelease_info'] = tuple(osrelease_info) grains['osfinger'] = '{os}-{ver}'.format( os=grains['os'], ver=grains['osrelease']) grains['init'] = 'Windows' return grains elif salt.utils.platform.is_linux(): # Add SELinux grain, if you have it if _linux_bin_exists('selinuxenabled'): log.trace('Adding selinux grains') grains['selinux'] = {} grains['selinux']['enabled'] = __salt__['cmd.retcode']( 'selinuxenabled' ) == 0 if _linux_bin_exists('getenforce'): grains['selinux']['enforced'] = __salt__['cmd.run']( 'getenforce' ).strip() # Add systemd grain, if you have it if _linux_bin_exists('systemctl') and _linux_bin_exists('localectl'): log.trace('Adding systemd grains') grains['systemd'] = {} systemd_info = __salt__['cmd.run']( 'systemctl --version' ).splitlines() grains['systemd']['version'] = systemd_info[0].split()[1] grains['systemd']['features'] = systemd_info[1] # Add init grain grains['init'] = 'unknown' log.trace('Adding init grain') try: os.stat('/run/systemd/system') grains['init'] = 'systemd' except (OSError, IOError): try: with salt.utils.files.fopen('/proc/1/cmdline') as fhr: init_cmdline = fhr.read().replace('\x00', ' ').split() except (IOError, OSError): pass else: try: init_bin = salt.utils.path.which(init_cmdline[0]) except IndexError: # Emtpy init_cmdline init_bin = None log.warning('Unable to fetch data from /proc/1/cmdline') if init_bin is not None and init_bin.endswith('bin/init'): supported_inits = (b'upstart', b'sysvinit', b'systemd') edge_len = max(len(x) for x in supported_inits) - 1 try: buf_size = __opts__['file_buffer_size'] except KeyError: # Default to the value of file_buffer_size for the minion buf_size = 262144 try: with salt.utils.files.fopen(init_bin, 'rb') as fp_: edge = b'' buf = fp_.read(buf_size).lower() while buf: buf = edge + buf for item in supported_inits: if item in buf: if six.PY3: item = item.decode('utf-8') grains['init'] = item buf = b'' break edge = buf[-edge_len:] buf = fp_.read(buf_size).lower() except (IOError, OSError) as exc: log.error( 'Unable to read from init_bin (%s): %s', init_bin, exc ) elif salt.utils.path.which('supervisord') in init_cmdline: grains['init'] = 'supervisord' elif salt.utils.path.which('dumb-init') in init_cmdline: # https://github.com/Yelp/dumb-init grains['init'] = 'dumb-init' elif salt.utils.path.which('tini') in init_cmdline: # https://github.com/krallin/tini grains['init'] = 'tini' elif init_cmdline == ['runit']: grains['init'] = 'runit' elif '/sbin/my_init' in init_cmdline: # Phusion Base docker container use runit for srv mgmt, but # my_init as pid1 grains['init'] = 'runit' else: log.debug( 'Could not determine init system from command line: (%s)', ' '.join(init_cmdline) ) # Add lsb grains on any distro with lsb-release. Note that this import # can fail on systems with lsb-release installed if the system package # does not install the python package for the python interpreter used by # Salt (i.e. python2 or python3) try: log.trace('Getting lsb_release distro information') import lsb_release # pylint: disable=import-error release = lsb_release.get_distro_information() for key, value in six.iteritems(release): key = key.lower() lsb_param = 'lsb_{0}{1}'.format( '' if key.startswith('distrib_') else 'distrib_', key ) grains[lsb_param] = value # Catch a NameError to workaround possible breakage in lsb_release # See https://github.com/saltstack/salt/issues/37867 except (ImportError, NameError): # if the python library isn't available, try to parse # /etc/lsb-release using regex log.trace('lsb_release python bindings not available') grains.update(_parse_lsb_release()) if grains.get('lsb_distrib_description', '').lower().startswith('antergos'): # Antergos incorrectly configures their /etc/lsb-release, # setting the DISTRIB_ID to "Arch". This causes the "os" grain # to be incorrectly set to "Arch". grains['osfullname'] = 'Antergos Linux' elif 'lsb_distrib_id' not in grains: log.trace( 'Failed to get lsb_distrib_id, trying to parse os-release' ) os_release = _parse_os_release('/etc/os-release', '/usr/lib/os-release') if os_release: if 'NAME' in os_release: grains['lsb_distrib_id'] = os_release['NAME'].strip() if 'VERSION_ID' in os_release: grains['lsb_distrib_release'] = os_release['VERSION_ID'] if 'VERSION_CODENAME' in os_release: grains['lsb_distrib_codename'] = os_release['VERSION_CODENAME'] elif 'PRETTY_NAME' in os_release: codename = os_release['PRETTY_NAME'] # https://github.com/saltstack/salt/issues/44108 if os_release['ID'] == 'debian': codename_match = re.search(r'\((\w+)\)$', codename) if codename_match: codename = codename_match.group(1) grains['lsb_distrib_codename'] = codename if 'CPE_NAME' in os_release: cpe = _parse_cpe_name(os_release['CPE_NAME']) if not cpe: log.error('Broken CPE_NAME format in /etc/os-release!') elif cpe.get('vendor', '').lower() in ['suse', 'opensuse']: grains['os'] = "SUSE" # openSUSE `osfullname` grain normalization if os_release.get("NAME") == "openSUSE Leap": grains['osfullname'] = "Leap" elif os_release.get("VERSION") == "Tumbleweed": grains['osfullname'] = os_release["VERSION"] # Override VERSION_ID, if CPE_NAME around if cpe.get('version') and cpe.get('vendor') == 'opensuse': # Keep VERSION_ID for SLES grains['lsb_distrib_release'] = cpe['version'] elif os.path.isfile('/etc/SuSE-release'): log.trace('Parsing distrib info from /etc/SuSE-release') grains['lsb_distrib_id'] = 'SUSE' version = '' patch = '' with salt.utils.files.fopen('/etc/SuSE-release') as fhr: for line in fhr: if 'enterprise' in line.lower(): grains['lsb_distrib_id'] = 'SLES' grains['lsb_distrib_codename'] = re.sub(r'\(.+\)', '', line).strip() elif 'version' in line.lower(): version = re.sub(r'[^0-9]', '', line) elif 'patchlevel' in line.lower(): patch = re.sub(r'[^0-9]', '', line) grains['lsb_distrib_release'] = version if patch: grains['lsb_distrib_release'] += '.' + patch patchstr = 'SP' + patch if grains['lsb_distrib_codename'] and patchstr not in grains['lsb_distrib_codename']: grains['lsb_distrib_codename'] += ' ' + patchstr if not grains.get('lsb_distrib_codename'): grains['lsb_distrib_codename'] = 'n.a' elif os.path.isfile('/etc/altlinux-release'): log.trace('Parsing distrib info from /etc/altlinux-release') # ALT Linux grains['lsb_distrib_id'] = 'altlinux' with salt.utils.files.fopen('/etc/altlinux-release') as ifile: # This file is symlinked to from: # /etc/fedora-release # /etc/redhat-release # /etc/system-release for line in ifile: # ALT Linux Sisyphus (unstable) comps = line.split() if comps[0] == 'ALT': grains['lsb_distrib_release'] = comps[2] grains['lsb_distrib_codename'] = \ comps[3].replace('(', '').replace(')', '') elif os.path.isfile('/etc/centos-release'): log.trace('Parsing distrib info from /etc/centos-release') # Maybe CentOS Linux; could also be SUSE Expanded Support. # SUSE ES has both, centos-release and redhat-release. if os.path.isfile('/etc/redhat-release'): with salt.utils.files.fopen('/etc/redhat-release') as ifile: for line in ifile: if "red hat enterprise linux server" in line.lower(): # This is a SUSE Expanded Support Rhel installation grains['lsb_distrib_id'] = 'RedHat' break grains.setdefault('lsb_distrib_id', 'CentOS') with salt.utils.files.fopen('/etc/centos-release') as ifile: for line in ifile: # Need to pull out the version and codename # in the case of custom content in /etc/centos-release find_release = re.compile(r'\d+\.\d+') find_codename = re.compile(r'(?<=\()(.*?)(?=\))') release = find_release.search(line) codename = find_codename.search(line) if release is not None: grains['lsb_distrib_release'] = release.group() if codename is not None: grains['lsb_distrib_codename'] = codename.group() elif os.path.isfile('/etc.defaults/VERSION') \ and os.path.isfile('/etc.defaults/synoinfo.conf'): grains['osfullname'] = 'Synology' log.trace( 'Parsing Synology distrib info from /etc/.defaults/VERSION' ) with salt.utils.files.fopen('/etc.defaults/VERSION', 'r') as fp_: synoinfo = {} for line in fp_: try: key, val = line.rstrip('\n').split('=') except ValueError: continue if key in ('majorversion', 'minorversion', 'buildnumber'): synoinfo[key] = val.strip('"') if len(synoinfo) != 3: log.warning( 'Unable to determine Synology version info. ' 'Please report this, as it is likely a bug.' ) else: grains['osrelease'] = ( '{majorversion}.{minorversion}-{buildnumber}' .format(**synoinfo) ) # Use the already intelligent platform module to get distro info # (though apparently it's not intelligent enough to strip quotes) log.trace( 'Getting OS name, release, and codename from ' 'distro.linux_distribution()' ) (osname, osrelease, oscodename) = \ [x.strip('"').strip("'") for x in linux_distribution(supported_dists=_supported_dists)] # Try to assign these three names based on the lsb info, they tend to # be more accurate than what python gets from /etc/DISTRO-release. # It's worth noting that Ubuntu has patched their Python distribution # so that linux_distribution() does the /etc/lsb-release parsing, but # we do it anyway here for the sake for full portability. if 'osfullname' not in grains: # If NI Linux RT distribution, set the grains['osfullname'] to 'nilrt' if grains.get('lsb_distrib_id', '').lower().startswith('nilrt'): grains['osfullname'] = 'nilrt' else: grains['osfullname'] = grains.get('lsb_distrib_id', osname).strip() if 'osrelease' not in grains: # NOTE: This is a workaround for CentOS 7 os-release bug # https://bugs.centos.org/view.php?id=8359 # /etc/os-release contains no minor distro release number so we fall back to parse # /etc/centos-release file instead. # Commit introducing this comment should be reverted after the upstream bug is released. if 'CentOS Linux 7' in grains.get('lsb_distrib_codename', ''): grains.pop('lsb_distrib_release', None) grains['osrelease'] = grains.get('lsb_distrib_release', osrelease).strip() grains['oscodename'] = grains.get('lsb_distrib_codename', '').strip() or oscodename if 'Red Hat' in grains['oscodename']: grains['oscodename'] = oscodename distroname = _REPLACE_LINUX_RE.sub('', grains['osfullname']).strip() # return the first ten characters with no spaces, lowercased shortname = distroname.replace(' ', '').lower()[:10] # this maps the long names from the /etc/DISTRO-release files to the # traditional short names that Salt has used. if 'os' not in grains: grains['os'] = _OS_NAME_MAP.get(shortname, distroname) grains.update(_linux_cpudata()) grains.update(_linux_gpu_data()) elif grains['kernel'] == 'SunOS': if salt.utils.platform.is_smartos(): # See https://github.com/joyent/smartos-live/issues/224 if HAS_UNAME: uname_v = os.uname()[3] # format: joyent_20161101T004406Z else: uname_v = os.name uname_v = uname_v[uname_v.index('_')+1:] grains['os'] = grains['osfullname'] = 'SmartOS' # store a parsed version of YYYY.MM.DD as osrelease grains['osrelease'] = ".".join([ uname_v.split('T')[0][0:4], uname_v.split('T')[0][4:6], uname_v.split('T')[0][6:8], ]) # store a untouched copy of the timestamp in osrelease_stamp grains['osrelease_stamp'] = uname_v elif os.path.isfile('/etc/release'): with salt.utils.files.fopen('/etc/release', 'r') as fp_: rel_data = fp_.read() try: release_re = re.compile( r'((?:Open|Oracle )?Solaris|OpenIndiana|OmniOS) (Development)?' r'\s*(\d+\.?\d*|v\d+)\s?[A-Z]*\s?(r\d+|\d+\/\d+|oi_\S+|snv_\S+)?' ) osname, development, osmajorrelease, osminorrelease = release_re.search(rel_data).groups() except AttributeError: # Set a blank osrelease grain and fallback to 'Solaris' # as the 'os' grain. grains['os'] = grains['osfullname'] = 'Solaris' grains['osrelease'] = '' else: if development is not None: osname = ' '.join((osname, development)) if HAS_UNAME: uname_v = os.uname()[3] else: uname_v = os.name grains['os'] = grains['osfullname'] = osname if osname in ['Oracle Solaris'] and uname_v.startswith(osmajorrelease): # Oracla Solars 11 and up have minor version in uname grains['osrelease'] = uname_v elif osname in ['OmniOS']: # OmniOS osrelease = [] osrelease.append(osmajorrelease[1:]) osrelease.append(osminorrelease[1:]) grains['osrelease'] = ".".join(osrelease) grains['osrelease_stamp'] = uname_v else: # Sun Solaris 10 and earlier/comparable osrelease = [] osrelease.append(osmajorrelease) if osminorrelease: osrelease.append(osminorrelease) grains['osrelease'] = ".".join(osrelease) grains['osrelease_stamp'] = uname_v grains.update(_sunos_cpudata()) elif grains['kernel'] == 'VMkernel': grains['os'] = 'ESXi' elif grains['kernel'] == 'Darwin': osrelease = __salt__['cmd.run']('sw_vers -productVersion') osname = __salt__['cmd.run']('sw_vers -productName') osbuild = __salt__['cmd.run']('sw_vers -buildVersion') grains['os'] = 'MacOS' grains['os_family'] = 'MacOS' grains['osfullname'] = "{0} {1}".format(osname, osrelease) grains['osrelease'] = osrelease grains['osbuild'] = osbuild grains['init'] = 'launchd' grains.update(_bsd_cpudata(grains)) grains.update(_osx_gpudata()) grains.update(_osx_platform_data()) elif grains['kernel'] == 'AIX': osrelease = __salt__['cmd.run']('oslevel') osrelease_techlevel = __salt__['cmd.run']('oslevel -r') osname = __salt__['cmd.run']('uname') grains['os'] = 'AIX' grains['osfullname'] = osname grains['osrelease'] = osrelease grains['osrelease_techlevel'] = osrelease_techlevel grains.update(_aix_cpudata()) else: grains['os'] = grains['kernel'] if grains['kernel'] == 'FreeBSD': try: grains['osrelease'] = __salt__['cmd.run']('freebsd-version -u').split('-')[0] except salt.exceptions.CommandExecutionError: # freebsd-version was introduced in 10.0. # derive osrelease from kernelversion prior to that grains['osrelease'] = grains['kernelrelease'].split('-')[0] grains.update(_bsd_cpudata(grains)) if grains['kernel'] in ('OpenBSD', 'NetBSD'): grains.update(_bsd_cpudata(grains)) grains['osrelease'] = grains['kernelrelease'].split('-')[0] if grains['kernel'] == 'NetBSD': grains.update(_netbsd_gpu_data()) if not grains['os']: grains['os'] = 'Unknown {0}'.format(grains['kernel']) grains['os_family'] = 'Unknown' else: # this assigns family names based on the os name # family defaults to the os name if not found grains['os_family'] = _OS_FAMILY_MAP.get(grains['os'], grains['os']) # Build the osarch grain. This grain will be used for platform-specific # considerations such as package management. Fall back to the CPU # architecture. if grains.get('os_family') == 'Debian': osarch = __salt__['cmd.run']('dpkg --print-architecture').strip() elif grains.get('os_family') in ['RedHat', 'Suse']: osarch = salt.utils.pkg.rpm.get_osarch() elif grains.get('os_family') in ('NILinuxRT', 'Poky'): archinfo = {} for line in __salt__['cmd.run']('opkg print-architecture').splitlines(): if line.startswith('arch'): _, arch, priority = line.split() archinfo[arch.strip()] = int(priority.strip()) # Return osarch in priority order (higher to lower) osarch = sorted(archinfo, key=archinfo.get, reverse=True) else: osarch = grains['cpuarch'] grains['osarch'] = osarch grains.update(_memdata(grains)) # Get the hardware and bios data grains.update(_hw_data(grains)) # Load the virtual machine info grains.update(_virtual(grains)) grains.update(_virtual_hv(grains)) grains.update(_ps(grains)) if grains.get('osrelease', ''): osrelease_info = grains['osrelease'].split('.') for idx, value in enumerate(osrelease_info): if not value.isdigit(): continue osrelease_info[idx] = int(value) grains['osrelease_info'] = tuple(osrelease_info) try: grains['osmajorrelease'] = int(grains['osrelease_info'][0]) except (IndexError, TypeError, ValueError): log.debug( 'Unable to derive osmajorrelease from osrelease_info \'%s\'. ' 'The osmajorrelease grain will not be set.', grains['osrelease_info'] ) os_name = grains['os' if grains.get('os') in ( 'Debian', 'FreeBSD', 'OpenBSD', 'NetBSD', 'Mac', 'Raspbian') else 'osfullname'] grains['osfinger'] = '{0}-{1}'.format( os_name, grains['osrelease'] if os_name in ('Ubuntu',) else grains['osrelease_info'][0]) return grains def locale_info(): ''' Provides defaultlanguage defaultencoding ''' grains = {} grains['locale_info'] = {} if salt.utils.platform.is_proxy(): return grains try: ( grains['locale_info']['defaultlanguage'], grains['locale_info']['defaultencoding'] ) = locale.getdefaultlocale() except Exception: # locale.getdefaultlocale can ValueError!! Catch anything else it # might do, per #2205 grains['locale_info']['defaultlanguage'] = 'unknown' grains['locale_info']['defaultencoding'] = 'unknown' grains['locale_info']['detectedencoding'] = __salt_system_encoding__ if _DATEUTIL_TZ: grains['locale_info']['timezone'] = datetime.datetime.now(dateutil.tz.tzlocal()).tzname() return grains def hostname(): ''' Return fqdn, hostname, domainname ''' # This is going to need some work # Provides: # fqdn # host # localhost # domain global __FQDN__ grains = {} if salt.utils.platform.is_proxy(): return grains grains['localhost'] = socket.gethostname() if __FQDN__ is None: __FQDN__ = salt.utils.network.get_fqhostname() # On some distros (notably FreeBSD) if there is no hostname set # salt.utils.network.get_fqhostname() will return None. # In this case we punt and log a message at error level, but force the # hostname and domain to be localhost.localdomain # Otherwise we would stacktrace below if __FQDN__ is None: # still! log.error('Having trouble getting a hostname. Does this machine have its hostname and domain set properly?') __FQDN__ = 'localhost.localdomain' grains['fqdn'] = __FQDN__ (grains['host'], grains['domain']) = grains['fqdn'].partition('.')[::2] return grains def append_domain(): ''' Return append_domain if set ''' grain = {} if salt.utils.platform.is_proxy(): return grain if 'append_domain' in __opts__: grain['append_domain'] = __opts__['append_domain'] return grain def fqdns(): ''' Return all known FQDNs for the system by enumerating all interfaces and then trying to reverse resolve them (excluding 'lo' interface). ''' # Provides: # fqdns grains = {} fqdns = set() addresses = salt.utils.network.ip_addrs(include_loopback=False, interface_data=_get_interfaces()) addresses.extend(salt.utils.network.ip_addrs6(include_loopback=False, interface_data=_get_interfaces())) err_message = 'Exception during resolving address: %s' for ip in addresses: try: name, aliaslist, addresslist = socket.gethostbyaddr(ip) fqdns.update([socket.getfqdn(name)] + [als for als in aliaslist if salt.utils.network.is_fqdn(als)]) except socket.herror as err: if err.errno == 0: # No FQDN for this IP address, so we don't need to know this all the time. log.debug("Unable to resolve address %s: %s", ip, err) else: log.error(err_message, err) except (socket.error, socket.gaierror, socket.timeout) as err: log.error(err_message, err) return {"fqdns": sorted(list(fqdns))} def ip_fqdn(): ''' Return ip address and FQDN grains ''' if salt.utils.platform.is_proxy(): return {} ret = {} ret['ipv4'] = salt.utils.network.ip_addrs(include_loopback=True) ret['ipv6'] = salt.utils.network.ip_addrs6(include_loopback=True) _fqdn = hostname()['fqdn'] for socket_type, ipv_num in ((socket.AF_INET, '4'), (socket.AF_INET6, '6')): key = 'fqdn_ip' + ipv_num if not ret['ipv' + ipv_num]: ret[key] = [] else: try: start_time = datetime.datetime.utcnow() info = socket.getaddrinfo(_fqdn, None, socket_type) ret[key] = list(set(item[4][0] for item in info)) except socket.error: timediff = datetime.datetime.utcnow() - start_time if timediff.seconds > 5 and __opts__['__role'] == 'master': log.warning( 'Unable to find IPv%s record for "%s" causing a %s ' 'second timeout when rendering grains. Set the dns or ' '/etc/hosts for IPv%s to clear this.', ipv_num, _fqdn, timediff, ipv_num ) ret[key] = [] return ret def ip_interfaces(): ''' Provide a dict of the connected interfaces and their ip addresses The addresses will be passed as a list for each interface ''' # Provides: # ip_interfaces if salt.utils.platform.is_proxy(): return {} ret = {} ifaces = _get_interfaces() for face in ifaces: iface_ips = [] for inet in ifaces[face].get('inet', []): if 'address' in inet: iface_ips.append(inet['address']) for inet in ifaces[face].get('inet6', []): if 'address' in inet: iface_ips.append(inet['address']) for secondary in ifaces[face].get('secondary', []): if 'address' in secondary: iface_ips.append(secondary['address']) ret[face] = iface_ips return {'ip_interfaces': ret} def ip4_interfaces(): ''' Provide a dict of the connected interfaces and their ip4 addresses The addresses will be passed as a list for each interface ''' # Provides: # ip_interfaces if salt.utils.platform.is_proxy(): return {} ret = {} ifaces = _get_interfaces() for face in ifaces: iface_ips = [] for inet in ifaces[face].get('inet', []): if 'address' in inet: iface_ips.append(inet['address']) for secondary in ifaces[face].get('secondary', []): if 'address' in secondary: iface_ips.append(secondary['address']) ret[face] = iface_ips return {'ip4_interfaces': ret} def ip6_interfaces(): ''' Provide a dict of the connected interfaces and their ip6 addresses The addresses will be passed as a list for each interface ''' # Provides: # ip_interfaces if salt.utils.platform.is_proxy(): return {} ret = {} ifaces = _get_interfaces() for face in ifaces: iface_ips = [] for inet in ifaces[face].get('inet6', []): if 'address' in inet: iface_ips.append(inet['address']) for secondary in ifaces[face].get('secondary', []): if 'address' in secondary: iface_ips.append(secondary['address']) ret[face] = iface_ips return {'ip6_interfaces': ret} def hwaddr_interfaces(): ''' Provide a dict of the connected interfaces and their hw addresses (Mac Address) ''' # Provides: # hwaddr_interfaces ret = {} ifaces = _get_interfaces() for face in ifaces: if 'hwaddr' in ifaces[face]: ret[face] = ifaces[face]['hwaddr'] return {'hwaddr_interfaces': ret} def dns(): ''' Parse the resolver configuration file .. versionadded:: 2016.3.0 ''' # Provides: # dns if salt.utils.platform.is_windows() or 'proxyminion' in __opts__: return {} resolv = salt.utils.dns.parse_resolv() for key in ('nameservers', 'ip4_nameservers', 'ip6_nameservers', 'sortlist'): if key in resolv: resolv[key] = [six.text_type(i) for i in resolv[key]] return {'dns': resolv} if resolv else {} def get_machine_id(): ''' Provide the machine-id for machine/virtualization combination ''' # Provides: # machine-id if platform.system() == 'AIX': return _aix_get_machine_id() locations = ['/etc/machine-id', '/var/lib/dbus/machine-id'] existing_locations = [loc for loc in locations if os.path.exists(loc)] if not existing_locations: return {} else: with salt.utils.files.fopen(existing_locations[0]) as machineid: return {'machine_id': machineid.read().strip()} def cwd(): ''' Current working directory ''' return {'cwd': os.getcwd()} def path(): ''' Return the path ''' # Provides: # path return {'path': os.environ.get('PATH', '').strip()} def pythonversion(): ''' Return the Python version ''' # Provides: # pythonversion return {'pythonversion': list(sys.version_info)} def pythonpath(): ''' Return the Python path ''' # Provides: # pythonpath return {'pythonpath': sys.path} def pythonexecutable(): ''' Return the python executable in use ''' # Provides: # pythonexecutable return {'pythonexecutable': sys.executable} def saltpath(): ''' Return the path of the salt module ''' # Provides: # saltpath salt_path = os.path.abspath(os.path.join(__file__, os.path.pardir)) return {'saltpath': os.path.dirname(salt_path)} def saltversion(): ''' Return the version of salt ''' # Provides: # saltversion from salt.version import __version__ return {'saltversion': __version__} def zmqversion(): ''' Return the zeromq version ''' # Provides: # zmqversion try: import zmq return {'zmqversion': zmq.zmq_version()} # pylint: disable=no-member except ImportError: return {} def saltversioninfo(): ''' Return the version_info of salt .. versionadded:: 0.17.0 ''' # Provides: # saltversioninfo from salt.version import __version_info__ return {'saltversioninfo': list(__version_info__)} def _hw_data(osdata): ''' Get system specific hardware data from dmidecode Provides biosversion productname manufacturer serialnumber biosreleasedate uuid .. versionadded:: 0.9.5 ''' if salt.utils.platform.is_proxy(): return {} grains = {} if osdata['kernel'] == 'Linux' and os.path.exists('/sys/class/dmi/id'): # On many Linux distributions basic firmware information is available via sysfs # requires CONFIG_DMIID to be enabled in the Linux kernel configuration sysfs_firmware_info = { 'biosversion': 'bios_version', 'productname': 'product_name', 'manufacturer': 'sys_vendor', 'biosreleasedate': 'bios_date', 'uuid': 'product_uuid', 'serialnumber': 'product_serial' } for key, fw_file in sysfs_firmware_info.items(): contents_file = os.path.join('/sys/class/dmi/id', fw_file) if os.path.exists(contents_file): try: with salt.utils.files.fopen(contents_file, 'r') as ifile: grains[key] = salt.utils.stringutils.to_unicode(ifile.read().strip(), errors='replace') if key == 'uuid': grains['uuid'] = grains['uuid'].lower() except (IOError, OSError) as err: # PermissionError is new to Python 3, but corresponds to the EACESS and # EPERM error numbers. Use those instead here for PY2 compatibility. if err.errno == EACCES or err.errno == EPERM: # Skip the grain if non-root user has no access to the file. pass elif salt.utils.path.which_bin(['dmidecode', 'smbios']) is not None and not ( salt.utils.platform.is_smartos() or ( # SunOS on SPARC - 'smbios: failed to load SMBIOS: System does not export an SMBIOS table' osdata['kernel'] == 'SunOS' and osdata['cpuarch'].startswith('sparc') )): # On SmartOS (possibly SunOS also) smbios only works in the global zone # smbios is also not compatible with linux's smbios (smbios -s = print summarized) grains = { 'biosversion': __salt__['smbios.get']('bios-version'), 'productname': __salt__['smbios.get']('system-product-name'), 'manufacturer': __salt__['smbios.get']('system-manufacturer'), 'biosreleasedate': __salt__['smbios.get']('bios-release-date'), 'uuid': __salt__['smbios.get']('system-uuid') } grains = dict([(key, val) for key, val in grains.items() if val is not None]) uuid = __salt__['smbios.get']('system-uuid') if uuid is not None: grains['uuid'] = uuid.lower() for serial in ('system-serial-number', 'chassis-serial-number', 'baseboard-serial-number'): serial = __salt__['smbios.get'](serial) if serial is not None: grains['serialnumber'] = serial break elif salt.utils.path.which_bin(['fw_printenv']) is not None: # ARM Linux devices expose UBOOT env variables via fw_printenv hwdata = { 'manufacturer': 'manufacturer', 'serialnumber': 'serial#', 'productname': 'DeviceDesc', } for grain_name, cmd_key in six.iteritems(hwdata): result = __salt__['cmd.run_all']('fw_printenv {0}'.format(cmd_key)) if result['retcode'] == 0: uboot_keyval = result['stdout'].split('=') grains[grain_name] = _clean_value(grain_name, uboot_keyval[1]) elif osdata['kernel'] == 'FreeBSD': # On FreeBSD /bin/kenv (already in base system) # can be used instead of dmidecode kenv = salt.utils.path.which('kenv') if kenv: # In theory, it will be easier to add new fields to this later fbsd_hwdata = { 'biosversion': 'smbios.bios.version', 'manufacturer': 'smbios.system.maker', 'serialnumber': 'smbios.system.serial', 'productname': 'smbios.system.product', 'biosreleasedate': 'smbios.bios.reldate', 'uuid': 'smbios.system.uuid', } for key, val in six.iteritems(fbsd_hwdata): value = __salt__['cmd.run']('{0} {1}'.format(kenv, val)) grains[key] = _clean_value(key, value) elif osdata['kernel'] == 'OpenBSD': sysctl = salt.utils.path.which('sysctl') hwdata = {'biosversion': 'hw.version', 'manufacturer': 'hw.vendor', 'productname': 'hw.product', 'serialnumber': 'hw.serialno', 'uuid': 'hw.uuid'} for key, oid in six.iteritems(hwdata): value = __salt__['cmd.run']('{0} -n {1}'.format(sysctl, oid)) if not value.endswith(' value is not available'): grains[key] = _clean_value(key, value) elif osdata['kernel'] == 'NetBSD': sysctl = salt.utils.path.which('sysctl') nbsd_hwdata = { 'biosversion': 'machdep.dmi.board-version', 'manufacturer': 'machdep.dmi.system-vendor', 'serialnumber': 'machdep.dmi.system-serial', 'productname': 'machdep.dmi.system-product', 'biosreleasedate': 'machdep.dmi.bios-date', 'uuid': 'machdep.dmi.system-uuid', } for key, oid in six.iteritems(nbsd_hwdata): result = __salt__['cmd.run_all']('{0} -n {1}'.format(sysctl, oid)) if result['retcode'] == 0: grains[key] = _clean_value(key, result['stdout']) elif osdata['kernel'] == 'Darwin': grains['manufacturer'] = 'Apple Inc.' sysctl = salt.utils.path.which('sysctl') hwdata = {'productname': 'hw.model'} for key, oid in hwdata.items(): value = __salt__['cmd.run']('{0} -b {1}'.format(sysctl, oid)) if not value.endswith(' is invalid'): grains[key] = _clean_value(key, value) elif osdata['kernel'] == 'SunOS' and osdata['cpuarch'].startswith('sparc'): # Depending on the hardware model, commands can report different bits # of information. With that said, consolidate the output from various # commands and attempt various lookups. data = "" for (cmd, args) in (('/usr/sbin/prtdiag', '-v'), ('/usr/sbin/prtconf', '-vp'), ('/usr/sbin/virtinfo', '-a')): if salt.utils.path.which(cmd): # Also verifies that cmd is executable data += __salt__['cmd.run']('{0} {1}'.format(cmd, args)) data += '\n' sn_regexes = [ re.compile(r) for r in [ r'(?im)^\s*Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag r'(?im)^\s*chassis-sn:\s*(\S+)', # prtconf r'(?im)^\s*Chassis\s+Serial#:\s*(\S+)', # virtinfo ] ] obp_regexes = [ re.compile(r) for r in [ r'(?im)^\s*System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag r'(?im)^\s*version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf ] ] fw_regexes = [ re.compile(r) for r in [ r'(?im)^\s*Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag ] ] uuid_regexes = [ re.compile(r) for r in [ r'(?im)^\s*Domain\s+UUID:\s*(\S+)', # virtinfo ] ] manufacture_regexes = [ re.compile(r) for r in [ r'(?im)^\s*System\s+Configuration:\s*(.*)(?=sun)', # prtdiag ] ] product_regexes = [ re.compile(r) for r in [ r'(?im)^\s*System\s+Configuration:\s*.*?sun\d\S+[^\S\r\n]*(.*)', # prtdiag r'(?im)^[^\S\r\n]*banner-name:[^\S\r\n]*(.*)', # prtconf r'(?im)^[^\S\r\n]*product-name:[^\S\r\n]*(.*)', # prtconf ] ] sn_regexes = [ re.compile(r) for r in [ r'(?im)Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag r'(?i)Chassis\s+Serial#:\s*(\S+)', # virtinfo r'(?i)chassis-sn:\s*(\S+)', # prtconf ] ] obp_regexes = [ re.compile(r) for r in [ r'(?im)System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag r'(?im)version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf ] ] fw_regexes = [ re.compile(r) for r in [ r'(?i)Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag ] ] uuid_regexes = [ re.compile(r) for r in [ r'(?i)Domain\s+UUID:\s+(\S+)', # virtinfo ] ] for regex in sn_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: grains['serialnumber'] = res.group(1).strip().replace("'", "") break for regex in obp_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: obp_rev, obp_date = res.groups()[0:2] # Limit the number in case we found the data in multiple places grains['biosversion'] = obp_rev.strip().replace("'", "") grains['biosreleasedate'] = obp_date.strip().replace("'", "") for regex in fw_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: fw_rev, fw_date = res.groups()[0:2] grains['systemfirmware'] = fw_rev.strip().replace("'", "") grains['systemfirmwaredate'] = fw_date.strip().replace("'", "") break for regex in uuid_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: grains['uuid'] = res.group(1).strip().replace("'", "") break for regex in manufacture_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: grains['manufacture'] = res.group(1).strip().replace("'", "") break for regex in product_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: t_productname = res.group(1).strip().replace("'", "") if t_productname: grains['product'] = t_productname grains['productname'] = t_productname break elif osdata['kernel'] == 'AIX': cmd = salt.utils.path.which('prtconf') if cmd: data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'), ('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')): for regex in [re.compile(r) for r in [regstring]]: res = regex.search(data) if res and len(res.groups()) >= 1: grains[dest] = res.group(1).strip().replace("'", '') product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')] for regex in product_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",") break else: log.error('The \'prtconf\' binary was not found in $PATH.') elif osdata['kernel'] == 'AIX': cmd = salt.utils.path.which('prtconf') if data: data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'), ('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')): for regex in [re.compile(r) for r in [regstring]]: res = regex.search(data) if res and len(res.groups()) >= 1: grains[dest] = res.group(1).strip().replace("'", '') product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')] for regex in product_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",") break else: log.error('The \'prtconf\' binary was not found in $PATH.') return grains def get_server_id(): ''' Provides an integer based on the FQDN of a machine. Useful as server-id in MySQL replication or anywhere else you'll need an ID like this. ''' # Provides: # server_id if salt.utils.platform.is_proxy(): server_id = {} else: use_crc = __opts__.get('server_id_use_crc') if bool(use_crc): id_hash = getattr(zlib, use_crc, zlib.adler32)(__opts__.get('id', '').encode()) & 0xffffffff else: log.debug('This server_id is computed not by Adler32 nor by CRC32. ' 'Please use "server_id_use_crc" option and define algorithm you ' 'prefer (default "Adler32"). Starting with Sodium, the ' 'server_id will be computed with Adler32 by default.') id_hash = _get_hash_by_shell() server_id = {'server_id': id_hash} return server_id def get_master(): ''' Provides the minion with the name of its master. This is useful in states to target other services running on the master. ''' # Provides: # master return {'master': __opts__.get('master', '')} def default_gateway(): ''' Populates grains which describe whether a server has a default gateway configured or not. Uses `ip -4 route show` and `ip -6 route show` and greps for a `default` at the beginning of any line. Assuming the standard `default via <ip>` format for default gateways, it will also parse out the ip address of the default gateway, and put it in ip4_gw or ip6_gw. If the `ip` command is unavailable, no grains will be populated. Currently does not support multiple default gateways. The grains will be set to the first default gateway found. List of grains: ip4_gw: True # ip/True/False if default ipv4 gateway ip6_gw: True # ip/True/False if default ipv6 gateway ip_gw: True # True if either of the above is True, False otherwise ''' grains = {} ip_bin = salt.utils.path.which('ip') if not ip_bin: return {} grains['ip_gw'] = False grains['ip4_gw'] = False grains['ip6_gw'] = False for ip_version in ('4', '6'): try: out = __salt__['cmd.run']([ip_bin, '-' + ip_version, 'route', 'show']) for line in out.splitlines(): if line.startswith('default'): grains['ip_gw'] = True grains['ip{0}_gw'.format(ip_version)] = True try: via, gw_ip = line.split()[1:3] except ValueError: pass else: if via == 'via': grains['ip{0}_gw'.format(ip_version)] = gw_ip break except Exception: continue return grains def kernelparams(): ''' Return the kernel boot parameters ''' if salt.utils.platform.is_windows(): # TODO: add grains using `bcdedit /enum {current}` return {} else: try: with salt.utils.files.fopen('/proc/cmdline', 'r') as fhr: cmdline = fhr.read() grains = {'kernelparams': []} for data in [item.split('=') for item in salt.utils.args.shlex_split(cmdline)]: value = None if len(data) == 2: value = data[1].strip('"') grains['kernelparams'] += [(data[0], value)] except IOError as exc: grains = {} log.debug('Failed to read /proc/cmdline: %s', exc) return grains
saltstack/salt
salt/grains/core.py
get_server_id
python
def get_server_id(): ''' Provides an integer based on the FQDN of a machine. Useful as server-id in MySQL replication or anywhere else you'll need an ID like this. ''' # Provides: # server_id if salt.utils.platform.is_proxy(): server_id = {} else: use_crc = __opts__.get('server_id_use_crc') if bool(use_crc): id_hash = getattr(zlib, use_crc, zlib.adler32)(__opts__.get('id', '').encode()) & 0xffffffff else: log.debug('This server_id is computed not by Adler32 nor by CRC32. ' 'Please use "server_id_use_crc" option and define algorithm you ' 'prefer (default "Adler32"). Starting with Sodium, the ' 'server_id will be computed with Adler32 by default.') id_hash = _get_hash_by_shell() server_id = {'server_id': id_hash} return server_id
Provides an integer based on the FQDN of a machine. Useful as server-id in MySQL replication or anywhere else you'll need an ID like this.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/grains/core.py#L2765-L2788
[ "def _get_hash_by_shell():\n '''\n Shell-out Python 3 for compute reliable hash\n :return:\n '''\n id_ = __opts__.get('id', '')\n id_hash = None\n py_ver = sys.version_info[:2]\n if py_ver >= (3, 3):\n # Python 3.3 enabled hash randomization, so we need to shell out to get\n # a reliable hash.\n id_hash = __salt__['cmd.run']([sys.executable, '-c', 'print(hash(\"{0}\"))'.format(id_)],\n env={'PYTHONHASHSEED': '0'})\n try:\n id_hash = int(id_hash)\n except (TypeError, ValueError):\n log.debug('Failed to hash the ID to get the server_id grain. Result of hash command: %s', id_hash)\n id_hash = None\n if id_hash is None:\n # Python < 3.3 or error encountered above\n id_hash = hash(id_)\n\n return abs(id_hash % (2 ** 31))\n" ]
# -*- coding: utf-8 -*- ''' The static grains, these are the core, or built in grains. When grains are loaded they are not loaded in the same way that modules are loaded, grain functions are detected and executed, the functions MUST return a dict which will be applied to the main grains dict. This module will always be executed first, so that any grains loaded here in the core module can be overwritten just by returning dict keys with the same value as those returned here ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import socket import sys import re import platform import logging import locale import uuid import zlib from errno import EACCES, EPERM import datetime import warnings # pylint: disable=import-error try: import dateutil.tz _DATEUTIL_TZ = True except ImportError: _DATEUTIL_TZ = False __proxyenabled__ = ['*'] __FQDN__ = None # Extend the default list of supported distros. This will be used for the # /etc/DISTRO-release checking that is part of linux_distribution() from platform import _supported_dists _supported_dists += ('arch', 'mageia', 'meego', 'vmware', 'bluewhite64', 'slamd64', 'ovs', 'system', 'mint', 'oracle', 'void') # linux_distribution deprecated in py3.7 try: from platform import linux_distribution as _deprecated_linux_distribution def linux_distribution(**kwargs): with warnings.catch_warnings(): warnings.simplefilter("ignore") return _deprecated_linux_distribution(**kwargs) except ImportError: from distro import linux_distribution # Import salt libs import salt.exceptions import salt.log import salt.utils.args import salt.utils.dns import salt.utils.files import salt.utils.network import salt.utils.path import salt.utils.pkg.rpm import salt.utils.platform import salt.utils.stringutils import salt.utils.versions from salt.ext import six from salt.ext.six.moves import range if salt.utils.platform.is_windows(): import salt.utils.win_osinfo # Solve the Chicken and egg problem where grains need to run before any # of the modules are loaded and are generally available for any usage. import salt.modules.cmdmod import salt.modules.smbios __salt__ = { 'cmd.run': salt.modules.cmdmod._run_quiet, 'cmd.retcode': salt.modules.cmdmod._retcode_quiet, 'cmd.run_all': salt.modules.cmdmod._run_all_quiet, 'smbios.records': salt.modules.smbios.records, 'smbios.get': salt.modules.smbios.get, } log = logging.getLogger(__name__) HAS_WMI = False if salt.utils.platform.is_windows(): # attempt to import the python wmi module # the Windows minion uses WMI for some of its grains try: import wmi # pylint: disable=import-error import salt.utils.winapi import win32api import salt.utils.win_reg HAS_WMI = True except ImportError: log.exception( 'Unable to import Python wmi module, some core grains ' 'will be missing' ) HAS_UNAME = True if not hasattr(os, 'uname'): HAS_UNAME = False _INTERFACES = {} def _windows_cpudata(): ''' Return some CPU information on Windows minions ''' # Provides: # num_cpus # cpu_model grains = {} if 'NUMBER_OF_PROCESSORS' in os.environ: # Cast to int so that the logic isn't broken when used as a # conditional in templating. Also follows _linux_cpudata() try: grains['num_cpus'] = int(os.environ['NUMBER_OF_PROCESSORS']) except ValueError: grains['num_cpus'] = 1 grains['cpu_model'] = salt.utils.win_reg.read_value( hive="HKEY_LOCAL_MACHINE", key="HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", vname="ProcessorNameString").get('vdata') return grains def _linux_cpudata(): ''' Return some CPU information for Linux minions ''' # Provides: # num_cpus # cpu_model # cpu_flags grains = {} cpuinfo = '/proc/cpuinfo' # Parse over the cpuinfo file if os.path.isfile(cpuinfo): with salt.utils.files.fopen(cpuinfo, 'r') as _fp: grains['num_cpus'] = 0 for line in _fp: comps = line.split(':') if not len(comps) > 1: continue key = comps[0].strip() val = comps[1].strip() if key == 'processor': grains['num_cpus'] += 1 elif key == 'model name': grains['cpu_model'] = val elif key == 'flags': grains['cpu_flags'] = val.split() elif key == 'Features': grains['cpu_flags'] = val.split() # ARM support - /proc/cpuinfo # # Processor : ARMv6-compatible processor rev 7 (v6l) # BogoMIPS : 697.95 # Features : swp half thumb fastmult vfp edsp java tls # CPU implementer : 0x41 # CPU architecture: 7 # CPU variant : 0x0 # CPU part : 0xb76 # CPU revision : 7 # # Hardware : BCM2708 # Revision : 0002 # Serial : 00000000 elif key == 'Processor': grains['cpu_model'] = val.split('-')[0] grains['num_cpus'] = 1 if 'num_cpus' not in grains: grains['num_cpus'] = 0 if 'cpu_model' not in grains: grains['cpu_model'] = 'Unknown' if 'cpu_flags' not in grains: grains['cpu_flags'] = [] return grains def _linux_gpu_data(): ''' num_gpus: int gpus: - vendor: nvidia|amd|ati|... model: string ''' if __opts__.get('enable_lspci', True) is False: return {} if __opts__.get('enable_gpu_grains', True) is False: return {} lspci = salt.utils.path.which('lspci') if not lspci: log.debug( 'The `lspci` binary is not available on the system. GPU grains ' 'will not be available.' ) return {} # dominant gpu vendors to search for (MUST be lowercase for matching below) known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed'] gpu_classes = ('vga compatible controller', '3d controller') devs = [] try: lspci_out = __salt__['cmd.run']('{0} -vmm'.format(lspci)) cur_dev = {} error = False # Add a blank element to the lspci_out.splitlines() list, # otherwise the last device is not evaluated as a cur_dev and ignored. lspci_list = lspci_out.splitlines() lspci_list.append('') for line in lspci_list: # check for record-separating empty lines if line == '': if cur_dev.get('Class', '').lower() in gpu_classes: devs.append(cur_dev) cur_dev = {} continue if re.match(r'^\w+:\s+.*', line): key, val = line.split(':', 1) cur_dev[key.strip()] = val.strip() else: error = True log.debug('Unexpected lspci output: \'%s\'', line) if error: log.warning( 'Error loading grains, unexpected linux_gpu_data output, ' 'check that you have a valid shell configured and ' 'permissions to run lspci command' ) except OSError: pass gpus = [] for gpu in devs: vendor_strings = re.split('[^A-Za-z0-9]', gpu['Vendor'].lower()) # default vendor to 'unknown', overwrite if we match a known one vendor = 'unknown' for name in known_vendors: # search for an 'expected' vendor name in the list of strings if name in vendor_strings: vendor = name break gpus.append({'vendor': vendor, 'model': gpu['Device']}) grains = {} grains['num_gpus'] = len(gpus) grains['gpus'] = gpus return grains def _netbsd_gpu_data(): ''' num_gpus: int gpus: - vendor: nvidia|amd|ati|... model: string ''' known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed'] gpus = [] try: pcictl_out = __salt__['cmd.run']('pcictl pci0 list') for line in pcictl_out.splitlines(): for vendor in known_vendors: vendor_match = re.match( r'[0-9:]+ ({0}) (.+) \(VGA .+\)'.format(vendor), line, re.IGNORECASE ) if vendor_match: gpus.append({'vendor': vendor_match.group(1), 'model': vendor_match.group(2)}) except OSError: pass grains = {} grains['num_gpus'] = len(gpus) grains['gpus'] = gpus return grains def _osx_gpudata(): ''' num_gpus: int gpus: - vendor: nvidia|amd|ati|... model: string ''' gpus = [] try: pcictl_out = __salt__['cmd.run']('system_profiler SPDisplaysDataType') for line in pcictl_out.splitlines(): fieldname, _, fieldval = line.partition(': ') if fieldname.strip() == "Chipset Model": vendor, _, model = fieldval.partition(' ') vendor = vendor.lower() gpus.append({'vendor': vendor, 'model': model}) except OSError: pass grains = {} grains['num_gpus'] = len(gpus) grains['gpus'] = gpus return grains def _bsd_cpudata(osdata): ''' Return CPU information for BSD-like systems ''' # Provides: # cpuarch # num_cpus # cpu_model # cpu_flags sysctl = salt.utils.path.which('sysctl') arch = salt.utils.path.which('arch') cmds = {} if sysctl: cmds.update({ 'num_cpus': '{0} -n hw.ncpu'.format(sysctl), 'cpuarch': '{0} -n hw.machine'.format(sysctl), 'cpu_model': '{0} -n hw.model'.format(sysctl), }) if arch and osdata['kernel'] == 'OpenBSD': cmds['cpuarch'] = '{0} -s'.format(arch) if osdata['kernel'] == 'Darwin': cmds['cpu_model'] = '{0} -n machdep.cpu.brand_string'.format(sysctl) cmds['cpu_flags'] = '{0} -n machdep.cpu.features'.format(sysctl) grains = dict([(k, __salt__['cmd.run'](v)) for k, v in six.iteritems(cmds)]) if 'cpu_flags' in grains and isinstance(grains['cpu_flags'], six.string_types): grains['cpu_flags'] = grains['cpu_flags'].split(' ') if osdata['kernel'] == 'NetBSD': grains['cpu_flags'] = [] for line in __salt__['cmd.run']('cpuctl identify 0').splitlines(): cpu_match = re.match(r'cpu[0-9]:\ features[0-9]?\ .+<(.+)>', line) if cpu_match: flag = cpu_match.group(1).split(',') grains['cpu_flags'].extend(flag) if osdata['kernel'] == 'FreeBSD' and os.path.isfile('/var/run/dmesg.boot'): grains['cpu_flags'] = [] # TODO: at least it needs to be tested for BSD other then FreeBSD with salt.utils.files.fopen('/var/run/dmesg.boot', 'r') as _fp: cpu_here = False for line in _fp: if line.startswith('CPU: '): cpu_here = True # starts CPU descr continue if cpu_here: if not line.startswith(' '): break # game over if 'Features' in line: start = line.find('<') end = line.find('>') if start > 0 and end > 0: flag = line[start + 1:end].split(',') grains['cpu_flags'].extend(flag) try: grains['num_cpus'] = int(grains['num_cpus']) except ValueError: grains['num_cpus'] = 1 return grains def _sunos_cpudata(): ''' Return the CPU information for Solaris-like systems ''' # Provides: # cpuarch # num_cpus # cpu_model # cpu_flags grains = {} grains['cpu_flags'] = [] grains['cpuarch'] = __salt__['cmd.run']('isainfo -k') psrinfo = '/usr/sbin/psrinfo 2>/dev/null' grains['num_cpus'] = len(__salt__['cmd.run'](psrinfo, python_shell=True).splitlines()) kstat_info = 'kstat -p cpu_info:*:*:brand' for line in __salt__['cmd.run'](kstat_info).splitlines(): match = re.match(r'(\w+:\d+:\w+\d+:\w+)\s+(.+)', line) if match: grains['cpu_model'] = match.group(2) isainfo = 'isainfo -n -v' for line in __salt__['cmd.run'](isainfo).splitlines(): match = re.match(r'^\s+(.+)', line) if match: cpu_flags = match.group(1).split() grains['cpu_flags'].extend(cpu_flags) return grains def _aix_cpudata(): ''' Return CPU information for AIX systems ''' # Provides: # cpuarch # num_cpus # cpu_model # cpu_flags grains = {} cmd = salt.utils.path.which('prtconf') if cmd: data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep for dest, regstring in (('cpuarch', r'(?im)^\s*Processor\s+Type:\s+(\S+)'), ('cpu_flags', r'(?im)^\s*Processor\s+Version:\s+(\S+)'), ('cpu_model', r'(?im)^\s*Processor\s+Implementation\s+Mode:\s+(.*)'), ('num_cpus', r'(?im)^\s*Number\s+Of\s+Processors:\s+(\S+)')): for regex in [re.compile(r) for r in [regstring]]: res = regex.search(data) if res and len(res.groups()) >= 1: grains[dest] = res.group(1).strip().replace("'", '') else: log.error('The \'prtconf\' binary was not found in $PATH.') return grains def _linux_memdata(): ''' Return the memory information for Linux-like systems ''' grains = {'mem_total': 0, 'swap_total': 0} meminfo = '/proc/meminfo' if os.path.isfile(meminfo): with salt.utils.files.fopen(meminfo, 'r') as ifile: for line in ifile: comps = line.rstrip('\n').split(':') if not len(comps) > 1: continue if comps[0].strip() == 'MemTotal': # Use floor division to force output to be an integer grains['mem_total'] = int(comps[1].split()[0]) // 1024 if comps[0].strip() == 'SwapTotal': # Use floor division to force output to be an integer grains['swap_total'] = int(comps[1].split()[0]) // 1024 return grains def _osx_memdata(): ''' Return the memory information for BSD-like systems ''' grains = {'mem_total': 0, 'swap_total': 0} sysctl = salt.utils.path.which('sysctl') if sysctl: mem = __salt__['cmd.run']('{0} -n hw.memsize'.format(sysctl)) swap_total = __salt__['cmd.run']('{0} -n vm.swapusage'.format(sysctl)).split()[2].replace(',', '.') if swap_total.endswith('K'): _power = 2**10 elif swap_total.endswith('M'): _power = 2**20 elif swap_total.endswith('G'): _power = 2**30 swap_total = float(swap_total[:-1]) * _power grains['mem_total'] = int(mem) // 1024 // 1024 grains['swap_total'] = int(swap_total) // 1024 // 1024 return grains def _bsd_memdata(osdata): ''' Return the memory information for BSD-like systems ''' grains = {'mem_total': 0, 'swap_total': 0} sysctl = salt.utils.path.which('sysctl') if sysctl: mem = __salt__['cmd.run']('{0} -n hw.physmem'.format(sysctl)) if osdata['kernel'] == 'NetBSD' and mem.startswith('-'): mem = __salt__['cmd.run']('{0} -n hw.physmem64'.format(sysctl)) grains['mem_total'] = int(mem) // 1024 // 1024 if osdata['kernel'] in ['OpenBSD', 'NetBSD']: swapctl = salt.utils.path.which('swapctl') swap_data = __salt__['cmd.run']('{0} -sk'.format(swapctl)) if swap_data == 'no swap devices configured': swap_total = 0 else: swap_total = swap_data.split(' ')[1] else: swap_total = __salt__['cmd.run']('{0} -n vm.swap_total'.format(sysctl)) grains['swap_total'] = int(swap_total) // 1024 // 1024 return grains def _sunos_memdata(): ''' Return the memory information for SunOS-like systems ''' grains = {'mem_total': 0, 'swap_total': 0} prtconf = '/usr/sbin/prtconf 2>/dev/null' for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines(): comps = line.split(' ') if comps[0].strip() == 'Memory' and comps[1].strip() == 'size:': grains['mem_total'] = int(comps[2].strip()) swap_cmd = salt.utils.path.which('swap') swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split() try: swap_avail = int(swap_data[-2][:-1]) swap_used = int(swap_data[-4][:-1]) swap_total = (swap_avail + swap_used) // 1024 except ValueError: swap_total = None grains['swap_total'] = swap_total return grains def _aix_memdata(): ''' Return the memory information for AIX systems ''' grains = {'mem_total': 0, 'swap_total': 0} prtconf = salt.utils.path.which('prtconf') if prtconf: for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines(): comps = [x for x in line.strip().split(' ') if x] if len(comps) > 2 and 'Memory' in comps[0] and 'Size' in comps[1]: grains['mem_total'] = int(comps[2]) break else: log.error('The \'prtconf\' binary was not found in $PATH.') swap_cmd = salt.utils.path.which('swap') if swap_cmd: swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split() try: swap_total = (int(swap_data[-2]) + int(swap_data[-6])) * 4 except ValueError: swap_total = None grains['swap_total'] = swap_total else: log.error('The \'swap\' binary was not found in $PATH.') return grains def _windows_memdata(): ''' Return the memory information for Windows systems ''' grains = {'mem_total': 0} # get the Total Physical memory as reported by msinfo32 tot_bytes = win32api.GlobalMemoryStatusEx()['TotalPhys'] # return memory info in gigabytes grains['mem_total'] = int(tot_bytes / (1024 ** 2)) return grains def _memdata(osdata): ''' Gather information about the system memory ''' # Provides: # mem_total # swap_total, for supported systems. grains = {'mem_total': 0} if osdata['kernel'] == 'Linux': grains.update(_linux_memdata()) elif osdata['kernel'] in ('FreeBSD', 'OpenBSD', 'NetBSD'): grains.update(_bsd_memdata(osdata)) elif osdata['kernel'] == 'Darwin': grains.update(_osx_memdata()) elif osdata['kernel'] == 'SunOS': grains.update(_sunos_memdata()) elif osdata['kernel'] == 'AIX': grains.update(_aix_memdata()) elif osdata['kernel'] == 'Windows' and HAS_WMI: grains.update(_windows_memdata()) return grains def _aix_get_machine_id(): ''' Parse the output of lsattr -El sys0 for os_uuid ''' grains = {} cmd = salt.utils.path.which('lsattr') if cmd: data = __salt__['cmd.run']('{0} -El sys0'.format(cmd)) + os.linesep uuid_regexes = [re.compile(r'(?im)^\s*os_uuid\s+(\S+)\s+(.*)')] for regex in uuid_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: grains['machine_id'] = res.group(1).strip() break else: log.error('The \'lsattr\' binary was not found in $PATH.') return grains def _windows_virtual(osdata): ''' Returns what type of virtual hardware is under the hood, kvm or physical ''' # Provides: # virtual # virtual_subtype grains = dict() if osdata['kernel'] != 'Windows': return grains grains['virtual'] = 'physical' # It is possible that the 'manufacturer' and/or 'productname' grains # exist but have a value of None. manufacturer = osdata.get('manufacturer', '') if manufacturer is None: manufacturer = '' productname = osdata.get('productname', '') if productname is None: productname = '' if 'QEMU' in manufacturer: # FIXME: Make this detect between kvm or qemu grains['virtual'] = 'kvm' if 'Bochs' in manufacturer: grains['virtual'] = 'kvm' # Product Name: (oVirt) www.ovirt.org # Red Hat Community virtualization Project based on kvm elif 'oVirt' in productname: grains['virtual'] = 'kvm' grains['virtual_subtype'] = 'oVirt' # Red Hat Enterprise Virtualization elif 'RHEV Hypervisor' in productname: grains['virtual'] = 'kvm' grains['virtual_subtype'] = 'rhev' # Product Name: VirtualBox elif 'VirtualBox' in productname: grains['virtual'] = 'VirtualBox' # Product Name: VMware Virtual Platform elif 'VMware Virtual Platform' in productname: grains['virtual'] = 'VMware' # Manufacturer: Microsoft Corporation # Product Name: Virtual Machine elif 'Microsoft' in manufacturer and \ 'Virtual Machine' in productname: grains['virtual'] = 'VirtualPC' # Manufacturer: Parallels Software International Inc. elif 'Parallels Software' in manufacturer: grains['virtual'] = 'Parallels' # Apache CloudStack elif 'CloudStack KVM Hypervisor' in productname: grains['virtual'] = 'kvm' grains['virtual_subtype'] = 'cloudstack' return grains def _virtual(osdata): ''' Returns what type of virtual hardware is under the hood, kvm or physical ''' # This is going to be a monster, if you are running a vm you can test this # grain with please submit patches! # Provides: # virtual # virtual_subtype grains = {'virtual': 'physical'} # Skip the below loop on platforms which have none of the desired cmds # This is a temporary measure until we can write proper virtual hardware # detection. skip_cmds = ('AIX',) # list of commands to be executed to determine the 'virtual' grain _cmds = ['systemd-detect-virt', 'virt-what', 'dmidecode'] # test first for virt-what, which covers most of the desired functionality # on most platforms if not salt.utils.platform.is_windows() and osdata['kernel'] not in skip_cmds: if salt.utils.path.which('virt-what'): _cmds = ['virt-what'] # Check if enable_lspci is True or False if __opts__.get('enable_lspci', True) is True: # /proc/bus/pci does not exists, lspci will fail if os.path.exists('/proc/bus/pci'): _cmds += ['lspci'] # Add additional last resort commands if osdata['kernel'] in skip_cmds: _cmds = () # Quick backout for BrandZ (Solaris LX Branded zones) # Don't waste time trying other commands to detect the virtual grain if HAS_UNAME and osdata['kernel'] == 'Linux' and 'BrandZ virtual linux' in os.uname(): grains['virtual'] = 'zone' return grains failed_commands = set() for command in _cmds: args = [] if osdata['kernel'] == 'Darwin': command = 'system_profiler' args = ['SPDisplaysDataType'] elif osdata['kernel'] == 'SunOS': virtinfo = salt.utils.path.which('virtinfo') if virtinfo: try: ret = __salt__['cmd.run_all']('{0} -a'.format(virtinfo)) except salt.exceptions.CommandExecutionError: if salt.log.is_logging_configured(): failed_commands.add(virtinfo) else: if ret['stdout'].endswith('not supported'): command = 'prtdiag' else: command = 'virtinfo' else: command = 'prtdiag' cmd = salt.utils.path.which(command) if not cmd: continue cmd = '{0} {1}'.format(cmd, ' '.join(args)) try: ret = __salt__['cmd.run_all'](cmd) if ret['retcode'] > 0: if salt.log.is_logging_configured(): # systemd-detect-virt always returns > 0 on non-virtualized # systems # prtdiag only works in the global zone, skip if it fails if salt.utils.platform.is_windows() or 'systemd-detect-virt' in cmd or 'prtdiag' in cmd: continue failed_commands.add(command) continue except salt.exceptions.CommandExecutionError: if salt.log.is_logging_configured(): if salt.utils.platform.is_windows(): continue failed_commands.add(command) continue output = ret['stdout'] if command == "system_profiler": macoutput = output.lower() if '0x1ab8' in macoutput: grains['virtual'] = 'Parallels' if 'parallels' in macoutput: grains['virtual'] = 'Parallels' if 'vmware' in macoutput: grains['virtual'] = 'VMware' if '0x15ad' in macoutput: grains['virtual'] = 'VMware' if 'virtualbox' in macoutput: grains['virtual'] = 'VirtualBox' # Break out of the loop so the next log message is not issued break elif command == 'systemd-detect-virt': if output in ('qemu', 'kvm', 'oracle', 'xen', 'bochs', 'chroot', 'uml', 'systemd-nspawn'): grains['virtual'] = output break elif 'vmware' in output: grains['virtual'] = 'VMware' break elif 'microsoft' in output: grains['virtual'] = 'VirtualPC' break elif 'lxc' in output: grains['virtual'] = 'LXC' break elif 'systemd-nspawn' in output: grains['virtual'] = 'LXC' break elif command == 'virt-what': try: output = output.splitlines()[-1] except IndexError: pass if output in ('kvm', 'qemu', 'uml', 'xen', 'lxc'): grains['virtual'] = output break elif 'vmware' in output: grains['virtual'] = 'VMware' break elif 'parallels' in output: grains['virtual'] = 'Parallels' break elif 'hyperv' in output: grains['virtual'] = 'HyperV' break elif command == 'dmidecode': # Product Name: VirtualBox if 'Vendor: QEMU' in output: # FIXME: Make this detect between kvm or qemu grains['virtual'] = 'kvm' if 'Manufacturer: QEMU' in output: grains['virtual'] = 'kvm' if 'Vendor: Bochs' in output: grains['virtual'] = 'kvm' if 'Manufacturer: Bochs' in output: grains['virtual'] = 'kvm' if 'BHYVE' in output: grains['virtual'] = 'bhyve' # Product Name: (oVirt) www.ovirt.org # Red Hat Community virtualization Project based on kvm elif 'Manufacturer: oVirt' in output: grains['virtual'] = 'kvm' grains['virtual_subtype'] = 'ovirt' # Red Hat Enterprise Virtualization elif 'Product Name: RHEV Hypervisor' in output: grains['virtual'] = 'kvm' grains['virtual_subtype'] = 'rhev' elif 'VirtualBox' in output: grains['virtual'] = 'VirtualBox' # Product Name: VMware Virtual Platform elif 'VMware' in output: grains['virtual'] = 'VMware' # Manufacturer: Microsoft Corporation # Product Name: Virtual Machine elif ': Microsoft' in output and 'Virtual Machine' in output: grains['virtual'] = 'VirtualPC' # Manufacturer: Parallels Software International Inc. elif 'Parallels Software' in output: grains['virtual'] = 'Parallels' elif 'Manufacturer: Google' in output: grains['virtual'] = 'kvm' # Proxmox KVM elif 'Vendor: SeaBIOS' in output: grains['virtual'] = 'kvm' # Break out of the loop, lspci parsing is not necessary break elif command == 'lspci': # dmidecode not available or the user does not have the necessary # permissions model = output.lower() if 'vmware' in model: grains['virtual'] = 'VMware' # 00:04.0 System peripheral: InnoTek Systemberatung GmbH # VirtualBox Guest Service elif 'virtualbox' in model: grains['virtual'] = 'VirtualBox' elif 'qemu' in model: grains['virtual'] = 'kvm' elif 'virtio' in model: grains['virtual'] = 'kvm' # Break out of the loop so the next log message is not issued break elif command == 'prtdiag': model = output.lower().split("\n")[0] if 'vmware' in model: grains['virtual'] = 'VMware' elif 'virtualbox' in model: grains['virtual'] = 'VirtualBox' elif 'qemu' in model: grains['virtual'] = 'kvm' elif 'joyent smartdc hvm' in model: grains['virtual'] = 'kvm' break elif command == 'virtinfo': grains['virtual'] = 'LDOM' break choices = ('Linux', 'HP-UX') isdir = os.path.isdir sysctl = salt.utils.path.which('sysctl') if osdata['kernel'] in choices: if os.path.isdir('/proc'): try: self_root = os.stat('/') init_root = os.stat('/proc/1/root/.') if self_root != init_root: grains['virtual_subtype'] = 'chroot' except (IOError, OSError): pass if isdir('/proc/vz'): if os.path.isfile('/proc/vz/version'): grains['virtual'] = 'openvzhn' elif os.path.isfile('/proc/vz/veinfo'): grains['virtual'] = 'openvzve' # a posteriori, it's expected for these to have failed: failed_commands.discard('lspci') failed_commands.discard('dmidecode') # Provide additional detection for OpenVZ if os.path.isfile('/proc/self/status'): with salt.utils.files.fopen('/proc/self/status') as status_file: vz_re = re.compile(r'^envID:\s+(\d+)$') for line in status_file: vz_match = vz_re.match(line.rstrip('\n')) if vz_match and int(vz_match.groups()[0]) != 0: grains['virtual'] = 'openvzve' elif vz_match and int(vz_match.groups()[0]) == 0: grains['virtual'] = 'openvzhn' if isdir('/proc/sys/xen') or \ isdir('/sys/bus/xen') or isdir('/proc/xen'): if os.path.isfile('/proc/xen/xsd_kva'): # Tested on CentOS 5.3 / 2.6.18-194.26.1.el5xen # Tested on CentOS 5.4 / 2.6.18-164.15.1.el5xen grains['virtual_subtype'] = 'Xen Dom0' else: if osdata.get('productname', '') == 'HVM domU': # Requires dmidecode! grains['virtual_subtype'] = 'Xen HVM DomU' elif os.path.isfile('/proc/xen/capabilities') and \ os.access('/proc/xen/capabilities', os.R_OK): with salt.utils.files.fopen('/proc/xen/capabilities') as fhr: if 'control_d' not in fhr.read(): # Tested on CentOS 5.5 / 2.6.18-194.3.1.el5xen grains['virtual_subtype'] = 'Xen PV DomU' else: # Shouldn't get to this, but just in case grains['virtual_subtype'] = 'Xen Dom0' # Tested on Fedora 10 / 2.6.27.30-170.2.82 with xen # Tested on Fedora 15 / 2.6.41.4-1 without running xen elif isdir('/sys/bus/xen'): if 'xen:' in __salt__['cmd.run']('dmesg').lower(): grains['virtual_subtype'] = 'Xen PV DomU' elif os.path.isfile('/sys/bus/xen/drivers/xenconsole'): # An actual DomU will have the xenconsole driver grains['virtual_subtype'] = 'Xen PV DomU' # If a Dom0 or DomU was detected, obviously this is xen if 'dom' in grains.get('virtual_subtype', '').lower(): grains['virtual'] = 'xen' # Check container type after hypervisors, to avoid variable overwrite on containers running in virtual environment. if os.path.isfile('/proc/1/cgroup'): try: with salt.utils.files.fopen('/proc/1/cgroup', 'r') as fhr: fhr_contents = fhr.read() if ':/lxc/' in fhr_contents: grains['virtual_subtype'] = 'LXC' elif ':/kubepods/' in fhr_contents: grains['virtual_subtype'] = 'kubernetes' elif ':/libpod_parent/' in fhr_contents: grains['virtual_subtype'] = 'libpod' else: if any(x in fhr_contents for x in (':/system.slice/docker', ':/docker/', ':/docker-ce/')): grains['virtual_subtype'] = 'Docker' except IOError: pass if os.path.isfile('/proc/cpuinfo'): with salt.utils.files.fopen('/proc/cpuinfo', 'r') as fhr: if 'QEMU Virtual CPU' in fhr.read(): grains['virtual'] = 'kvm' if os.path.isfile('/sys/devices/virtual/dmi/id/product_name'): try: with salt.utils.files.fopen('/sys/devices/virtual/dmi/id/product_name', 'r') as fhr: output = salt.utils.stringutils.to_unicode(fhr.read(), errors='replace') if 'VirtualBox' in output: grains['virtual'] = 'VirtualBox' elif 'RHEV Hypervisor' in output: grains['virtual'] = 'kvm' grains['virtual_subtype'] = 'rhev' elif 'oVirt Node' in output: grains['virtual'] = 'kvm' grains['virtual_subtype'] = 'ovirt' elif 'Google' in output: grains['virtual'] = 'gce' elif 'BHYVE' in output: grains['virtual'] = 'bhyve' except IOError: pass elif osdata['kernel'] == 'FreeBSD': kenv = salt.utils.path.which('kenv') if kenv: product = __salt__['cmd.run']( '{0} smbios.system.product'.format(kenv) ) maker = __salt__['cmd.run']( '{0} smbios.system.maker'.format(kenv) ) if product.startswith('VMware'): grains['virtual'] = 'VMware' if product.startswith('VirtualBox'): grains['virtual'] = 'VirtualBox' if maker.startswith('Xen'): grains['virtual_subtype'] = '{0} {1}'.format(maker, product) grains['virtual'] = 'xen' if maker.startswith('Microsoft') and product.startswith('Virtual'): grains['virtual'] = 'VirtualPC' if maker.startswith('OpenStack'): grains['virtual'] = 'OpenStack' if maker.startswith('Bochs'): grains['virtual'] = 'kvm' if sysctl: hv_vendor = __salt__['cmd.run']('{0} hw.hv_vendor'.format(sysctl)) model = __salt__['cmd.run']('{0} hw.model'.format(sysctl)) jail = __salt__['cmd.run']( '{0} -n security.jail.jailed'.format(sysctl) ) if 'bhyve' in hv_vendor: grains['virtual'] = 'bhyve' if jail == '1': grains['virtual_subtype'] = 'jail' if 'QEMU Virtual CPU' in model: grains['virtual'] = 'kvm' elif osdata['kernel'] == 'OpenBSD': if 'manufacturer' in osdata: if osdata['manufacturer'] in ['QEMU', 'Red Hat', 'Joyent']: grains['virtual'] = 'kvm' if osdata['manufacturer'] == 'OpenBSD': grains['virtual'] = 'vmm' elif osdata['kernel'] == 'SunOS': if grains['virtual'] == 'LDOM': roles = [] for role in ('control', 'io', 'root', 'service'): subtype_cmd = '{0} -c current get -H -o value {1}-role'.format(cmd, role) ret = __salt__['cmd.run_all']('{0}'.format(subtype_cmd)) if ret['stdout'] == 'true': roles.append(role) if roles: grains['virtual_subtype'] = roles else: # Check if it's a "regular" zone. (i.e. Solaris 10/11 zone) zonename = salt.utils.path.which('zonename') if zonename: zone = __salt__['cmd.run']('{0}'.format(zonename)) if zone != 'global': grains['virtual'] = 'zone' # Check if it's a branded zone (i.e. Solaris 8/9 zone) if isdir('/.SUNWnative'): grains['virtual'] = 'zone' elif osdata['kernel'] == 'NetBSD': if sysctl: if 'QEMU Virtual CPU' in __salt__['cmd.run']( '{0} -n machdep.cpu_brand'.format(sysctl)): grains['virtual'] = 'kvm' elif 'invalid' not in __salt__['cmd.run']( '{0} -n machdep.xen.suspend'.format(sysctl)): grains['virtual'] = 'Xen PV DomU' elif 'VMware' in __salt__['cmd.run']( '{0} -n machdep.dmi.system-vendor'.format(sysctl)): grains['virtual'] = 'VMware' # NetBSD has Xen dom0 support elif __salt__['cmd.run']( '{0} -n machdep.idle-mechanism'.format(sysctl)) == 'xen': if os.path.isfile('/var/run/xenconsoled.pid'): grains['virtual_subtype'] = 'Xen Dom0' for command in failed_commands: log.info( "Although '%s' was found in path, the current user " 'cannot execute it. Grains output might not be ' 'accurate.', command ) return grains def _virtual_hv(osdata): ''' Returns detailed hypervisor information from sysfs Currently this seems to be used only by Xen ''' grains = {} # Bail early if we're not running on Xen try: if 'xen' not in osdata['virtual']: return grains except KeyError: return grains # Try to get the exact hypervisor version from sysfs try: version = {} for fn in ('major', 'minor', 'extra'): with salt.utils.files.fopen('/sys/hypervisor/version/{}'.format(fn), 'r') as fhr: version[fn] = salt.utils.stringutils.to_unicode(fhr.read().strip()) grains['virtual_hv_version'] = '{}.{}{}'.format(version['major'], version['minor'], version['extra']) grains['virtual_hv_version_info'] = [version['major'], version['minor'], version['extra']] except (IOError, OSError, KeyError): pass # Try to read and decode the supported feature set of the hypervisor # Based on https://github.com/brendangregg/Misc/blob/master/xen/xen-features.py # Table data from include/xen/interface/features.h xen_feature_table = {0: 'writable_page_tables', 1: 'writable_descriptor_tables', 2: 'auto_translated_physmap', 3: 'supervisor_mode_kernel', 4: 'pae_pgdir_above_4gb', 5: 'mmu_pt_update_preserve_ad', 7: 'gnttab_map_avail_bits', 8: 'hvm_callback_vector', 9: 'hvm_safe_pvclock', 10: 'hvm_pirqs', 11: 'dom0', 12: 'grant_map_identity', 13: 'memory_op_vnode_supported', 14: 'ARM_SMCCC_supported'} try: with salt.utils.files.fopen('/sys/hypervisor/properties/features', 'r') as fhr: features = salt.utils.stringutils.to_unicode(fhr.read().strip()) enabled_features = [] for bit, feat in six.iteritems(xen_feature_table): if int(features, 16) & (1 << bit): enabled_features.append(feat) grains['virtual_hv_features'] = features grains['virtual_hv_features_list'] = enabled_features except (IOError, OSError, KeyError): pass return grains def _ps(osdata): ''' Return the ps grain ''' grains = {} bsd_choices = ('FreeBSD', 'NetBSD', 'OpenBSD', 'MacOS') if osdata['os'] in bsd_choices: grains['ps'] = 'ps auxwww' elif osdata['os_family'] == 'Solaris': grains['ps'] = '/usr/ucb/ps auxwww' elif osdata['os'] == 'Windows': grains['ps'] = 'tasklist.exe' elif osdata.get('virtual', '') == 'openvzhn': grains['ps'] = ( 'ps -fH -p $(grep -l \"^envID:[[:space:]]*0\\$\" ' '/proc/[0-9]*/status | sed -e \"s=/proc/\\([0-9]*\\)/.*=\\1=\") ' '| awk \'{ $7=\"\"; print }\'' ) elif osdata['os_family'] == 'AIX': grains['ps'] = '/usr/bin/ps auxww' elif osdata['os_family'] == 'NILinuxRT': grains['ps'] = 'ps -o user,pid,ppid,tty,time,comm' else: grains['ps'] = 'ps -efHww' return grains def _clean_value(key, val): ''' Clean out well-known bogus values. If it isn't clean (for example has value 'None'), return None. Otherwise, return the original value. NOTE: This logic also exists in the smbios module. This function is for use when not using smbios to retrieve the value. ''' if (val is None or not val or re.match('none', val, flags=re.IGNORECASE)): return None elif 'uuid' in key: # Try each version (1-5) of RFC4122 to check if it's actually a UUID for uuidver in range(1, 5): try: uuid.UUID(val, version=uuidver) return val except ValueError: continue log.trace('HW %s value %s is an invalid UUID', key, val.replace('\n', ' ')) return None elif re.search('serial|part|version', key): # 'To be filled by O.E.M. # 'Not applicable' etc. # 'Not specified' etc. # 0000000, 1234567 etc. # begone! if (re.match(r'^[0]+$', val) or re.match(r'[0]?1234567[8]?[9]?[0]?', val) or re.search(r'sernum|part[_-]?number|specified|filled|applicable', val, flags=re.IGNORECASE)): return None elif re.search('asset|manufacturer', key): # AssetTag0. Manufacturer04. Begone. if re.search(r'manufacturer|to be filled|available|asset|^no(ne|t)', val, flags=re.IGNORECASE): return None else: # map unspecified, undefined, unknown & whatever to None if (re.search(r'to be filled', val, flags=re.IGNORECASE) or re.search(r'un(known|specified)|no(t|ne)? (asset|provided|defined|available|present|specified)', val, flags=re.IGNORECASE)): return None return val def _windows_platform_data(): ''' Use the platform module for as much as we can. ''' # Provides: # kernelrelease # kernelversion # osversion # osrelease # osservicepack # osmanufacturer # manufacturer # productname # biosversion # serialnumber # osfullname # timezone # windowsdomain # windowsdomaintype # motherboard.productname # motherboard.serialnumber # virtual if not HAS_WMI: return {} with salt.utils.winapi.Com(): wmi_c = wmi.WMI() # http://msdn.microsoft.com/en-us/library/windows/desktop/aa394102%28v=vs.85%29.aspx systeminfo = wmi_c.Win32_ComputerSystem()[0] # https://msdn.microsoft.com/en-us/library/aa394239(v=vs.85).aspx osinfo = wmi_c.Win32_OperatingSystem()[0] # http://msdn.microsoft.com/en-us/library/windows/desktop/aa394077(v=vs.85).aspx biosinfo = wmi_c.Win32_BIOS()[0] # http://msdn.microsoft.com/en-us/library/windows/desktop/aa394498(v=vs.85).aspx timeinfo = wmi_c.Win32_TimeZone()[0] # http://msdn.microsoft.com/en-us/library/windows/desktop/aa394072(v=vs.85).aspx motherboard = {'product': None, 'serial': None} try: motherboardinfo = wmi_c.Win32_BaseBoard()[0] motherboard['product'] = motherboardinfo.Product motherboard['serial'] = motherboardinfo.SerialNumber except IndexError: log.debug('Motherboard info not available on this system') os_release = platform.release() kernel_version = platform.version() info = salt.utils.win_osinfo.get_os_version_info() net_info = salt.utils.win_osinfo.get_join_info() service_pack = None if info['ServicePackMajor'] > 0: service_pack = ''.join(['SP', six.text_type(info['ServicePackMajor'])]) # This creates the osrelease grain based on the Windows Operating # System Product Name. As long as Microsoft maintains a similar format # this should be future proof version = 'Unknown' release = '' if 'Server' in osinfo.Caption: for item in osinfo.Caption.split(' '): # If it's all digits, then it's version if re.match(r'\d+', item): version = item # If it starts with R and then numbers, it's the release # ie: R2 if re.match(r'^R\d+$', item): release = item os_release = '{0}Server{1}'.format(version, release) else: for item in osinfo.Caption.split(' '): # If it's a number, decimal number, Thin or Vista, then it's the # version if re.match(r'^(\d+(\.\d+)?)|Thin|Vista$', item): version = item os_release = version grains = { 'kernelrelease': _clean_value('kernelrelease', osinfo.Version), 'kernelversion': _clean_value('kernelversion', kernel_version), 'osversion': _clean_value('osversion', osinfo.Version), 'osrelease': _clean_value('osrelease', os_release), 'osservicepack': _clean_value('osservicepack', service_pack), 'osmanufacturer': _clean_value('osmanufacturer', osinfo.Manufacturer), 'manufacturer': _clean_value('manufacturer', systeminfo.Manufacturer), 'productname': _clean_value('productname', systeminfo.Model), # bios name had a bunch of whitespace appended to it in my testing # 'PhoenixBIOS 4.0 Release 6.0 ' 'biosversion': _clean_value('biosversion', biosinfo.Name.strip()), 'serialnumber': _clean_value('serialnumber', biosinfo.SerialNumber), 'osfullname': _clean_value('osfullname', osinfo.Caption), 'timezone': _clean_value('timezone', timeinfo.Description), 'windowsdomain': _clean_value('windowsdomain', net_info['Domain']), 'windowsdomaintype': _clean_value('windowsdomaintype', net_info['DomainType']), 'motherboard': { 'productname': _clean_value('motherboard.productname', motherboard['product']), 'serialnumber': _clean_value('motherboard.serialnumber', motherboard['serial']), } } # test for virtualized environments # I only had VMware available so the rest are unvalidated if 'VRTUAL' in biosinfo.Version: # (not a typo) grains['virtual'] = 'HyperV' elif 'A M I' in biosinfo.Version: grains['virtual'] = 'VirtualPC' elif 'VMware' in systeminfo.Model: grains['virtual'] = 'VMware' elif 'VirtualBox' in systeminfo.Model: grains['virtual'] = 'VirtualBox' elif 'Xen' in biosinfo.Version: grains['virtual'] = 'Xen' if 'HVM domU' in systeminfo.Model: grains['virtual_subtype'] = 'HVM domU' elif 'OpenStack' in systeminfo.Model: grains['virtual'] = 'OpenStack' return grains def _osx_platform_data(): ''' Additional data for macOS systems Returns: A dictionary containing values for the following: - model_name - boot_rom_version - smc_version - system_serialnumber ''' cmd = 'system_profiler SPHardwareDataType' hardware = __salt__['cmd.run'](cmd) grains = {} for line in hardware.splitlines(): field_name, _, field_val = line.partition(': ') if field_name.strip() == "Model Name": key = 'model_name' grains[key] = _clean_value(key, field_val) if field_name.strip() == "Boot ROM Version": key = 'boot_rom_version' grains[key] = _clean_value(key, field_val) if field_name.strip() == "SMC Version (system)": key = 'smc_version' grains[key] = _clean_value(key, field_val) if field_name.strip() == "Serial Number (system)": key = 'system_serialnumber' grains[key] = _clean_value(key, field_val) return grains def id_(): ''' Return the id ''' return {'id': __opts__.get('id', '')} _REPLACE_LINUX_RE = re.compile(r'\W(?:gnu/)?linux', re.IGNORECASE) # This maps (at most) the first ten characters (no spaces, lowercased) of # 'osfullname' to the 'os' grain that Salt traditionally uses. # Please see os_data() and _supported_dists. # If your system is not detecting properly it likely needs an entry here. _OS_NAME_MAP = { 'redhatente': 'RedHat', 'gentoobase': 'Gentoo', 'archarm': 'Arch ARM', 'arch': 'Arch', 'debian': 'Debian', 'raspbian': 'Raspbian', 'fedoraremi': 'Fedora', 'chapeau': 'Chapeau', 'korora': 'Korora', 'amazonami': 'Amazon', 'alt': 'ALT', 'enterprise': 'OEL', 'oracleserv': 'OEL', 'cloudserve': 'CloudLinux', 'cloudlinux': 'CloudLinux', 'pidora': 'Fedora', 'scientific': 'ScientificLinux', 'synology': 'Synology', 'nilrt': 'NILinuxRT', 'poky': 'Poky', 'manjaro': 'Manjaro', 'manjarolin': 'Manjaro', 'univention': 'Univention', 'antergos': 'Antergos', 'sles': 'SUSE', 'void': 'Void', 'slesexpand': 'RES', 'linuxmint': 'Mint', 'neon': 'KDE neon', } # Map the 'os' grain to the 'os_family' grain # These should always be capitalized entries as the lookup comes # post-_OS_NAME_MAP. If your system is having trouble with detection, please # make sure that the 'os' grain is capitalized and working correctly first. _OS_FAMILY_MAP = { 'Ubuntu': 'Debian', 'Fedora': 'RedHat', 'Chapeau': 'RedHat', 'Korora': 'RedHat', 'FedBerry': 'RedHat', 'CentOS': 'RedHat', 'GoOSe': 'RedHat', 'Scientific': 'RedHat', 'Amazon': 'RedHat', 'CloudLinux': 'RedHat', 'OVS': 'RedHat', 'OEL': 'RedHat', 'XCP': 'RedHat', 'XCP-ng': 'RedHat', 'XenServer': 'RedHat', 'RES': 'RedHat', 'Sangoma': 'RedHat', 'Mandrake': 'Mandriva', 'ESXi': 'VMware', 'Mint': 'Debian', 'VMwareESX': 'VMware', 'Bluewhite64': 'Bluewhite', 'Slamd64': 'Slackware', 'SLES': 'Suse', 'SUSE Enterprise Server': 'Suse', 'SUSE Enterprise Server': 'Suse', 'SLED': 'Suse', 'openSUSE': 'Suse', 'SUSE': 'Suse', 'openSUSE Leap': 'Suse', 'openSUSE Tumbleweed': 'Suse', 'SLES_SAP': 'Suse', 'Solaris': 'Solaris', 'SmartOS': 'Solaris', 'OmniOS': 'Solaris', 'OpenIndiana Development': 'Solaris', 'OpenIndiana': 'Solaris', 'OpenSolaris Development': 'Solaris', 'OpenSolaris': 'Solaris', 'Oracle Solaris': 'Solaris', 'Arch ARM': 'Arch', 'Manjaro': 'Arch', 'Antergos': 'Arch', 'ALT': 'RedHat', 'Trisquel': 'Debian', 'GCEL': 'Debian', 'Linaro': 'Debian', 'elementary OS': 'Debian', 'elementary': 'Debian', 'Univention': 'Debian', 'ScientificLinux': 'RedHat', 'Raspbian': 'Debian', 'Devuan': 'Debian', 'antiX': 'Debian', 'Kali': 'Debian', 'neon': 'Debian', 'Cumulus': 'Debian', 'Deepin': 'Debian', 'NILinuxRT': 'NILinuxRT', 'KDE neon': 'Debian', 'Void': 'Void', 'IDMS': 'Debian', 'Funtoo': 'Gentoo', 'AIX': 'AIX', 'TurnKey': 'Debian', } # Matches any possible format: # DISTRIB_ID="Ubuntu" # DISTRIB_ID='Mageia' # DISTRIB_ID=Fedora # DISTRIB_RELEASE='10.10' # DISTRIB_CODENAME='squeeze' # DISTRIB_DESCRIPTION='Ubuntu 10.10' _LSB_REGEX = re.compile(( '^(DISTRIB_(?:ID|RELEASE|CODENAME|DESCRIPTION))=(?:\'|")?' '([\\w\\s\\.\\-_]+)(?:\'|")?' )) def _linux_bin_exists(binary): ''' Does a binary exist in linux (depends on which, type, or whereis) ''' for search_cmd in ('which', 'type -ap'): try: return __salt__['cmd.retcode']( '{0} {1}'.format(search_cmd, binary) ) == 0 except salt.exceptions.CommandExecutionError: pass try: return len(__salt__['cmd.run_all']( 'whereis -b {0}'.format(binary) )['stdout'].split()) > 1 except salt.exceptions.CommandExecutionError: return False def _get_interfaces(): ''' Provide a dict of the connected interfaces and their ip addresses ''' global _INTERFACES if not _INTERFACES: _INTERFACES = salt.utils.network.interfaces() return _INTERFACES def _parse_lsb_release(): ret = {} try: log.trace('Attempting to parse /etc/lsb-release') with salt.utils.files.fopen('/etc/lsb-release') as ifile: for line in ifile: try: key, value = _LSB_REGEX.match(line.rstrip('\n')).groups()[:2] except AttributeError: pass else: # Adds lsb_distrib_{id,release,codename,description} ret['lsb_{0}'.format(key.lower())] = value.rstrip() except (IOError, OSError) as exc: log.trace('Failed to parse /etc/lsb-release: %s', exc) return ret def _parse_os_release(*os_release_files): ''' Parse os-release and return a parameter dictionary See http://www.freedesktop.org/software/systemd/man/os-release.html for specification of the file format. ''' ret = {} for filename in os_release_files: try: with salt.utils.files.fopen(filename) as ifile: regex = re.compile('^([\\w]+)=(?:\'|")?(.*?)(?:\'|")?$') for line in ifile: match = regex.match(line.strip()) if match: # Shell special characters ("$", quotes, backslash, # backtick) are escaped with backslashes ret[match.group(1)] = re.sub( r'\\([$"\'\\`])', r'\1', match.group(2) ) break except (IOError, OSError): pass return ret def _parse_cpe_name(cpe): ''' Parse CPE_NAME data from the os-release Info: https://csrc.nist.gov/projects/security-content-automation-protocol/scap-specifications/cpe :param cpe: :return: ''' part = { 'o': 'operating system', 'h': 'hardware', 'a': 'application', } ret = {} cpe = (cpe or '').split(':') if len(cpe) > 4 and cpe[0] == 'cpe': if cpe[1].startswith('/'): # WFN to URI ret['vendor'], ret['product'], ret['version'] = cpe[2:5] ret['phase'] = cpe[5] if len(cpe) > 5 else None ret['part'] = part.get(cpe[1][1:]) elif len(cpe) == 13 and cpe[1] == '2.3': # WFN to a string ret['vendor'], ret['product'], ret['version'], ret['phase'] = [x if x != '*' else None for x in cpe[3:7]] ret['part'] = part.get(cpe[2]) return ret def os_data(): ''' Return grains pertaining to the operating system ''' grains = { 'num_gpus': 0, 'gpus': [], } # Windows Server 2008 64-bit # ('Windows', 'MINIONNAME', '2008ServerR2', '6.1.7601', 'AMD64', # 'Intel64 Fam ily 6 Model 23 Stepping 6, GenuineIntel') # Ubuntu 10.04 # ('Linux', 'MINIONNAME', '2.6.32-38-server', # '#83-Ubuntu SMP Wed Jan 4 11:26:59 UTC 2012', 'x86_64', '') # pylint: disable=unpacking-non-sequence (grains['kernel'], grains['nodename'], grains['kernelrelease'], grains['kernelversion'], grains['cpuarch'], _) = platform.uname() # pylint: enable=unpacking-non-sequence if salt.utils.platform.is_proxy(): grains['kernel'] = 'proxy' grains['kernelrelease'] = 'proxy' grains['kernelversion'] = 'proxy' grains['osrelease'] = 'proxy' grains['os'] = 'proxy' grains['os_family'] = 'proxy' grains['osfullname'] = 'proxy' elif salt.utils.platform.is_windows(): grains['os'] = 'Windows' grains['os_family'] = 'Windows' grains.update(_memdata(grains)) grains.update(_windows_platform_data()) grains.update(_windows_cpudata()) grains.update(_windows_virtual(grains)) grains.update(_ps(grains)) if 'Server' in grains['osrelease']: osrelease_info = grains['osrelease'].split('Server', 1) osrelease_info[1] = osrelease_info[1].lstrip('R') else: osrelease_info = grains['osrelease'].split('.') for idx, value in enumerate(osrelease_info): if not value.isdigit(): continue osrelease_info[idx] = int(value) grains['osrelease_info'] = tuple(osrelease_info) grains['osfinger'] = '{os}-{ver}'.format( os=grains['os'], ver=grains['osrelease']) grains['init'] = 'Windows' return grains elif salt.utils.platform.is_linux(): # Add SELinux grain, if you have it if _linux_bin_exists('selinuxenabled'): log.trace('Adding selinux grains') grains['selinux'] = {} grains['selinux']['enabled'] = __salt__['cmd.retcode']( 'selinuxenabled' ) == 0 if _linux_bin_exists('getenforce'): grains['selinux']['enforced'] = __salt__['cmd.run']( 'getenforce' ).strip() # Add systemd grain, if you have it if _linux_bin_exists('systemctl') and _linux_bin_exists('localectl'): log.trace('Adding systemd grains') grains['systemd'] = {} systemd_info = __salt__['cmd.run']( 'systemctl --version' ).splitlines() grains['systemd']['version'] = systemd_info[0].split()[1] grains['systemd']['features'] = systemd_info[1] # Add init grain grains['init'] = 'unknown' log.trace('Adding init grain') try: os.stat('/run/systemd/system') grains['init'] = 'systemd' except (OSError, IOError): try: with salt.utils.files.fopen('/proc/1/cmdline') as fhr: init_cmdline = fhr.read().replace('\x00', ' ').split() except (IOError, OSError): pass else: try: init_bin = salt.utils.path.which(init_cmdline[0]) except IndexError: # Emtpy init_cmdline init_bin = None log.warning('Unable to fetch data from /proc/1/cmdline') if init_bin is not None and init_bin.endswith('bin/init'): supported_inits = (b'upstart', b'sysvinit', b'systemd') edge_len = max(len(x) for x in supported_inits) - 1 try: buf_size = __opts__['file_buffer_size'] except KeyError: # Default to the value of file_buffer_size for the minion buf_size = 262144 try: with salt.utils.files.fopen(init_bin, 'rb') as fp_: edge = b'' buf = fp_.read(buf_size).lower() while buf: buf = edge + buf for item in supported_inits: if item in buf: if six.PY3: item = item.decode('utf-8') grains['init'] = item buf = b'' break edge = buf[-edge_len:] buf = fp_.read(buf_size).lower() except (IOError, OSError) as exc: log.error( 'Unable to read from init_bin (%s): %s', init_bin, exc ) elif salt.utils.path.which('supervisord') in init_cmdline: grains['init'] = 'supervisord' elif salt.utils.path.which('dumb-init') in init_cmdline: # https://github.com/Yelp/dumb-init grains['init'] = 'dumb-init' elif salt.utils.path.which('tini') in init_cmdline: # https://github.com/krallin/tini grains['init'] = 'tini' elif init_cmdline == ['runit']: grains['init'] = 'runit' elif '/sbin/my_init' in init_cmdline: # Phusion Base docker container use runit for srv mgmt, but # my_init as pid1 grains['init'] = 'runit' else: log.debug( 'Could not determine init system from command line: (%s)', ' '.join(init_cmdline) ) # Add lsb grains on any distro with lsb-release. Note that this import # can fail on systems with lsb-release installed if the system package # does not install the python package for the python interpreter used by # Salt (i.e. python2 or python3) try: log.trace('Getting lsb_release distro information') import lsb_release # pylint: disable=import-error release = lsb_release.get_distro_information() for key, value in six.iteritems(release): key = key.lower() lsb_param = 'lsb_{0}{1}'.format( '' if key.startswith('distrib_') else 'distrib_', key ) grains[lsb_param] = value # Catch a NameError to workaround possible breakage in lsb_release # See https://github.com/saltstack/salt/issues/37867 except (ImportError, NameError): # if the python library isn't available, try to parse # /etc/lsb-release using regex log.trace('lsb_release python bindings not available') grains.update(_parse_lsb_release()) if grains.get('lsb_distrib_description', '').lower().startswith('antergos'): # Antergos incorrectly configures their /etc/lsb-release, # setting the DISTRIB_ID to "Arch". This causes the "os" grain # to be incorrectly set to "Arch". grains['osfullname'] = 'Antergos Linux' elif 'lsb_distrib_id' not in grains: log.trace( 'Failed to get lsb_distrib_id, trying to parse os-release' ) os_release = _parse_os_release('/etc/os-release', '/usr/lib/os-release') if os_release: if 'NAME' in os_release: grains['lsb_distrib_id'] = os_release['NAME'].strip() if 'VERSION_ID' in os_release: grains['lsb_distrib_release'] = os_release['VERSION_ID'] if 'VERSION_CODENAME' in os_release: grains['lsb_distrib_codename'] = os_release['VERSION_CODENAME'] elif 'PRETTY_NAME' in os_release: codename = os_release['PRETTY_NAME'] # https://github.com/saltstack/salt/issues/44108 if os_release['ID'] == 'debian': codename_match = re.search(r'\((\w+)\)$', codename) if codename_match: codename = codename_match.group(1) grains['lsb_distrib_codename'] = codename if 'CPE_NAME' in os_release: cpe = _parse_cpe_name(os_release['CPE_NAME']) if not cpe: log.error('Broken CPE_NAME format in /etc/os-release!') elif cpe.get('vendor', '').lower() in ['suse', 'opensuse']: grains['os'] = "SUSE" # openSUSE `osfullname` grain normalization if os_release.get("NAME") == "openSUSE Leap": grains['osfullname'] = "Leap" elif os_release.get("VERSION") == "Tumbleweed": grains['osfullname'] = os_release["VERSION"] # Override VERSION_ID, if CPE_NAME around if cpe.get('version') and cpe.get('vendor') == 'opensuse': # Keep VERSION_ID for SLES grains['lsb_distrib_release'] = cpe['version'] elif os.path.isfile('/etc/SuSE-release'): log.trace('Parsing distrib info from /etc/SuSE-release') grains['lsb_distrib_id'] = 'SUSE' version = '' patch = '' with salt.utils.files.fopen('/etc/SuSE-release') as fhr: for line in fhr: if 'enterprise' in line.lower(): grains['lsb_distrib_id'] = 'SLES' grains['lsb_distrib_codename'] = re.sub(r'\(.+\)', '', line).strip() elif 'version' in line.lower(): version = re.sub(r'[^0-9]', '', line) elif 'patchlevel' in line.lower(): patch = re.sub(r'[^0-9]', '', line) grains['lsb_distrib_release'] = version if patch: grains['lsb_distrib_release'] += '.' + patch patchstr = 'SP' + patch if grains['lsb_distrib_codename'] and patchstr not in grains['lsb_distrib_codename']: grains['lsb_distrib_codename'] += ' ' + patchstr if not grains.get('lsb_distrib_codename'): grains['lsb_distrib_codename'] = 'n.a' elif os.path.isfile('/etc/altlinux-release'): log.trace('Parsing distrib info from /etc/altlinux-release') # ALT Linux grains['lsb_distrib_id'] = 'altlinux' with salt.utils.files.fopen('/etc/altlinux-release') as ifile: # This file is symlinked to from: # /etc/fedora-release # /etc/redhat-release # /etc/system-release for line in ifile: # ALT Linux Sisyphus (unstable) comps = line.split() if comps[0] == 'ALT': grains['lsb_distrib_release'] = comps[2] grains['lsb_distrib_codename'] = \ comps[3].replace('(', '').replace(')', '') elif os.path.isfile('/etc/centos-release'): log.trace('Parsing distrib info from /etc/centos-release') # Maybe CentOS Linux; could also be SUSE Expanded Support. # SUSE ES has both, centos-release and redhat-release. if os.path.isfile('/etc/redhat-release'): with salt.utils.files.fopen('/etc/redhat-release') as ifile: for line in ifile: if "red hat enterprise linux server" in line.lower(): # This is a SUSE Expanded Support Rhel installation grains['lsb_distrib_id'] = 'RedHat' break grains.setdefault('lsb_distrib_id', 'CentOS') with salt.utils.files.fopen('/etc/centos-release') as ifile: for line in ifile: # Need to pull out the version and codename # in the case of custom content in /etc/centos-release find_release = re.compile(r'\d+\.\d+') find_codename = re.compile(r'(?<=\()(.*?)(?=\))') release = find_release.search(line) codename = find_codename.search(line) if release is not None: grains['lsb_distrib_release'] = release.group() if codename is not None: grains['lsb_distrib_codename'] = codename.group() elif os.path.isfile('/etc.defaults/VERSION') \ and os.path.isfile('/etc.defaults/synoinfo.conf'): grains['osfullname'] = 'Synology' log.trace( 'Parsing Synology distrib info from /etc/.defaults/VERSION' ) with salt.utils.files.fopen('/etc.defaults/VERSION', 'r') as fp_: synoinfo = {} for line in fp_: try: key, val = line.rstrip('\n').split('=') except ValueError: continue if key in ('majorversion', 'minorversion', 'buildnumber'): synoinfo[key] = val.strip('"') if len(synoinfo) != 3: log.warning( 'Unable to determine Synology version info. ' 'Please report this, as it is likely a bug.' ) else: grains['osrelease'] = ( '{majorversion}.{minorversion}-{buildnumber}' .format(**synoinfo) ) # Use the already intelligent platform module to get distro info # (though apparently it's not intelligent enough to strip quotes) log.trace( 'Getting OS name, release, and codename from ' 'distro.linux_distribution()' ) (osname, osrelease, oscodename) = \ [x.strip('"').strip("'") for x in linux_distribution(supported_dists=_supported_dists)] # Try to assign these three names based on the lsb info, they tend to # be more accurate than what python gets from /etc/DISTRO-release. # It's worth noting that Ubuntu has patched their Python distribution # so that linux_distribution() does the /etc/lsb-release parsing, but # we do it anyway here for the sake for full portability. if 'osfullname' not in grains: # If NI Linux RT distribution, set the grains['osfullname'] to 'nilrt' if grains.get('lsb_distrib_id', '').lower().startswith('nilrt'): grains['osfullname'] = 'nilrt' else: grains['osfullname'] = grains.get('lsb_distrib_id', osname).strip() if 'osrelease' not in grains: # NOTE: This is a workaround for CentOS 7 os-release bug # https://bugs.centos.org/view.php?id=8359 # /etc/os-release contains no minor distro release number so we fall back to parse # /etc/centos-release file instead. # Commit introducing this comment should be reverted after the upstream bug is released. if 'CentOS Linux 7' in grains.get('lsb_distrib_codename', ''): grains.pop('lsb_distrib_release', None) grains['osrelease'] = grains.get('lsb_distrib_release', osrelease).strip() grains['oscodename'] = grains.get('lsb_distrib_codename', '').strip() or oscodename if 'Red Hat' in grains['oscodename']: grains['oscodename'] = oscodename distroname = _REPLACE_LINUX_RE.sub('', grains['osfullname']).strip() # return the first ten characters with no spaces, lowercased shortname = distroname.replace(' ', '').lower()[:10] # this maps the long names from the /etc/DISTRO-release files to the # traditional short names that Salt has used. if 'os' not in grains: grains['os'] = _OS_NAME_MAP.get(shortname, distroname) grains.update(_linux_cpudata()) grains.update(_linux_gpu_data()) elif grains['kernel'] == 'SunOS': if salt.utils.platform.is_smartos(): # See https://github.com/joyent/smartos-live/issues/224 if HAS_UNAME: uname_v = os.uname()[3] # format: joyent_20161101T004406Z else: uname_v = os.name uname_v = uname_v[uname_v.index('_')+1:] grains['os'] = grains['osfullname'] = 'SmartOS' # store a parsed version of YYYY.MM.DD as osrelease grains['osrelease'] = ".".join([ uname_v.split('T')[0][0:4], uname_v.split('T')[0][4:6], uname_v.split('T')[0][6:8], ]) # store a untouched copy of the timestamp in osrelease_stamp grains['osrelease_stamp'] = uname_v elif os.path.isfile('/etc/release'): with salt.utils.files.fopen('/etc/release', 'r') as fp_: rel_data = fp_.read() try: release_re = re.compile( r'((?:Open|Oracle )?Solaris|OpenIndiana|OmniOS) (Development)?' r'\s*(\d+\.?\d*|v\d+)\s?[A-Z]*\s?(r\d+|\d+\/\d+|oi_\S+|snv_\S+)?' ) osname, development, osmajorrelease, osminorrelease = release_re.search(rel_data).groups() except AttributeError: # Set a blank osrelease grain and fallback to 'Solaris' # as the 'os' grain. grains['os'] = grains['osfullname'] = 'Solaris' grains['osrelease'] = '' else: if development is not None: osname = ' '.join((osname, development)) if HAS_UNAME: uname_v = os.uname()[3] else: uname_v = os.name grains['os'] = grains['osfullname'] = osname if osname in ['Oracle Solaris'] and uname_v.startswith(osmajorrelease): # Oracla Solars 11 and up have minor version in uname grains['osrelease'] = uname_v elif osname in ['OmniOS']: # OmniOS osrelease = [] osrelease.append(osmajorrelease[1:]) osrelease.append(osminorrelease[1:]) grains['osrelease'] = ".".join(osrelease) grains['osrelease_stamp'] = uname_v else: # Sun Solaris 10 and earlier/comparable osrelease = [] osrelease.append(osmajorrelease) if osminorrelease: osrelease.append(osminorrelease) grains['osrelease'] = ".".join(osrelease) grains['osrelease_stamp'] = uname_v grains.update(_sunos_cpudata()) elif grains['kernel'] == 'VMkernel': grains['os'] = 'ESXi' elif grains['kernel'] == 'Darwin': osrelease = __salt__['cmd.run']('sw_vers -productVersion') osname = __salt__['cmd.run']('sw_vers -productName') osbuild = __salt__['cmd.run']('sw_vers -buildVersion') grains['os'] = 'MacOS' grains['os_family'] = 'MacOS' grains['osfullname'] = "{0} {1}".format(osname, osrelease) grains['osrelease'] = osrelease grains['osbuild'] = osbuild grains['init'] = 'launchd' grains.update(_bsd_cpudata(grains)) grains.update(_osx_gpudata()) grains.update(_osx_platform_data()) elif grains['kernel'] == 'AIX': osrelease = __salt__['cmd.run']('oslevel') osrelease_techlevel = __salt__['cmd.run']('oslevel -r') osname = __salt__['cmd.run']('uname') grains['os'] = 'AIX' grains['osfullname'] = osname grains['osrelease'] = osrelease grains['osrelease_techlevel'] = osrelease_techlevel grains.update(_aix_cpudata()) else: grains['os'] = grains['kernel'] if grains['kernel'] == 'FreeBSD': try: grains['osrelease'] = __salt__['cmd.run']('freebsd-version -u').split('-')[0] except salt.exceptions.CommandExecutionError: # freebsd-version was introduced in 10.0. # derive osrelease from kernelversion prior to that grains['osrelease'] = grains['kernelrelease'].split('-')[0] grains.update(_bsd_cpudata(grains)) if grains['kernel'] in ('OpenBSD', 'NetBSD'): grains.update(_bsd_cpudata(grains)) grains['osrelease'] = grains['kernelrelease'].split('-')[0] if grains['kernel'] == 'NetBSD': grains.update(_netbsd_gpu_data()) if not grains['os']: grains['os'] = 'Unknown {0}'.format(grains['kernel']) grains['os_family'] = 'Unknown' else: # this assigns family names based on the os name # family defaults to the os name if not found grains['os_family'] = _OS_FAMILY_MAP.get(grains['os'], grains['os']) # Build the osarch grain. This grain will be used for platform-specific # considerations such as package management. Fall back to the CPU # architecture. if grains.get('os_family') == 'Debian': osarch = __salt__['cmd.run']('dpkg --print-architecture').strip() elif grains.get('os_family') in ['RedHat', 'Suse']: osarch = salt.utils.pkg.rpm.get_osarch() elif grains.get('os_family') in ('NILinuxRT', 'Poky'): archinfo = {} for line in __salt__['cmd.run']('opkg print-architecture').splitlines(): if line.startswith('arch'): _, arch, priority = line.split() archinfo[arch.strip()] = int(priority.strip()) # Return osarch in priority order (higher to lower) osarch = sorted(archinfo, key=archinfo.get, reverse=True) else: osarch = grains['cpuarch'] grains['osarch'] = osarch grains.update(_memdata(grains)) # Get the hardware and bios data grains.update(_hw_data(grains)) # Load the virtual machine info grains.update(_virtual(grains)) grains.update(_virtual_hv(grains)) grains.update(_ps(grains)) if grains.get('osrelease', ''): osrelease_info = grains['osrelease'].split('.') for idx, value in enumerate(osrelease_info): if not value.isdigit(): continue osrelease_info[idx] = int(value) grains['osrelease_info'] = tuple(osrelease_info) try: grains['osmajorrelease'] = int(grains['osrelease_info'][0]) except (IndexError, TypeError, ValueError): log.debug( 'Unable to derive osmajorrelease from osrelease_info \'%s\'. ' 'The osmajorrelease grain will not be set.', grains['osrelease_info'] ) os_name = grains['os' if grains.get('os') in ( 'Debian', 'FreeBSD', 'OpenBSD', 'NetBSD', 'Mac', 'Raspbian') else 'osfullname'] grains['osfinger'] = '{0}-{1}'.format( os_name, grains['osrelease'] if os_name in ('Ubuntu',) else grains['osrelease_info'][0]) return grains def locale_info(): ''' Provides defaultlanguage defaultencoding ''' grains = {} grains['locale_info'] = {} if salt.utils.platform.is_proxy(): return grains try: ( grains['locale_info']['defaultlanguage'], grains['locale_info']['defaultencoding'] ) = locale.getdefaultlocale() except Exception: # locale.getdefaultlocale can ValueError!! Catch anything else it # might do, per #2205 grains['locale_info']['defaultlanguage'] = 'unknown' grains['locale_info']['defaultencoding'] = 'unknown' grains['locale_info']['detectedencoding'] = __salt_system_encoding__ if _DATEUTIL_TZ: grains['locale_info']['timezone'] = datetime.datetime.now(dateutil.tz.tzlocal()).tzname() return grains def hostname(): ''' Return fqdn, hostname, domainname ''' # This is going to need some work # Provides: # fqdn # host # localhost # domain global __FQDN__ grains = {} if salt.utils.platform.is_proxy(): return grains grains['localhost'] = socket.gethostname() if __FQDN__ is None: __FQDN__ = salt.utils.network.get_fqhostname() # On some distros (notably FreeBSD) if there is no hostname set # salt.utils.network.get_fqhostname() will return None. # In this case we punt and log a message at error level, but force the # hostname and domain to be localhost.localdomain # Otherwise we would stacktrace below if __FQDN__ is None: # still! log.error('Having trouble getting a hostname. Does this machine have its hostname and domain set properly?') __FQDN__ = 'localhost.localdomain' grains['fqdn'] = __FQDN__ (grains['host'], grains['domain']) = grains['fqdn'].partition('.')[::2] return grains def append_domain(): ''' Return append_domain if set ''' grain = {} if salt.utils.platform.is_proxy(): return grain if 'append_domain' in __opts__: grain['append_domain'] = __opts__['append_domain'] return grain def fqdns(): ''' Return all known FQDNs for the system by enumerating all interfaces and then trying to reverse resolve them (excluding 'lo' interface). ''' # Provides: # fqdns grains = {} fqdns = set() addresses = salt.utils.network.ip_addrs(include_loopback=False, interface_data=_get_interfaces()) addresses.extend(salt.utils.network.ip_addrs6(include_loopback=False, interface_data=_get_interfaces())) err_message = 'Exception during resolving address: %s' for ip in addresses: try: name, aliaslist, addresslist = socket.gethostbyaddr(ip) fqdns.update([socket.getfqdn(name)] + [als for als in aliaslist if salt.utils.network.is_fqdn(als)]) except socket.herror as err: if err.errno == 0: # No FQDN for this IP address, so we don't need to know this all the time. log.debug("Unable to resolve address %s: %s", ip, err) else: log.error(err_message, err) except (socket.error, socket.gaierror, socket.timeout) as err: log.error(err_message, err) return {"fqdns": sorted(list(fqdns))} def ip_fqdn(): ''' Return ip address and FQDN grains ''' if salt.utils.platform.is_proxy(): return {} ret = {} ret['ipv4'] = salt.utils.network.ip_addrs(include_loopback=True) ret['ipv6'] = salt.utils.network.ip_addrs6(include_loopback=True) _fqdn = hostname()['fqdn'] for socket_type, ipv_num in ((socket.AF_INET, '4'), (socket.AF_INET6, '6')): key = 'fqdn_ip' + ipv_num if not ret['ipv' + ipv_num]: ret[key] = [] else: try: start_time = datetime.datetime.utcnow() info = socket.getaddrinfo(_fqdn, None, socket_type) ret[key] = list(set(item[4][0] for item in info)) except socket.error: timediff = datetime.datetime.utcnow() - start_time if timediff.seconds > 5 and __opts__['__role'] == 'master': log.warning( 'Unable to find IPv%s record for "%s" causing a %s ' 'second timeout when rendering grains. Set the dns or ' '/etc/hosts for IPv%s to clear this.', ipv_num, _fqdn, timediff, ipv_num ) ret[key] = [] return ret def ip_interfaces(): ''' Provide a dict of the connected interfaces and their ip addresses The addresses will be passed as a list for each interface ''' # Provides: # ip_interfaces if salt.utils.platform.is_proxy(): return {} ret = {} ifaces = _get_interfaces() for face in ifaces: iface_ips = [] for inet in ifaces[face].get('inet', []): if 'address' in inet: iface_ips.append(inet['address']) for inet in ifaces[face].get('inet6', []): if 'address' in inet: iface_ips.append(inet['address']) for secondary in ifaces[face].get('secondary', []): if 'address' in secondary: iface_ips.append(secondary['address']) ret[face] = iface_ips return {'ip_interfaces': ret} def ip4_interfaces(): ''' Provide a dict of the connected interfaces and their ip4 addresses The addresses will be passed as a list for each interface ''' # Provides: # ip_interfaces if salt.utils.platform.is_proxy(): return {} ret = {} ifaces = _get_interfaces() for face in ifaces: iface_ips = [] for inet in ifaces[face].get('inet', []): if 'address' in inet: iface_ips.append(inet['address']) for secondary in ifaces[face].get('secondary', []): if 'address' in secondary: iface_ips.append(secondary['address']) ret[face] = iface_ips return {'ip4_interfaces': ret} def ip6_interfaces(): ''' Provide a dict of the connected interfaces and their ip6 addresses The addresses will be passed as a list for each interface ''' # Provides: # ip_interfaces if salt.utils.platform.is_proxy(): return {} ret = {} ifaces = _get_interfaces() for face in ifaces: iface_ips = [] for inet in ifaces[face].get('inet6', []): if 'address' in inet: iface_ips.append(inet['address']) for secondary in ifaces[face].get('secondary', []): if 'address' in secondary: iface_ips.append(secondary['address']) ret[face] = iface_ips return {'ip6_interfaces': ret} def hwaddr_interfaces(): ''' Provide a dict of the connected interfaces and their hw addresses (Mac Address) ''' # Provides: # hwaddr_interfaces ret = {} ifaces = _get_interfaces() for face in ifaces: if 'hwaddr' in ifaces[face]: ret[face] = ifaces[face]['hwaddr'] return {'hwaddr_interfaces': ret} def dns(): ''' Parse the resolver configuration file .. versionadded:: 2016.3.0 ''' # Provides: # dns if salt.utils.platform.is_windows() or 'proxyminion' in __opts__: return {} resolv = salt.utils.dns.parse_resolv() for key in ('nameservers', 'ip4_nameservers', 'ip6_nameservers', 'sortlist'): if key in resolv: resolv[key] = [six.text_type(i) for i in resolv[key]] return {'dns': resolv} if resolv else {} def get_machine_id(): ''' Provide the machine-id for machine/virtualization combination ''' # Provides: # machine-id if platform.system() == 'AIX': return _aix_get_machine_id() locations = ['/etc/machine-id', '/var/lib/dbus/machine-id'] existing_locations = [loc for loc in locations if os.path.exists(loc)] if not existing_locations: return {} else: with salt.utils.files.fopen(existing_locations[0]) as machineid: return {'machine_id': machineid.read().strip()} def cwd(): ''' Current working directory ''' return {'cwd': os.getcwd()} def path(): ''' Return the path ''' # Provides: # path return {'path': os.environ.get('PATH', '').strip()} def pythonversion(): ''' Return the Python version ''' # Provides: # pythonversion return {'pythonversion': list(sys.version_info)} def pythonpath(): ''' Return the Python path ''' # Provides: # pythonpath return {'pythonpath': sys.path} def pythonexecutable(): ''' Return the python executable in use ''' # Provides: # pythonexecutable return {'pythonexecutable': sys.executable} def saltpath(): ''' Return the path of the salt module ''' # Provides: # saltpath salt_path = os.path.abspath(os.path.join(__file__, os.path.pardir)) return {'saltpath': os.path.dirname(salt_path)} def saltversion(): ''' Return the version of salt ''' # Provides: # saltversion from salt.version import __version__ return {'saltversion': __version__} def zmqversion(): ''' Return the zeromq version ''' # Provides: # zmqversion try: import zmq return {'zmqversion': zmq.zmq_version()} # pylint: disable=no-member except ImportError: return {} def saltversioninfo(): ''' Return the version_info of salt .. versionadded:: 0.17.0 ''' # Provides: # saltversioninfo from salt.version import __version_info__ return {'saltversioninfo': list(__version_info__)} def _hw_data(osdata): ''' Get system specific hardware data from dmidecode Provides biosversion productname manufacturer serialnumber biosreleasedate uuid .. versionadded:: 0.9.5 ''' if salt.utils.platform.is_proxy(): return {} grains = {} if osdata['kernel'] == 'Linux' and os.path.exists('/sys/class/dmi/id'): # On many Linux distributions basic firmware information is available via sysfs # requires CONFIG_DMIID to be enabled in the Linux kernel configuration sysfs_firmware_info = { 'biosversion': 'bios_version', 'productname': 'product_name', 'manufacturer': 'sys_vendor', 'biosreleasedate': 'bios_date', 'uuid': 'product_uuid', 'serialnumber': 'product_serial' } for key, fw_file in sysfs_firmware_info.items(): contents_file = os.path.join('/sys/class/dmi/id', fw_file) if os.path.exists(contents_file): try: with salt.utils.files.fopen(contents_file, 'r') as ifile: grains[key] = salt.utils.stringutils.to_unicode(ifile.read().strip(), errors='replace') if key == 'uuid': grains['uuid'] = grains['uuid'].lower() except (IOError, OSError) as err: # PermissionError is new to Python 3, but corresponds to the EACESS and # EPERM error numbers. Use those instead here for PY2 compatibility. if err.errno == EACCES or err.errno == EPERM: # Skip the grain if non-root user has no access to the file. pass elif salt.utils.path.which_bin(['dmidecode', 'smbios']) is not None and not ( salt.utils.platform.is_smartos() or ( # SunOS on SPARC - 'smbios: failed to load SMBIOS: System does not export an SMBIOS table' osdata['kernel'] == 'SunOS' and osdata['cpuarch'].startswith('sparc') )): # On SmartOS (possibly SunOS also) smbios only works in the global zone # smbios is also not compatible with linux's smbios (smbios -s = print summarized) grains = { 'biosversion': __salt__['smbios.get']('bios-version'), 'productname': __salt__['smbios.get']('system-product-name'), 'manufacturer': __salt__['smbios.get']('system-manufacturer'), 'biosreleasedate': __salt__['smbios.get']('bios-release-date'), 'uuid': __salt__['smbios.get']('system-uuid') } grains = dict([(key, val) for key, val in grains.items() if val is not None]) uuid = __salt__['smbios.get']('system-uuid') if uuid is not None: grains['uuid'] = uuid.lower() for serial in ('system-serial-number', 'chassis-serial-number', 'baseboard-serial-number'): serial = __salt__['smbios.get'](serial) if serial is not None: grains['serialnumber'] = serial break elif salt.utils.path.which_bin(['fw_printenv']) is not None: # ARM Linux devices expose UBOOT env variables via fw_printenv hwdata = { 'manufacturer': 'manufacturer', 'serialnumber': 'serial#', 'productname': 'DeviceDesc', } for grain_name, cmd_key in six.iteritems(hwdata): result = __salt__['cmd.run_all']('fw_printenv {0}'.format(cmd_key)) if result['retcode'] == 0: uboot_keyval = result['stdout'].split('=') grains[grain_name] = _clean_value(grain_name, uboot_keyval[1]) elif osdata['kernel'] == 'FreeBSD': # On FreeBSD /bin/kenv (already in base system) # can be used instead of dmidecode kenv = salt.utils.path.which('kenv') if kenv: # In theory, it will be easier to add new fields to this later fbsd_hwdata = { 'biosversion': 'smbios.bios.version', 'manufacturer': 'smbios.system.maker', 'serialnumber': 'smbios.system.serial', 'productname': 'smbios.system.product', 'biosreleasedate': 'smbios.bios.reldate', 'uuid': 'smbios.system.uuid', } for key, val in six.iteritems(fbsd_hwdata): value = __salt__['cmd.run']('{0} {1}'.format(kenv, val)) grains[key] = _clean_value(key, value) elif osdata['kernel'] == 'OpenBSD': sysctl = salt.utils.path.which('sysctl') hwdata = {'biosversion': 'hw.version', 'manufacturer': 'hw.vendor', 'productname': 'hw.product', 'serialnumber': 'hw.serialno', 'uuid': 'hw.uuid'} for key, oid in six.iteritems(hwdata): value = __salt__['cmd.run']('{0} -n {1}'.format(sysctl, oid)) if not value.endswith(' value is not available'): grains[key] = _clean_value(key, value) elif osdata['kernel'] == 'NetBSD': sysctl = salt.utils.path.which('sysctl') nbsd_hwdata = { 'biosversion': 'machdep.dmi.board-version', 'manufacturer': 'machdep.dmi.system-vendor', 'serialnumber': 'machdep.dmi.system-serial', 'productname': 'machdep.dmi.system-product', 'biosreleasedate': 'machdep.dmi.bios-date', 'uuid': 'machdep.dmi.system-uuid', } for key, oid in six.iteritems(nbsd_hwdata): result = __salt__['cmd.run_all']('{0} -n {1}'.format(sysctl, oid)) if result['retcode'] == 0: grains[key] = _clean_value(key, result['stdout']) elif osdata['kernel'] == 'Darwin': grains['manufacturer'] = 'Apple Inc.' sysctl = salt.utils.path.which('sysctl') hwdata = {'productname': 'hw.model'} for key, oid in hwdata.items(): value = __salt__['cmd.run']('{0} -b {1}'.format(sysctl, oid)) if not value.endswith(' is invalid'): grains[key] = _clean_value(key, value) elif osdata['kernel'] == 'SunOS' and osdata['cpuarch'].startswith('sparc'): # Depending on the hardware model, commands can report different bits # of information. With that said, consolidate the output from various # commands and attempt various lookups. data = "" for (cmd, args) in (('/usr/sbin/prtdiag', '-v'), ('/usr/sbin/prtconf', '-vp'), ('/usr/sbin/virtinfo', '-a')): if salt.utils.path.which(cmd): # Also verifies that cmd is executable data += __salt__['cmd.run']('{0} {1}'.format(cmd, args)) data += '\n' sn_regexes = [ re.compile(r) for r in [ r'(?im)^\s*Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag r'(?im)^\s*chassis-sn:\s*(\S+)', # prtconf r'(?im)^\s*Chassis\s+Serial#:\s*(\S+)', # virtinfo ] ] obp_regexes = [ re.compile(r) for r in [ r'(?im)^\s*System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag r'(?im)^\s*version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf ] ] fw_regexes = [ re.compile(r) for r in [ r'(?im)^\s*Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag ] ] uuid_regexes = [ re.compile(r) for r in [ r'(?im)^\s*Domain\s+UUID:\s*(\S+)', # virtinfo ] ] manufacture_regexes = [ re.compile(r) for r in [ r'(?im)^\s*System\s+Configuration:\s*(.*)(?=sun)', # prtdiag ] ] product_regexes = [ re.compile(r) for r in [ r'(?im)^\s*System\s+Configuration:\s*.*?sun\d\S+[^\S\r\n]*(.*)', # prtdiag r'(?im)^[^\S\r\n]*banner-name:[^\S\r\n]*(.*)', # prtconf r'(?im)^[^\S\r\n]*product-name:[^\S\r\n]*(.*)', # prtconf ] ] sn_regexes = [ re.compile(r) for r in [ r'(?im)Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag r'(?i)Chassis\s+Serial#:\s*(\S+)', # virtinfo r'(?i)chassis-sn:\s*(\S+)', # prtconf ] ] obp_regexes = [ re.compile(r) for r in [ r'(?im)System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag r'(?im)version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf ] ] fw_regexes = [ re.compile(r) for r in [ r'(?i)Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag ] ] uuid_regexes = [ re.compile(r) for r in [ r'(?i)Domain\s+UUID:\s+(\S+)', # virtinfo ] ] for regex in sn_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: grains['serialnumber'] = res.group(1).strip().replace("'", "") break for regex in obp_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: obp_rev, obp_date = res.groups()[0:2] # Limit the number in case we found the data in multiple places grains['biosversion'] = obp_rev.strip().replace("'", "") grains['biosreleasedate'] = obp_date.strip().replace("'", "") for regex in fw_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: fw_rev, fw_date = res.groups()[0:2] grains['systemfirmware'] = fw_rev.strip().replace("'", "") grains['systemfirmwaredate'] = fw_date.strip().replace("'", "") break for regex in uuid_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: grains['uuid'] = res.group(1).strip().replace("'", "") break for regex in manufacture_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: grains['manufacture'] = res.group(1).strip().replace("'", "") break for regex in product_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: t_productname = res.group(1).strip().replace("'", "") if t_productname: grains['product'] = t_productname grains['productname'] = t_productname break elif osdata['kernel'] == 'AIX': cmd = salt.utils.path.which('prtconf') if cmd: data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'), ('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')): for regex in [re.compile(r) for r in [regstring]]: res = regex.search(data) if res and len(res.groups()) >= 1: grains[dest] = res.group(1).strip().replace("'", '') product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')] for regex in product_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",") break else: log.error('The \'prtconf\' binary was not found in $PATH.') elif osdata['kernel'] == 'AIX': cmd = salt.utils.path.which('prtconf') if data: data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'), ('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')): for regex in [re.compile(r) for r in [regstring]]: res = regex.search(data) if res and len(res.groups()) >= 1: grains[dest] = res.group(1).strip().replace("'", '') product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')] for regex in product_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",") break else: log.error('The \'prtconf\' binary was not found in $PATH.') return grains def _get_hash_by_shell(): ''' Shell-out Python 3 for compute reliable hash :return: ''' id_ = __opts__.get('id', '') id_hash = None py_ver = sys.version_info[:2] if py_ver >= (3, 3): # Python 3.3 enabled hash randomization, so we need to shell out to get # a reliable hash. id_hash = __salt__['cmd.run']([sys.executable, '-c', 'print(hash("{0}"))'.format(id_)], env={'PYTHONHASHSEED': '0'}) try: id_hash = int(id_hash) except (TypeError, ValueError): log.debug('Failed to hash the ID to get the server_id grain. Result of hash command: %s', id_hash) id_hash = None if id_hash is None: # Python < 3.3 or error encountered above id_hash = hash(id_) return abs(id_hash % (2 ** 31)) def get_master(): ''' Provides the minion with the name of its master. This is useful in states to target other services running on the master. ''' # Provides: # master return {'master': __opts__.get('master', '')} def default_gateway(): ''' Populates grains which describe whether a server has a default gateway configured or not. Uses `ip -4 route show` and `ip -6 route show` and greps for a `default` at the beginning of any line. Assuming the standard `default via <ip>` format for default gateways, it will also parse out the ip address of the default gateway, and put it in ip4_gw or ip6_gw. If the `ip` command is unavailable, no grains will be populated. Currently does not support multiple default gateways. The grains will be set to the first default gateway found. List of grains: ip4_gw: True # ip/True/False if default ipv4 gateway ip6_gw: True # ip/True/False if default ipv6 gateway ip_gw: True # True if either of the above is True, False otherwise ''' grains = {} ip_bin = salt.utils.path.which('ip') if not ip_bin: return {} grains['ip_gw'] = False grains['ip4_gw'] = False grains['ip6_gw'] = False for ip_version in ('4', '6'): try: out = __salt__['cmd.run']([ip_bin, '-' + ip_version, 'route', 'show']) for line in out.splitlines(): if line.startswith('default'): grains['ip_gw'] = True grains['ip{0}_gw'.format(ip_version)] = True try: via, gw_ip = line.split()[1:3] except ValueError: pass else: if via == 'via': grains['ip{0}_gw'.format(ip_version)] = gw_ip break except Exception: continue return grains def kernelparams(): ''' Return the kernel boot parameters ''' if salt.utils.platform.is_windows(): # TODO: add grains using `bcdedit /enum {current}` return {} else: try: with salt.utils.files.fopen('/proc/cmdline', 'r') as fhr: cmdline = fhr.read() grains = {'kernelparams': []} for data in [item.split('=') for item in salt.utils.args.shlex_split(cmdline)]: value = None if len(data) == 2: value = data[1].strip('"') grains['kernelparams'] += [(data[0], value)] except IOError as exc: grains = {} log.debug('Failed to read /proc/cmdline: %s', exc) return grains
saltstack/salt
salt/grains/core.py
default_gateway
python
def default_gateway(): ''' Populates grains which describe whether a server has a default gateway configured or not. Uses `ip -4 route show` and `ip -6 route show` and greps for a `default` at the beginning of any line. Assuming the standard `default via <ip>` format for default gateways, it will also parse out the ip address of the default gateway, and put it in ip4_gw or ip6_gw. If the `ip` command is unavailable, no grains will be populated. Currently does not support multiple default gateways. The grains will be set to the first default gateway found. List of grains: ip4_gw: True # ip/True/False if default ipv4 gateway ip6_gw: True # ip/True/False if default ipv6 gateway ip_gw: True # True if either of the above is True, False otherwise ''' grains = {} ip_bin = salt.utils.path.which('ip') if not ip_bin: return {} grains['ip_gw'] = False grains['ip4_gw'] = False grains['ip6_gw'] = False for ip_version in ('4', '6'): try: out = __salt__['cmd.run']([ip_bin, '-' + ip_version, 'route', 'show']) for line in out.splitlines(): if line.startswith('default'): grains['ip_gw'] = True grains['ip{0}_gw'.format(ip_version)] = True try: via, gw_ip = line.split()[1:3] except ValueError: pass else: if via == 'via': grains['ip{0}_gw'.format(ip_version)] = gw_ip break except Exception: continue return grains
Populates grains which describe whether a server has a default gateway configured or not. Uses `ip -4 route show` and `ip -6 route show` and greps for a `default` at the beginning of any line. Assuming the standard `default via <ip>` format for default gateways, it will also parse out the ip address of the default gateway, and put it in ip4_gw or ip6_gw. If the `ip` command is unavailable, no grains will be populated. Currently does not support multiple default gateways. The grains will be set to the first default gateway found. List of grains: ip4_gw: True # ip/True/False if default ipv4 gateway ip6_gw: True # ip/True/False if default ipv6 gateway ip_gw: True # True if either of the above is True, False otherwise
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/grains/core.py#L2801-L2844
null
# -*- coding: utf-8 -*- ''' The static grains, these are the core, or built in grains. When grains are loaded they are not loaded in the same way that modules are loaded, grain functions are detected and executed, the functions MUST return a dict which will be applied to the main grains dict. This module will always be executed first, so that any grains loaded here in the core module can be overwritten just by returning dict keys with the same value as those returned here ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import socket import sys import re import platform import logging import locale import uuid import zlib from errno import EACCES, EPERM import datetime import warnings # pylint: disable=import-error try: import dateutil.tz _DATEUTIL_TZ = True except ImportError: _DATEUTIL_TZ = False __proxyenabled__ = ['*'] __FQDN__ = None # Extend the default list of supported distros. This will be used for the # /etc/DISTRO-release checking that is part of linux_distribution() from platform import _supported_dists _supported_dists += ('arch', 'mageia', 'meego', 'vmware', 'bluewhite64', 'slamd64', 'ovs', 'system', 'mint', 'oracle', 'void') # linux_distribution deprecated in py3.7 try: from platform import linux_distribution as _deprecated_linux_distribution def linux_distribution(**kwargs): with warnings.catch_warnings(): warnings.simplefilter("ignore") return _deprecated_linux_distribution(**kwargs) except ImportError: from distro import linux_distribution # Import salt libs import salt.exceptions import salt.log import salt.utils.args import salt.utils.dns import salt.utils.files import salt.utils.network import salt.utils.path import salt.utils.pkg.rpm import salt.utils.platform import salt.utils.stringutils import salt.utils.versions from salt.ext import six from salt.ext.six.moves import range if salt.utils.platform.is_windows(): import salt.utils.win_osinfo # Solve the Chicken and egg problem where grains need to run before any # of the modules are loaded and are generally available for any usage. import salt.modules.cmdmod import salt.modules.smbios __salt__ = { 'cmd.run': salt.modules.cmdmod._run_quiet, 'cmd.retcode': salt.modules.cmdmod._retcode_quiet, 'cmd.run_all': salt.modules.cmdmod._run_all_quiet, 'smbios.records': salt.modules.smbios.records, 'smbios.get': salt.modules.smbios.get, } log = logging.getLogger(__name__) HAS_WMI = False if salt.utils.platform.is_windows(): # attempt to import the python wmi module # the Windows minion uses WMI for some of its grains try: import wmi # pylint: disable=import-error import salt.utils.winapi import win32api import salt.utils.win_reg HAS_WMI = True except ImportError: log.exception( 'Unable to import Python wmi module, some core grains ' 'will be missing' ) HAS_UNAME = True if not hasattr(os, 'uname'): HAS_UNAME = False _INTERFACES = {} def _windows_cpudata(): ''' Return some CPU information on Windows minions ''' # Provides: # num_cpus # cpu_model grains = {} if 'NUMBER_OF_PROCESSORS' in os.environ: # Cast to int so that the logic isn't broken when used as a # conditional in templating. Also follows _linux_cpudata() try: grains['num_cpus'] = int(os.environ['NUMBER_OF_PROCESSORS']) except ValueError: grains['num_cpus'] = 1 grains['cpu_model'] = salt.utils.win_reg.read_value( hive="HKEY_LOCAL_MACHINE", key="HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", vname="ProcessorNameString").get('vdata') return grains def _linux_cpudata(): ''' Return some CPU information for Linux minions ''' # Provides: # num_cpus # cpu_model # cpu_flags grains = {} cpuinfo = '/proc/cpuinfo' # Parse over the cpuinfo file if os.path.isfile(cpuinfo): with salt.utils.files.fopen(cpuinfo, 'r') as _fp: grains['num_cpus'] = 0 for line in _fp: comps = line.split(':') if not len(comps) > 1: continue key = comps[0].strip() val = comps[1].strip() if key == 'processor': grains['num_cpus'] += 1 elif key == 'model name': grains['cpu_model'] = val elif key == 'flags': grains['cpu_flags'] = val.split() elif key == 'Features': grains['cpu_flags'] = val.split() # ARM support - /proc/cpuinfo # # Processor : ARMv6-compatible processor rev 7 (v6l) # BogoMIPS : 697.95 # Features : swp half thumb fastmult vfp edsp java tls # CPU implementer : 0x41 # CPU architecture: 7 # CPU variant : 0x0 # CPU part : 0xb76 # CPU revision : 7 # # Hardware : BCM2708 # Revision : 0002 # Serial : 00000000 elif key == 'Processor': grains['cpu_model'] = val.split('-')[0] grains['num_cpus'] = 1 if 'num_cpus' not in grains: grains['num_cpus'] = 0 if 'cpu_model' not in grains: grains['cpu_model'] = 'Unknown' if 'cpu_flags' not in grains: grains['cpu_flags'] = [] return grains def _linux_gpu_data(): ''' num_gpus: int gpus: - vendor: nvidia|amd|ati|... model: string ''' if __opts__.get('enable_lspci', True) is False: return {} if __opts__.get('enable_gpu_grains', True) is False: return {} lspci = salt.utils.path.which('lspci') if not lspci: log.debug( 'The `lspci` binary is not available on the system. GPU grains ' 'will not be available.' ) return {} # dominant gpu vendors to search for (MUST be lowercase for matching below) known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed'] gpu_classes = ('vga compatible controller', '3d controller') devs = [] try: lspci_out = __salt__['cmd.run']('{0} -vmm'.format(lspci)) cur_dev = {} error = False # Add a blank element to the lspci_out.splitlines() list, # otherwise the last device is not evaluated as a cur_dev and ignored. lspci_list = lspci_out.splitlines() lspci_list.append('') for line in lspci_list: # check for record-separating empty lines if line == '': if cur_dev.get('Class', '').lower() in gpu_classes: devs.append(cur_dev) cur_dev = {} continue if re.match(r'^\w+:\s+.*', line): key, val = line.split(':', 1) cur_dev[key.strip()] = val.strip() else: error = True log.debug('Unexpected lspci output: \'%s\'', line) if error: log.warning( 'Error loading grains, unexpected linux_gpu_data output, ' 'check that you have a valid shell configured and ' 'permissions to run lspci command' ) except OSError: pass gpus = [] for gpu in devs: vendor_strings = re.split('[^A-Za-z0-9]', gpu['Vendor'].lower()) # default vendor to 'unknown', overwrite if we match a known one vendor = 'unknown' for name in known_vendors: # search for an 'expected' vendor name in the list of strings if name in vendor_strings: vendor = name break gpus.append({'vendor': vendor, 'model': gpu['Device']}) grains = {} grains['num_gpus'] = len(gpus) grains['gpus'] = gpus return grains def _netbsd_gpu_data(): ''' num_gpus: int gpus: - vendor: nvidia|amd|ati|... model: string ''' known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed'] gpus = [] try: pcictl_out = __salt__['cmd.run']('pcictl pci0 list') for line in pcictl_out.splitlines(): for vendor in known_vendors: vendor_match = re.match( r'[0-9:]+ ({0}) (.+) \(VGA .+\)'.format(vendor), line, re.IGNORECASE ) if vendor_match: gpus.append({'vendor': vendor_match.group(1), 'model': vendor_match.group(2)}) except OSError: pass grains = {} grains['num_gpus'] = len(gpus) grains['gpus'] = gpus return grains def _osx_gpudata(): ''' num_gpus: int gpus: - vendor: nvidia|amd|ati|... model: string ''' gpus = [] try: pcictl_out = __salt__['cmd.run']('system_profiler SPDisplaysDataType') for line in pcictl_out.splitlines(): fieldname, _, fieldval = line.partition(': ') if fieldname.strip() == "Chipset Model": vendor, _, model = fieldval.partition(' ') vendor = vendor.lower() gpus.append({'vendor': vendor, 'model': model}) except OSError: pass grains = {} grains['num_gpus'] = len(gpus) grains['gpus'] = gpus return grains def _bsd_cpudata(osdata): ''' Return CPU information for BSD-like systems ''' # Provides: # cpuarch # num_cpus # cpu_model # cpu_flags sysctl = salt.utils.path.which('sysctl') arch = salt.utils.path.which('arch') cmds = {} if sysctl: cmds.update({ 'num_cpus': '{0} -n hw.ncpu'.format(sysctl), 'cpuarch': '{0} -n hw.machine'.format(sysctl), 'cpu_model': '{0} -n hw.model'.format(sysctl), }) if arch and osdata['kernel'] == 'OpenBSD': cmds['cpuarch'] = '{0} -s'.format(arch) if osdata['kernel'] == 'Darwin': cmds['cpu_model'] = '{0} -n machdep.cpu.brand_string'.format(sysctl) cmds['cpu_flags'] = '{0} -n machdep.cpu.features'.format(sysctl) grains = dict([(k, __salt__['cmd.run'](v)) for k, v in six.iteritems(cmds)]) if 'cpu_flags' in grains and isinstance(grains['cpu_flags'], six.string_types): grains['cpu_flags'] = grains['cpu_flags'].split(' ') if osdata['kernel'] == 'NetBSD': grains['cpu_flags'] = [] for line in __salt__['cmd.run']('cpuctl identify 0').splitlines(): cpu_match = re.match(r'cpu[0-9]:\ features[0-9]?\ .+<(.+)>', line) if cpu_match: flag = cpu_match.group(1).split(',') grains['cpu_flags'].extend(flag) if osdata['kernel'] == 'FreeBSD' and os.path.isfile('/var/run/dmesg.boot'): grains['cpu_flags'] = [] # TODO: at least it needs to be tested for BSD other then FreeBSD with salt.utils.files.fopen('/var/run/dmesg.boot', 'r') as _fp: cpu_here = False for line in _fp: if line.startswith('CPU: '): cpu_here = True # starts CPU descr continue if cpu_here: if not line.startswith(' '): break # game over if 'Features' in line: start = line.find('<') end = line.find('>') if start > 0 and end > 0: flag = line[start + 1:end].split(',') grains['cpu_flags'].extend(flag) try: grains['num_cpus'] = int(grains['num_cpus']) except ValueError: grains['num_cpus'] = 1 return grains def _sunos_cpudata(): ''' Return the CPU information for Solaris-like systems ''' # Provides: # cpuarch # num_cpus # cpu_model # cpu_flags grains = {} grains['cpu_flags'] = [] grains['cpuarch'] = __salt__['cmd.run']('isainfo -k') psrinfo = '/usr/sbin/psrinfo 2>/dev/null' grains['num_cpus'] = len(__salt__['cmd.run'](psrinfo, python_shell=True).splitlines()) kstat_info = 'kstat -p cpu_info:*:*:brand' for line in __salt__['cmd.run'](kstat_info).splitlines(): match = re.match(r'(\w+:\d+:\w+\d+:\w+)\s+(.+)', line) if match: grains['cpu_model'] = match.group(2) isainfo = 'isainfo -n -v' for line in __salt__['cmd.run'](isainfo).splitlines(): match = re.match(r'^\s+(.+)', line) if match: cpu_flags = match.group(1).split() grains['cpu_flags'].extend(cpu_flags) return grains def _aix_cpudata(): ''' Return CPU information for AIX systems ''' # Provides: # cpuarch # num_cpus # cpu_model # cpu_flags grains = {} cmd = salt.utils.path.which('prtconf') if cmd: data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep for dest, regstring in (('cpuarch', r'(?im)^\s*Processor\s+Type:\s+(\S+)'), ('cpu_flags', r'(?im)^\s*Processor\s+Version:\s+(\S+)'), ('cpu_model', r'(?im)^\s*Processor\s+Implementation\s+Mode:\s+(.*)'), ('num_cpus', r'(?im)^\s*Number\s+Of\s+Processors:\s+(\S+)')): for regex in [re.compile(r) for r in [regstring]]: res = regex.search(data) if res and len(res.groups()) >= 1: grains[dest] = res.group(1).strip().replace("'", '') else: log.error('The \'prtconf\' binary was not found in $PATH.') return grains def _linux_memdata(): ''' Return the memory information for Linux-like systems ''' grains = {'mem_total': 0, 'swap_total': 0} meminfo = '/proc/meminfo' if os.path.isfile(meminfo): with salt.utils.files.fopen(meminfo, 'r') as ifile: for line in ifile: comps = line.rstrip('\n').split(':') if not len(comps) > 1: continue if comps[0].strip() == 'MemTotal': # Use floor division to force output to be an integer grains['mem_total'] = int(comps[1].split()[0]) // 1024 if comps[0].strip() == 'SwapTotal': # Use floor division to force output to be an integer grains['swap_total'] = int(comps[1].split()[0]) // 1024 return grains def _osx_memdata(): ''' Return the memory information for BSD-like systems ''' grains = {'mem_total': 0, 'swap_total': 0} sysctl = salt.utils.path.which('sysctl') if sysctl: mem = __salt__['cmd.run']('{0} -n hw.memsize'.format(sysctl)) swap_total = __salt__['cmd.run']('{0} -n vm.swapusage'.format(sysctl)).split()[2].replace(',', '.') if swap_total.endswith('K'): _power = 2**10 elif swap_total.endswith('M'): _power = 2**20 elif swap_total.endswith('G'): _power = 2**30 swap_total = float(swap_total[:-1]) * _power grains['mem_total'] = int(mem) // 1024 // 1024 grains['swap_total'] = int(swap_total) // 1024 // 1024 return grains def _bsd_memdata(osdata): ''' Return the memory information for BSD-like systems ''' grains = {'mem_total': 0, 'swap_total': 0} sysctl = salt.utils.path.which('sysctl') if sysctl: mem = __salt__['cmd.run']('{0} -n hw.physmem'.format(sysctl)) if osdata['kernel'] == 'NetBSD' and mem.startswith('-'): mem = __salt__['cmd.run']('{0} -n hw.physmem64'.format(sysctl)) grains['mem_total'] = int(mem) // 1024 // 1024 if osdata['kernel'] in ['OpenBSD', 'NetBSD']: swapctl = salt.utils.path.which('swapctl') swap_data = __salt__['cmd.run']('{0} -sk'.format(swapctl)) if swap_data == 'no swap devices configured': swap_total = 0 else: swap_total = swap_data.split(' ')[1] else: swap_total = __salt__['cmd.run']('{0} -n vm.swap_total'.format(sysctl)) grains['swap_total'] = int(swap_total) // 1024 // 1024 return grains def _sunos_memdata(): ''' Return the memory information for SunOS-like systems ''' grains = {'mem_total': 0, 'swap_total': 0} prtconf = '/usr/sbin/prtconf 2>/dev/null' for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines(): comps = line.split(' ') if comps[0].strip() == 'Memory' and comps[1].strip() == 'size:': grains['mem_total'] = int(comps[2].strip()) swap_cmd = salt.utils.path.which('swap') swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split() try: swap_avail = int(swap_data[-2][:-1]) swap_used = int(swap_data[-4][:-1]) swap_total = (swap_avail + swap_used) // 1024 except ValueError: swap_total = None grains['swap_total'] = swap_total return grains def _aix_memdata(): ''' Return the memory information for AIX systems ''' grains = {'mem_total': 0, 'swap_total': 0} prtconf = salt.utils.path.which('prtconf') if prtconf: for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines(): comps = [x for x in line.strip().split(' ') if x] if len(comps) > 2 and 'Memory' in comps[0] and 'Size' in comps[1]: grains['mem_total'] = int(comps[2]) break else: log.error('The \'prtconf\' binary was not found in $PATH.') swap_cmd = salt.utils.path.which('swap') if swap_cmd: swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split() try: swap_total = (int(swap_data[-2]) + int(swap_data[-6])) * 4 except ValueError: swap_total = None grains['swap_total'] = swap_total else: log.error('The \'swap\' binary was not found in $PATH.') return grains def _windows_memdata(): ''' Return the memory information for Windows systems ''' grains = {'mem_total': 0} # get the Total Physical memory as reported by msinfo32 tot_bytes = win32api.GlobalMemoryStatusEx()['TotalPhys'] # return memory info in gigabytes grains['mem_total'] = int(tot_bytes / (1024 ** 2)) return grains def _memdata(osdata): ''' Gather information about the system memory ''' # Provides: # mem_total # swap_total, for supported systems. grains = {'mem_total': 0} if osdata['kernel'] == 'Linux': grains.update(_linux_memdata()) elif osdata['kernel'] in ('FreeBSD', 'OpenBSD', 'NetBSD'): grains.update(_bsd_memdata(osdata)) elif osdata['kernel'] == 'Darwin': grains.update(_osx_memdata()) elif osdata['kernel'] == 'SunOS': grains.update(_sunos_memdata()) elif osdata['kernel'] == 'AIX': grains.update(_aix_memdata()) elif osdata['kernel'] == 'Windows' and HAS_WMI: grains.update(_windows_memdata()) return grains def _aix_get_machine_id(): ''' Parse the output of lsattr -El sys0 for os_uuid ''' grains = {} cmd = salt.utils.path.which('lsattr') if cmd: data = __salt__['cmd.run']('{0} -El sys0'.format(cmd)) + os.linesep uuid_regexes = [re.compile(r'(?im)^\s*os_uuid\s+(\S+)\s+(.*)')] for regex in uuid_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: grains['machine_id'] = res.group(1).strip() break else: log.error('The \'lsattr\' binary was not found in $PATH.') return grains def _windows_virtual(osdata): ''' Returns what type of virtual hardware is under the hood, kvm or physical ''' # Provides: # virtual # virtual_subtype grains = dict() if osdata['kernel'] != 'Windows': return grains grains['virtual'] = 'physical' # It is possible that the 'manufacturer' and/or 'productname' grains # exist but have a value of None. manufacturer = osdata.get('manufacturer', '') if manufacturer is None: manufacturer = '' productname = osdata.get('productname', '') if productname is None: productname = '' if 'QEMU' in manufacturer: # FIXME: Make this detect between kvm or qemu grains['virtual'] = 'kvm' if 'Bochs' in manufacturer: grains['virtual'] = 'kvm' # Product Name: (oVirt) www.ovirt.org # Red Hat Community virtualization Project based on kvm elif 'oVirt' in productname: grains['virtual'] = 'kvm' grains['virtual_subtype'] = 'oVirt' # Red Hat Enterprise Virtualization elif 'RHEV Hypervisor' in productname: grains['virtual'] = 'kvm' grains['virtual_subtype'] = 'rhev' # Product Name: VirtualBox elif 'VirtualBox' in productname: grains['virtual'] = 'VirtualBox' # Product Name: VMware Virtual Platform elif 'VMware Virtual Platform' in productname: grains['virtual'] = 'VMware' # Manufacturer: Microsoft Corporation # Product Name: Virtual Machine elif 'Microsoft' in manufacturer and \ 'Virtual Machine' in productname: grains['virtual'] = 'VirtualPC' # Manufacturer: Parallels Software International Inc. elif 'Parallels Software' in manufacturer: grains['virtual'] = 'Parallels' # Apache CloudStack elif 'CloudStack KVM Hypervisor' in productname: grains['virtual'] = 'kvm' grains['virtual_subtype'] = 'cloudstack' return grains def _virtual(osdata): ''' Returns what type of virtual hardware is under the hood, kvm or physical ''' # This is going to be a monster, if you are running a vm you can test this # grain with please submit patches! # Provides: # virtual # virtual_subtype grains = {'virtual': 'physical'} # Skip the below loop on platforms which have none of the desired cmds # This is a temporary measure until we can write proper virtual hardware # detection. skip_cmds = ('AIX',) # list of commands to be executed to determine the 'virtual' grain _cmds = ['systemd-detect-virt', 'virt-what', 'dmidecode'] # test first for virt-what, which covers most of the desired functionality # on most platforms if not salt.utils.platform.is_windows() and osdata['kernel'] not in skip_cmds: if salt.utils.path.which('virt-what'): _cmds = ['virt-what'] # Check if enable_lspci is True or False if __opts__.get('enable_lspci', True) is True: # /proc/bus/pci does not exists, lspci will fail if os.path.exists('/proc/bus/pci'): _cmds += ['lspci'] # Add additional last resort commands if osdata['kernel'] in skip_cmds: _cmds = () # Quick backout for BrandZ (Solaris LX Branded zones) # Don't waste time trying other commands to detect the virtual grain if HAS_UNAME and osdata['kernel'] == 'Linux' and 'BrandZ virtual linux' in os.uname(): grains['virtual'] = 'zone' return grains failed_commands = set() for command in _cmds: args = [] if osdata['kernel'] == 'Darwin': command = 'system_profiler' args = ['SPDisplaysDataType'] elif osdata['kernel'] == 'SunOS': virtinfo = salt.utils.path.which('virtinfo') if virtinfo: try: ret = __salt__['cmd.run_all']('{0} -a'.format(virtinfo)) except salt.exceptions.CommandExecutionError: if salt.log.is_logging_configured(): failed_commands.add(virtinfo) else: if ret['stdout'].endswith('not supported'): command = 'prtdiag' else: command = 'virtinfo' else: command = 'prtdiag' cmd = salt.utils.path.which(command) if not cmd: continue cmd = '{0} {1}'.format(cmd, ' '.join(args)) try: ret = __salt__['cmd.run_all'](cmd) if ret['retcode'] > 0: if salt.log.is_logging_configured(): # systemd-detect-virt always returns > 0 on non-virtualized # systems # prtdiag only works in the global zone, skip if it fails if salt.utils.platform.is_windows() or 'systemd-detect-virt' in cmd or 'prtdiag' in cmd: continue failed_commands.add(command) continue except salt.exceptions.CommandExecutionError: if salt.log.is_logging_configured(): if salt.utils.platform.is_windows(): continue failed_commands.add(command) continue output = ret['stdout'] if command == "system_profiler": macoutput = output.lower() if '0x1ab8' in macoutput: grains['virtual'] = 'Parallels' if 'parallels' in macoutput: grains['virtual'] = 'Parallels' if 'vmware' in macoutput: grains['virtual'] = 'VMware' if '0x15ad' in macoutput: grains['virtual'] = 'VMware' if 'virtualbox' in macoutput: grains['virtual'] = 'VirtualBox' # Break out of the loop so the next log message is not issued break elif command == 'systemd-detect-virt': if output in ('qemu', 'kvm', 'oracle', 'xen', 'bochs', 'chroot', 'uml', 'systemd-nspawn'): grains['virtual'] = output break elif 'vmware' in output: grains['virtual'] = 'VMware' break elif 'microsoft' in output: grains['virtual'] = 'VirtualPC' break elif 'lxc' in output: grains['virtual'] = 'LXC' break elif 'systemd-nspawn' in output: grains['virtual'] = 'LXC' break elif command == 'virt-what': try: output = output.splitlines()[-1] except IndexError: pass if output in ('kvm', 'qemu', 'uml', 'xen', 'lxc'): grains['virtual'] = output break elif 'vmware' in output: grains['virtual'] = 'VMware' break elif 'parallels' in output: grains['virtual'] = 'Parallels' break elif 'hyperv' in output: grains['virtual'] = 'HyperV' break elif command == 'dmidecode': # Product Name: VirtualBox if 'Vendor: QEMU' in output: # FIXME: Make this detect between kvm or qemu grains['virtual'] = 'kvm' if 'Manufacturer: QEMU' in output: grains['virtual'] = 'kvm' if 'Vendor: Bochs' in output: grains['virtual'] = 'kvm' if 'Manufacturer: Bochs' in output: grains['virtual'] = 'kvm' if 'BHYVE' in output: grains['virtual'] = 'bhyve' # Product Name: (oVirt) www.ovirt.org # Red Hat Community virtualization Project based on kvm elif 'Manufacturer: oVirt' in output: grains['virtual'] = 'kvm' grains['virtual_subtype'] = 'ovirt' # Red Hat Enterprise Virtualization elif 'Product Name: RHEV Hypervisor' in output: grains['virtual'] = 'kvm' grains['virtual_subtype'] = 'rhev' elif 'VirtualBox' in output: grains['virtual'] = 'VirtualBox' # Product Name: VMware Virtual Platform elif 'VMware' in output: grains['virtual'] = 'VMware' # Manufacturer: Microsoft Corporation # Product Name: Virtual Machine elif ': Microsoft' in output and 'Virtual Machine' in output: grains['virtual'] = 'VirtualPC' # Manufacturer: Parallels Software International Inc. elif 'Parallels Software' in output: grains['virtual'] = 'Parallels' elif 'Manufacturer: Google' in output: grains['virtual'] = 'kvm' # Proxmox KVM elif 'Vendor: SeaBIOS' in output: grains['virtual'] = 'kvm' # Break out of the loop, lspci parsing is not necessary break elif command == 'lspci': # dmidecode not available or the user does not have the necessary # permissions model = output.lower() if 'vmware' in model: grains['virtual'] = 'VMware' # 00:04.0 System peripheral: InnoTek Systemberatung GmbH # VirtualBox Guest Service elif 'virtualbox' in model: grains['virtual'] = 'VirtualBox' elif 'qemu' in model: grains['virtual'] = 'kvm' elif 'virtio' in model: grains['virtual'] = 'kvm' # Break out of the loop so the next log message is not issued break elif command == 'prtdiag': model = output.lower().split("\n")[0] if 'vmware' in model: grains['virtual'] = 'VMware' elif 'virtualbox' in model: grains['virtual'] = 'VirtualBox' elif 'qemu' in model: grains['virtual'] = 'kvm' elif 'joyent smartdc hvm' in model: grains['virtual'] = 'kvm' break elif command == 'virtinfo': grains['virtual'] = 'LDOM' break choices = ('Linux', 'HP-UX') isdir = os.path.isdir sysctl = salt.utils.path.which('sysctl') if osdata['kernel'] in choices: if os.path.isdir('/proc'): try: self_root = os.stat('/') init_root = os.stat('/proc/1/root/.') if self_root != init_root: grains['virtual_subtype'] = 'chroot' except (IOError, OSError): pass if isdir('/proc/vz'): if os.path.isfile('/proc/vz/version'): grains['virtual'] = 'openvzhn' elif os.path.isfile('/proc/vz/veinfo'): grains['virtual'] = 'openvzve' # a posteriori, it's expected for these to have failed: failed_commands.discard('lspci') failed_commands.discard('dmidecode') # Provide additional detection for OpenVZ if os.path.isfile('/proc/self/status'): with salt.utils.files.fopen('/proc/self/status') as status_file: vz_re = re.compile(r'^envID:\s+(\d+)$') for line in status_file: vz_match = vz_re.match(line.rstrip('\n')) if vz_match and int(vz_match.groups()[0]) != 0: grains['virtual'] = 'openvzve' elif vz_match and int(vz_match.groups()[0]) == 0: grains['virtual'] = 'openvzhn' if isdir('/proc/sys/xen') or \ isdir('/sys/bus/xen') or isdir('/proc/xen'): if os.path.isfile('/proc/xen/xsd_kva'): # Tested on CentOS 5.3 / 2.6.18-194.26.1.el5xen # Tested on CentOS 5.4 / 2.6.18-164.15.1.el5xen grains['virtual_subtype'] = 'Xen Dom0' else: if osdata.get('productname', '') == 'HVM domU': # Requires dmidecode! grains['virtual_subtype'] = 'Xen HVM DomU' elif os.path.isfile('/proc/xen/capabilities') and \ os.access('/proc/xen/capabilities', os.R_OK): with salt.utils.files.fopen('/proc/xen/capabilities') as fhr: if 'control_d' not in fhr.read(): # Tested on CentOS 5.5 / 2.6.18-194.3.1.el5xen grains['virtual_subtype'] = 'Xen PV DomU' else: # Shouldn't get to this, but just in case grains['virtual_subtype'] = 'Xen Dom0' # Tested on Fedora 10 / 2.6.27.30-170.2.82 with xen # Tested on Fedora 15 / 2.6.41.4-1 without running xen elif isdir('/sys/bus/xen'): if 'xen:' in __salt__['cmd.run']('dmesg').lower(): grains['virtual_subtype'] = 'Xen PV DomU' elif os.path.isfile('/sys/bus/xen/drivers/xenconsole'): # An actual DomU will have the xenconsole driver grains['virtual_subtype'] = 'Xen PV DomU' # If a Dom0 or DomU was detected, obviously this is xen if 'dom' in grains.get('virtual_subtype', '').lower(): grains['virtual'] = 'xen' # Check container type after hypervisors, to avoid variable overwrite on containers running in virtual environment. if os.path.isfile('/proc/1/cgroup'): try: with salt.utils.files.fopen('/proc/1/cgroup', 'r') as fhr: fhr_contents = fhr.read() if ':/lxc/' in fhr_contents: grains['virtual_subtype'] = 'LXC' elif ':/kubepods/' in fhr_contents: grains['virtual_subtype'] = 'kubernetes' elif ':/libpod_parent/' in fhr_contents: grains['virtual_subtype'] = 'libpod' else: if any(x in fhr_contents for x in (':/system.slice/docker', ':/docker/', ':/docker-ce/')): grains['virtual_subtype'] = 'Docker' except IOError: pass if os.path.isfile('/proc/cpuinfo'): with salt.utils.files.fopen('/proc/cpuinfo', 'r') as fhr: if 'QEMU Virtual CPU' in fhr.read(): grains['virtual'] = 'kvm' if os.path.isfile('/sys/devices/virtual/dmi/id/product_name'): try: with salt.utils.files.fopen('/sys/devices/virtual/dmi/id/product_name', 'r') as fhr: output = salt.utils.stringutils.to_unicode(fhr.read(), errors='replace') if 'VirtualBox' in output: grains['virtual'] = 'VirtualBox' elif 'RHEV Hypervisor' in output: grains['virtual'] = 'kvm' grains['virtual_subtype'] = 'rhev' elif 'oVirt Node' in output: grains['virtual'] = 'kvm' grains['virtual_subtype'] = 'ovirt' elif 'Google' in output: grains['virtual'] = 'gce' elif 'BHYVE' in output: grains['virtual'] = 'bhyve' except IOError: pass elif osdata['kernel'] == 'FreeBSD': kenv = salt.utils.path.which('kenv') if kenv: product = __salt__['cmd.run']( '{0} smbios.system.product'.format(kenv) ) maker = __salt__['cmd.run']( '{0} smbios.system.maker'.format(kenv) ) if product.startswith('VMware'): grains['virtual'] = 'VMware' if product.startswith('VirtualBox'): grains['virtual'] = 'VirtualBox' if maker.startswith('Xen'): grains['virtual_subtype'] = '{0} {1}'.format(maker, product) grains['virtual'] = 'xen' if maker.startswith('Microsoft') and product.startswith('Virtual'): grains['virtual'] = 'VirtualPC' if maker.startswith('OpenStack'): grains['virtual'] = 'OpenStack' if maker.startswith('Bochs'): grains['virtual'] = 'kvm' if sysctl: hv_vendor = __salt__['cmd.run']('{0} hw.hv_vendor'.format(sysctl)) model = __salt__['cmd.run']('{0} hw.model'.format(sysctl)) jail = __salt__['cmd.run']( '{0} -n security.jail.jailed'.format(sysctl) ) if 'bhyve' in hv_vendor: grains['virtual'] = 'bhyve' if jail == '1': grains['virtual_subtype'] = 'jail' if 'QEMU Virtual CPU' in model: grains['virtual'] = 'kvm' elif osdata['kernel'] == 'OpenBSD': if 'manufacturer' in osdata: if osdata['manufacturer'] in ['QEMU', 'Red Hat', 'Joyent']: grains['virtual'] = 'kvm' if osdata['manufacturer'] == 'OpenBSD': grains['virtual'] = 'vmm' elif osdata['kernel'] == 'SunOS': if grains['virtual'] == 'LDOM': roles = [] for role in ('control', 'io', 'root', 'service'): subtype_cmd = '{0} -c current get -H -o value {1}-role'.format(cmd, role) ret = __salt__['cmd.run_all']('{0}'.format(subtype_cmd)) if ret['stdout'] == 'true': roles.append(role) if roles: grains['virtual_subtype'] = roles else: # Check if it's a "regular" zone. (i.e. Solaris 10/11 zone) zonename = salt.utils.path.which('zonename') if zonename: zone = __salt__['cmd.run']('{0}'.format(zonename)) if zone != 'global': grains['virtual'] = 'zone' # Check if it's a branded zone (i.e. Solaris 8/9 zone) if isdir('/.SUNWnative'): grains['virtual'] = 'zone' elif osdata['kernel'] == 'NetBSD': if sysctl: if 'QEMU Virtual CPU' in __salt__['cmd.run']( '{0} -n machdep.cpu_brand'.format(sysctl)): grains['virtual'] = 'kvm' elif 'invalid' not in __salt__['cmd.run']( '{0} -n machdep.xen.suspend'.format(sysctl)): grains['virtual'] = 'Xen PV DomU' elif 'VMware' in __salt__['cmd.run']( '{0} -n machdep.dmi.system-vendor'.format(sysctl)): grains['virtual'] = 'VMware' # NetBSD has Xen dom0 support elif __salt__['cmd.run']( '{0} -n machdep.idle-mechanism'.format(sysctl)) == 'xen': if os.path.isfile('/var/run/xenconsoled.pid'): grains['virtual_subtype'] = 'Xen Dom0' for command in failed_commands: log.info( "Although '%s' was found in path, the current user " 'cannot execute it. Grains output might not be ' 'accurate.', command ) return grains def _virtual_hv(osdata): ''' Returns detailed hypervisor information from sysfs Currently this seems to be used only by Xen ''' grains = {} # Bail early if we're not running on Xen try: if 'xen' not in osdata['virtual']: return grains except KeyError: return grains # Try to get the exact hypervisor version from sysfs try: version = {} for fn in ('major', 'minor', 'extra'): with salt.utils.files.fopen('/sys/hypervisor/version/{}'.format(fn), 'r') as fhr: version[fn] = salt.utils.stringutils.to_unicode(fhr.read().strip()) grains['virtual_hv_version'] = '{}.{}{}'.format(version['major'], version['minor'], version['extra']) grains['virtual_hv_version_info'] = [version['major'], version['minor'], version['extra']] except (IOError, OSError, KeyError): pass # Try to read and decode the supported feature set of the hypervisor # Based on https://github.com/brendangregg/Misc/blob/master/xen/xen-features.py # Table data from include/xen/interface/features.h xen_feature_table = {0: 'writable_page_tables', 1: 'writable_descriptor_tables', 2: 'auto_translated_physmap', 3: 'supervisor_mode_kernel', 4: 'pae_pgdir_above_4gb', 5: 'mmu_pt_update_preserve_ad', 7: 'gnttab_map_avail_bits', 8: 'hvm_callback_vector', 9: 'hvm_safe_pvclock', 10: 'hvm_pirqs', 11: 'dom0', 12: 'grant_map_identity', 13: 'memory_op_vnode_supported', 14: 'ARM_SMCCC_supported'} try: with salt.utils.files.fopen('/sys/hypervisor/properties/features', 'r') as fhr: features = salt.utils.stringutils.to_unicode(fhr.read().strip()) enabled_features = [] for bit, feat in six.iteritems(xen_feature_table): if int(features, 16) & (1 << bit): enabled_features.append(feat) grains['virtual_hv_features'] = features grains['virtual_hv_features_list'] = enabled_features except (IOError, OSError, KeyError): pass return grains def _ps(osdata): ''' Return the ps grain ''' grains = {} bsd_choices = ('FreeBSD', 'NetBSD', 'OpenBSD', 'MacOS') if osdata['os'] in bsd_choices: grains['ps'] = 'ps auxwww' elif osdata['os_family'] == 'Solaris': grains['ps'] = '/usr/ucb/ps auxwww' elif osdata['os'] == 'Windows': grains['ps'] = 'tasklist.exe' elif osdata.get('virtual', '') == 'openvzhn': grains['ps'] = ( 'ps -fH -p $(grep -l \"^envID:[[:space:]]*0\\$\" ' '/proc/[0-9]*/status | sed -e \"s=/proc/\\([0-9]*\\)/.*=\\1=\") ' '| awk \'{ $7=\"\"; print }\'' ) elif osdata['os_family'] == 'AIX': grains['ps'] = '/usr/bin/ps auxww' elif osdata['os_family'] == 'NILinuxRT': grains['ps'] = 'ps -o user,pid,ppid,tty,time,comm' else: grains['ps'] = 'ps -efHww' return grains def _clean_value(key, val): ''' Clean out well-known bogus values. If it isn't clean (for example has value 'None'), return None. Otherwise, return the original value. NOTE: This logic also exists in the smbios module. This function is for use when not using smbios to retrieve the value. ''' if (val is None or not val or re.match('none', val, flags=re.IGNORECASE)): return None elif 'uuid' in key: # Try each version (1-5) of RFC4122 to check if it's actually a UUID for uuidver in range(1, 5): try: uuid.UUID(val, version=uuidver) return val except ValueError: continue log.trace('HW %s value %s is an invalid UUID', key, val.replace('\n', ' ')) return None elif re.search('serial|part|version', key): # 'To be filled by O.E.M. # 'Not applicable' etc. # 'Not specified' etc. # 0000000, 1234567 etc. # begone! if (re.match(r'^[0]+$', val) or re.match(r'[0]?1234567[8]?[9]?[0]?', val) or re.search(r'sernum|part[_-]?number|specified|filled|applicable', val, flags=re.IGNORECASE)): return None elif re.search('asset|manufacturer', key): # AssetTag0. Manufacturer04. Begone. if re.search(r'manufacturer|to be filled|available|asset|^no(ne|t)', val, flags=re.IGNORECASE): return None else: # map unspecified, undefined, unknown & whatever to None if (re.search(r'to be filled', val, flags=re.IGNORECASE) or re.search(r'un(known|specified)|no(t|ne)? (asset|provided|defined|available|present|specified)', val, flags=re.IGNORECASE)): return None return val def _windows_platform_data(): ''' Use the platform module for as much as we can. ''' # Provides: # kernelrelease # kernelversion # osversion # osrelease # osservicepack # osmanufacturer # manufacturer # productname # biosversion # serialnumber # osfullname # timezone # windowsdomain # windowsdomaintype # motherboard.productname # motherboard.serialnumber # virtual if not HAS_WMI: return {} with salt.utils.winapi.Com(): wmi_c = wmi.WMI() # http://msdn.microsoft.com/en-us/library/windows/desktop/aa394102%28v=vs.85%29.aspx systeminfo = wmi_c.Win32_ComputerSystem()[0] # https://msdn.microsoft.com/en-us/library/aa394239(v=vs.85).aspx osinfo = wmi_c.Win32_OperatingSystem()[0] # http://msdn.microsoft.com/en-us/library/windows/desktop/aa394077(v=vs.85).aspx biosinfo = wmi_c.Win32_BIOS()[0] # http://msdn.microsoft.com/en-us/library/windows/desktop/aa394498(v=vs.85).aspx timeinfo = wmi_c.Win32_TimeZone()[0] # http://msdn.microsoft.com/en-us/library/windows/desktop/aa394072(v=vs.85).aspx motherboard = {'product': None, 'serial': None} try: motherboardinfo = wmi_c.Win32_BaseBoard()[0] motherboard['product'] = motherboardinfo.Product motherboard['serial'] = motherboardinfo.SerialNumber except IndexError: log.debug('Motherboard info not available on this system') os_release = platform.release() kernel_version = platform.version() info = salt.utils.win_osinfo.get_os_version_info() net_info = salt.utils.win_osinfo.get_join_info() service_pack = None if info['ServicePackMajor'] > 0: service_pack = ''.join(['SP', six.text_type(info['ServicePackMajor'])]) # This creates the osrelease grain based on the Windows Operating # System Product Name. As long as Microsoft maintains a similar format # this should be future proof version = 'Unknown' release = '' if 'Server' in osinfo.Caption: for item in osinfo.Caption.split(' '): # If it's all digits, then it's version if re.match(r'\d+', item): version = item # If it starts with R and then numbers, it's the release # ie: R2 if re.match(r'^R\d+$', item): release = item os_release = '{0}Server{1}'.format(version, release) else: for item in osinfo.Caption.split(' '): # If it's a number, decimal number, Thin or Vista, then it's the # version if re.match(r'^(\d+(\.\d+)?)|Thin|Vista$', item): version = item os_release = version grains = { 'kernelrelease': _clean_value('kernelrelease', osinfo.Version), 'kernelversion': _clean_value('kernelversion', kernel_version), 'osversion': _clean_value('osversion', osinfo.Version), 'osrelease': _clean_value('osrelease', os_release), 'osservicepack': _clean_value('osservicepack', service_pack), 'osmanufacturer': _clean_value('osmanufacturer', osinfo.Manufacturer), 'manufacturer': _clean_value('manufacturer', systeminfo.Manufacturer), 'productname': _clean_value('productname', systeminfo.Model), # bios name had a bunch of whitespace appended to it in my testing # 'PhoenixBIOS 4.0 Release 6.0 ' 'biosversion': _clean_value('biosversion', biosinfo.Name.strip()), 'serialnumber': _clean_value('serialnumber', biosinfo.SerialNumber), 'osfullname': _clean_value('osfullname', osinfo.Caption), 'timezone': _clean_value('timezone', timeinfo.Description), 'windowsdomain': _clean_value('windowsdomain', net_info['Domain']), 'windowsdomaintype': _clean_value('windowsdomaintype', net_info['DomainType']), 'motherboard': { 'productname': _clean_value('motherboard.productname', motherboard['product']), 'serialnumber': _clean_value('motherboard.serialnumber', motherboard['serial']), } } # test for virtualized environments # I only had VMware available so the rest are unvalidated if 'VRTUAL' in biosinfo.Version: # (not a typo) grains['virtual'] = 'HyperV' elif 'A M I' in biosinfo.Version: grains['virtual'] = 'VirtualPC' elif 'VMware' in systeminfo.Model: grains['virtual'] = 'VMware' elif 'VirtualBox' in systeminfo.Model: grains['virtual'] = 'VirtualBox' elif 'Xen' in biosinfo.Version: grains['virtual'] = 'Xen' if 'HVM domU' in systeminfo.Model: grains['virtual_subtype'] = 'HVM domU' elif 'OpenStack' in systeminfo.Model: grains['virtual'] = 'OpenStack' return grains def _osx_platform_data(): ''' Additional data for macOS systems Returns: A dictionary containing values for the following: - model_name - boot_rom_version - smc_version - system_serialnumber ''' cmd = 'system_profiler SPHardwareDataType' hardware = __salt__['cmd.run'](cmd) grains = {} for line in hardware.splitlines(): field_name, _, field_val = line.partition(': ') if field_name.strip() == "Model Name": key = 'model_name' grains[key] = _clean_value(key, field_val) if field_name.strip() == "Boot ROM Version": key = 'boot_rom_version' grains[key] = _clean_value(key, field_val) if field_name.strip() == "SMC Version (system)": key = 'smc_version' grains[key] = _clean_value(key, field_val) if field_name.strip() == "Serial Number (system)": key = 'system_serialnumber' grains[key] = _clean_value(key, field_val) return grains def id_(): ''' Return the id ''' return {'id': __opts__.get('id', '')} _REPLACE_LINUX_RE = re.compile(r'\W(?:gnu/)?linux', re.IGNORECASE) # This maps (at most) the first ten characters (no spaces, lowercased) of # 'osfullname' to the 'os' grain that Salt traditionally uses. # Please see os_data() and _supported_dists. # If your system is not detecting properly it likely needs an entry here. _OS_NAME_MAP = { 'redhatente': 'RedHat', 'gentoobase': 'Gentoo', 'archarm': 'Arch ARM', 'arch': 'Arch', 'debian': 'Debian', 'raspbian': 'Raspbian', 'fedoraremi': 'Fedora', 'chapeau': 'Chapeau', 'korora': 'Korora', 'amazonami': 'Amazon', 'alt': 'ALT', 'enterprise': 'OEL', 'oracleserv': 'OEL', 'cloudserve': 'CloudLinux', 'cloudlinux': 'CloudLinux', 'pidora': 'Fedora', 'scientific': 'ScientificLinux', 'synology': 'Synology', 'nilrt': 'NILinuxRT', 'poky': 'Poky', 'manjaro': 'Manjaro', 'manjarolin': 'Manjaro', 'univention': 'Univention', 'antergos': 'Antergos', 'sles': 'SUSE', 'void': 'Void', 'slesexpand': 'RES', 'linuxmint': 'Mint', 'neon': 'KDE neon', } # Map the 'os' grain to the 'os_family' grain # These should always be capitalized entries as the lookup comes # post-_OS_NAME_MAP. If your system is having trouble with detection, please # make sure that the 'os' grain is capitalized and working correctly first. _OS_FAMILY_MAP = { 'Ubuntu': 'Debian', 'Fedora': 'RedHat', 'Chapeau': 'RedHat', 'Korora': 'RedHat', 'FedBerry': 'RedHat', 'CentOS': 'RedHat', 'GoOSe': 'RedHat', 'Scientific': 'RedHat', 'Amazon': 'RedHat', 'CloudLinux': 'RedHat', 'OVS': 'RedHat', 'OEL': 'RedHat', 'XCP': 'RedHat', 'XCP-ng': 'RedHat', 'XenServer': 'RedHat', 'RES': 'RedHat', 'Sangoma': 'RedHat', 'Mandrake': 'Mandriva', 'ESXi': 'VMware', 'Mint': 'Debian', 'VMwareESX': 'VMware', 'Bluewhite64': 'Bluewhite', 'Slamd64': 'Slackware', 'SLES': 'Suse', 'SUSE Enterprise Server': 'Suse', 'SUSE Enterprise Server': 'Suse', 'SLED': 'Suse', 'openSUSE': 'Suse', 'SUSE': 'Suse', 'openSUSE Leap': 'Suse', 'openSUSE Tumbleweed': 'Suse', 'SLES_SAP': 'Suse', 'Solaris': 'Solaris', 'SmartOS': 'Solaris', 'OmniOS': 'Solaris', 'OpenIndiana Development': 'Solaris', 'OpenIndiana': 'Solaris', 'OpenSolaris Development': 'Solaris', 'OpenSolaris': 'Solaris', 'Oracle Solaris': 'Solaris', 'Arch ARM': 'Arch', 'Manjaro': 'Arch', 'Antergos': 'Arch', 'ALT': 'RedHat', 'Trisquel': 'Debian', 'GCEL': 'Debian', 'Linaro': 'Debian', 'elementary OS': 'Debian', 'elementary': 'Debian', 'Univention': 'Debian', 'ScientificLinux': 'RedHat', 'Raspbian': 'Debian', 'Devuan': 'Debian', 'antiX': 'Debian', 'Kali': 'Debian', 'neon': 'Debian', 'Cumulus': 'Debian', 'Deepin': 'Debian', 'NILinuxRT': 'NILinuxRT', 'KDE neon': 'Debian', 'Void': 'Void', 'IDMS': 'Debian', 'Funtoo': 'Gentoo', 'AIX': 'AIX', 'TurnKey': 'Debian', } # Matches any possible format: # DISTRIB_ID="Ubuntu" # DISTRIB_ID='Mageia' # DISTRIB_ID=Fedora # DISTRIB_RELEASE='10.10' # DISTRIB_CODENAME='squeeze' # DISTRIB_DESCRIPTION='Ubuntu 10.10' _LSB_REGEX = re.compile(( '^(DISTRIB_(?:ID|RELEASE|CODENAME|DESCRIPTION))=(?:\'|")?' '([\\w\\s\\.\\-_]+)(?:\'|")?' )) def _linux_bin_exists(binary): ''' Does a binary exist in linux (depends on which, type, or whereis) ''' for search_cmd in ('which', 'type -ap'): try: return __salt__['cmd.retcode']( '{0} {1}'.format(search_cmd, binary) ) == 0 except salt.exceptions.CommandExecutionError: pass try: return len(__salt__['cmd.run_all']( 'whereis -b {0}'.format(binary) )['stdout'].split()) > 1 except salt.exceptions.CommandExecutionError: return False def _get_interfaces(): ''' Provide a dict of the connected interfaces and their ip addresses ''' global _INTERFACES if not _INTERFACES: _INTERFACES = salt.utils.network.interfaces() return _INTERFACES def _parse_lsb_release(): ret = {} try: log.trace('Attempting to parse /etc/lsb-release') with salt.utils.files.fopen('/etc/lsb-release') as ifile: for line in ifile: try: key, value = _LSB_REGEX.match(line.rstrip('\n')).groups()[:2] except AttributeError: pass else: # Adds lsb_distrib_{id,release,codename,description} ret['lsb_{0}'.format(key.lower())] = value.rstrip() except (IOError, OSError) as exc: log.trace('Failed to parse /etc/lsb-release: %s', exc) return ret def _parse_os_release(*os_release_files): ''' Parse os-release and return a parameter dictionary See http://www.freedesktop.org/software/systemd/man/os-release.html for specification of the file format. ''' ret = {} for filename in os_release_files: try: with salt.utils.files.fopen(filename) as ifile: regex = re.compile('^([\\w]+)=(?:\'|")?(.*?)(?:\'|")?$') for line in ifile: match = regex.match(line.strip()) if match: # Shell special characters ("$", quotes, backslash, # backtick) are escaped with backslashes ret[match.group(1)] = re.sub( r'\\([$"\'\\`])', r'\1', match.group(2) ) break except (IOError, OSError): pass return ret def _parse_cpe_name(cpe): ''' Parse CPE_NAME data from the os-release Info: https://csrc.nist.gov/projects/security-content-automation-protocol/scap-specifications/cpe :param cpe: :return: ''' part = { 'o': 'operating system', 'h': 'hardware', 'a': 'application', } ret = {} cpe = (cpe or '').split(':') if len(cpe) > 4 and cpe[0] == 'cpe': if cpe[1].startswith('/'): # WFN to URI ret['vendor'], ret['product'], ret['version'] = cpe[2:5] ret['phase'] = cpe[5] if len(cpe) > 5 else None ret['part'] = part.get(cpe[1][1:]) elif len(cpe) == 13 and cpe[1] == '2.3': # WFN to a string ret['vendor'], ret['product'], ret['version'], ret['phase'] = [x if x != '*' else None for x in cpe[3:7]] ret['part'] = part.get(cpe[2]) return ret def os_data(): ''' Return grains pertaining to the operating system ''' grains = { 'num_gpus': 0, 'gpus': [], } # Windows Server 2008 64-bit # ('Windows', 'MINIONNAME', '2008ServerR2', '6.1.7601', 'AMD64', # 'Intel64 Fam ily 6 Model 23 Stepping 6, GenuineIntel') # Ubuntu 10.04 # ('Linux', 'MINIONNAME', '2.6.32-38-server', # '#83-Ubuntu SMP Wed Jan 4 11:26:59 UTC 2012', 'x86_64', '') # pylint: disable=unpacking-non-sequence (grains['kernel'], grains['nodename'], grains['kernelrelease'], grains['kernelversion'], grains['cpuarch'], _) = platform.uname() # pylint: enable=unpacking-non-sequence if salt.utils.platform.is_proxy(): grains['kernel'] = 'proxy' grains['kernelrelease'] = 'proxy' grains['kernelversion'] = 'proxy' grains['osrelease'] = 'proxy' grains['os'] = 'proxy' grains['os_family'] = 'proxy' grains['osfullname'] = 'proxy' elif salt.utils.platform.is_windows(): grains['os'] = 'Windows' grains['os_family'] = 'Windows' grains.update(_memdata(grains)) grains.update(_windows_platform_data()) grains.update(_windows_cpudata()) grains.update(_windows_virtual(grains)) grains.update(_ps(grains)) if 'Server' in grains['osrelease']: osrelease_info = grains['osrelease'].split('Server', 1) osrelease_info[1] = osrelease_info[1].lstrip('R') else: osrelease_info = grains['osrelease'].split('.') for idx, value in enumerate(osrelease_info): if not value.isdigit(): continue osrelease_info[idx] = int(value) grains['osrelease_info'] = tuple(osrelease_info) grains['osfinger'] = '{os}-{ver}'.format( os=grains['os'], ver=grains['osrelease']) grains['init'] = 'Windows' return grains elif salt.utils.platform.is_linux(): # Add SELinux grain, if you have it if _linux_bin_exists('selinuxenabled'): log.trace('Adding selinux grains') grains['selinux'] = {} grains['selinux']['enabled'] = __salt__['cmd.retcode']( 'selinuxenabled' ) == 0 if _linux_bin_exists('getenforce'): grains['selinux']['enforced'] = __salt__['cmd.run']( 'getenforce' ).strip() # Add systemd grain, if you have it if _linux_bin_exists('systemctl') and _linux_bin_exists('localectl'): log.trace('Adding systemd grains') grains['systemd'] = {} systemd_info = __salt__['cmd.run']( 'systemctl --version' ).splitlines() grains['systemd']['version'] = systemd_info[0].split()[1] grains['systemd']['features'] = systemd_info[1] # Add init grain grains['init'] = 'unknown' log.trace('Adding init grain') try: os.stat('/run/systemd/system') grains['init'] = 'systemd' except (OSError, IOError): try: with salt.utils.files.fopen('/proc/1/cmdline') as fhr: init_cmdline = fhr.read().replace('\x00', ' ').split() except (IOError, OSError): pass else: try: init_bin = salt.utils.path.which(init_cmdline[0]) except IndexError: # Emtpy init_cmdline init_bin = None log.warning('Unable to fetch data from /proc/1/cmdline') if init_bin is not None and init_bin.endswith('bin/init'): supported_inits = (b'upstart', b'sysvinit', b'systemd') edge_len = max(len(x) for x in supported_inits) - 1 try: buf_size = __opts__['file_buffer_size'] except KeyError: # Default to the value of file_buffer_size for the minion buf_size = 262144 try: with salt.utils.files.fopen(init_bin, 'rb') as fp_: edge = b'' buf = fp_.read(buf_size).lower() while buf: buf = edge + buf for item in supported_inits: if item in buf: if six.PY3: item = item.decode('utf-8') grains['init'] = item buf = b'' break edge = buf[-edge_len:] buf = fp_.read(buf_size).lower() except (IOError, OSError) as exc: log.error( 'Unable to read from init_bin (%s): %s', init_bin, exc ) elif salt.utils.path.which('supervisord') in init_cmdline: grains['init'] = 'supervisord' elif salt.utils.path.which('dumb-init') in init_cmdline: # https://github.com/Yelp/dumb-init grains['init'] = 'dumb-init' elif salt.utils.path.which('tini') in init_cmdline: # https://github.com/krallin/tini grains['init'] = 'tini' elif init_cmdline == ['runit']: grains['init'] = 'runit' elif '/sbin/my_init' in init_cmdline: # Phusion Base docker container use runit for srv mgmt, but # my_init as pid1 grains['init'] = 'runit' else: log.debug( 'Could not determine init system from command line: (%s)', ' '.join(init_cmdline) ) # Add lsb grains on any distro with lsb-release. Note that this import # can fail on systems with lsb-release installed if the system package # does not install the python package for the python interpreter used by # Salt (i.e. python2 or python3) try: log.trace('Getting lsb_release distro information') import lsb_release # pylint: disable=import-error release = lsb_release.get_distro_information() for key, value in six.iteritems(release): key = key.lower() lsb_param = 'lsb_{0}{1}'.format( '' if key.startswith('distrib_') else 'distrib_', key ) grains[lsb_param] = value # Catch a NameError to workaround possible breakage in lsb_release # See https://github.com/saltstack/salt/issues/37867 except (ImportError, NameError): # if the python library isn't available, try to parse # /etc/lsb-release using regex log.trace('lsb_release python bindings not available') grains.update(_parse_lsb_release()) if grains.get('lsb_distrib_description', '').lower().startswith('antergos'): # Antergos incorrectly configures their /etc/lsb-release, # setting the DISTRIB_ID to "Arch". This causes the "os" grain # to be incorrectly set to "Arch". grains['osfullname'] = 'Antergos Linux' elif 'lsb_distrib_id' not in grains: log.trace( 'Failed to get lsb_distrib_id, trying to parse os-release' ) os_release = _parse_os_release('/etc/os-release', '/usr/lib/os-release') if os_release: if 'NAME' in os_release: grains['lsb_distrib_id'] = os_release['NAME'].strip() if 'VERSION_ID' in os_release: grains['lsb_distrib_release'] = os_release['VERSION_ID'] if 'VERSION_CODENAME' in os_release: grains['lsb_distrib_codename'] = os_release['VERSION_CODENAME'] elif 'PRETTY_NAME' in os_release: codename = os_release['PRETTY_NAME'] # https://github.com/saltstack/salt/issues/44108 if os_release['ID'] == 'debian': codename_match = re.search(r'\((\w+)\)$', codename) if codename_match: codename = codename_match.group(1) grains['lsb_distrib_codename'] = codename if 'CPE_NAME' in os_release: cpe = _parse_cpe_name(os_release['CPE_NAME']) if not cpe: log.error('Broken CPE_NAME format in /etc/os-release!') elif cpe.get('vendor', '').lower() in ['suse', 'opensuse']: grains['os'] = "SUSE" # openSUSE `osfullname` grain normalization if os_release.get("NAME") == "openSUSE Leap": grains['osfullname'] = "Leap" elif os_release.get("VERSION") == "Tumbleweed": grains['osfullname'] = os_release["VERSION"] # Override VERSION_ID, if CPE_NAME around if cpe.get('version') and cpe.get('vendor') == 'opensuse': # Keep VERSION_ID for SLES grains['lsb_distrib_release'] = cpe['version'] elif os.path.isfile('/etc/SuSE-release'): log.trace('Parsing distrib info from /etc/SuSE-release') grains['lsb_distrib_id'] = 'SUSE' version = '' patch = '' with salt.utils.files.fopen('/etc/SuSE-release') as fhr: for line in fhr: if 'enterprise' in line.lower(): grains['lsb_distrib_id'] = 'SLES' grains['lsb_distrib_codename'] = re.sub(r'\(.+\)', '', line).strip() elif 'version' in line.lower(): version = re.sub(r'[^0-9]', '', line) elif 'patchlevel' in line.lower(): patch = re.sub(r'[^0-9]', '', line) grains['lsb_distrib_release'] = version if patch: grains['lsb_distrib_release'] += '.' + patch patchstr = 'SP' + patch if grains['lsb_distrib_codename'] and patchstr not in grains['lsb_distrib_codename']: grains['lsb_distrib_codename'] += ' ' + patchstr if not grains.get('lsb_distrib_codename'): grains['lsb_distrib_codename'] = 'n.a' elif os.path.isfile('/etc/altlinux-release'): log.trace('Parsing distrib info from /etc/altlinux-release') # ALT Linux grains['lsb_distrib_id'] = 'altlinux' with salt.utils.files.fopen('/etc/altlinux-release') as ifile: # This file is symlinked to from: # /etc/fedora-release # /etc/redhat-release # /etc/system-release for line in ifile: # ALT Linux Sisyphus (unstable) comps = line.split() if comps[0] == 'ALT': grains['lsb_distrib_release'] = comps[2] grains['lsb_distrib_codename'] = \ comps[3].replace('(', '').replace(')', '') elif os.path.isfile('/etc/centos-release'): log.trace('Parsing distrib info from /etc/centos-release') # Maybe CentOS Linux; could also be SUSE Expanded Support. # SUSE ES has both, centos-release and redhat-release. if os.path.isfile('/etc/redhat-release'): with salt.utils.files.fopen('/etc/redhat-release') as ifile: for line in ifile: if "red hat enterprise linux server" in line.lower(): # This is a SUSE Expanded Support Rhel installation grains['lsb_distrib_id'] = 'RedHat' break grains.setdefault('lsb_distrib_id', 'CentOS') with salt.utils.files.fopen('/etc/centos-release') as ifile: for line in ifile: # Need to pull out the version and codename # in the case of custom content in /etc/centos-release find_release = re.compile(r'\d+\.\d+') find_codename = re.compile(r'(?<=\()(.*?)(?=\))') release = find_release.search(line) codename = find_codename.search(line) if release is not None: grains['lsb_distrib_release'] = release.group() if codename is not None: grains['lsb_distrib_codename'] = codename.group() elif os.path.isfile('/etc.defaults/VERSION') \ and os.path.isfile('/etc.defaults/synoinfo.conf'): grains['osfullname'] = 'Synology' log.trace( 'Parsing Synology distrib info from /etc/.defaults/VERSION' ) with salt.utils.files.fopen('/etc.defaults/VERSION', 'r') as fp_: synoinfo = {} for line in fp_: try: key, val = line.rstrip('\n').split('=') except ValueError: continue if key in ('majorversion', 'minorversion', 'buildnumber'): synoinfo[key] = val.strip('"') if len(synoinfo) != 3: log.warning( 'Unable to determine Synology version info. ' 'Please report this, as it is likely a bug.' ) else: grains['osrelease'] = ( '{majorversion}.{minorversion}-{buildnumber}' .format(**synoinfo) ) # Use the already intelligent platform module to get distro info # (though apparently it's not intelligent enough to strip quotes) log.trace( 'Getting OS name, release, and codename from ' 'distro.linux_distribution()' ) (osname, osrelease, oscodename) = \ [x.strip('"').strip("'") for x in linux_distribution(supported_dists=_supported_dists)] # Try to assign these three names based on the lsb info, they tend to # be more accurate than what python gets from /etc/DISTRO-release. # It's worth noting that Ubuntu has patched their Python distribution # so that linux_distribution() does the /etc/lsb-release parsing, but # we do it anyway here for the sake for full portability. if 'osfullname' not in grains: # If NI Linux RT distribution, set the grains['osfullname'] to 'nilrt' if grains.get('lsb_distrib_id', '').lower().startswith('nilrt'): grains['osfullname'] = 'nilrt' else: grains['osfullname'] = grains.get('lsb_distrib_id', osname).strip() if 'osrelease' not in grains: # NOTE: This is a workaround for CentOS 7 os-release bug # https://bugs.centos.org/view.php?id=8359 # /etc/os-release contains no minor distro release number so we fall back to parse # /etc/centos-release file instead. # Commit introducing this comment should be reverted after the upstream bug is released. if 'CentOS Linux 7' in grains.get('lsb_distrib_codename', ''): grains.pop('lsb_distrib_release', None) grains['osrelease'] = grains.get('lsb_distrib_release', osrelease).strip() grains['oscodename'] = grains.get('lsb_distrib_codename', '').strip() or oscodename if 'Red Hat' in grains['oscodename']: grains['oscodename'] = oscodename distroname = _REPLACE_LINUX_RE.sub('', grains['osfullname']).strip() # return the first ten characters with no spaces, lowercased shortname = distroname.replace(' ', '').lower()[:10] # this maps the long names from the /etc/DISTRO-release files to the # traditional short names that Salt has used. if 'os' not in grains: grains['os'] = _OS_NAME_MAP.get(shortname, distroname) grains.update(_linux_cpudata()) grains.update(_linux_gpu_data()) elif grains['kernel'] == 'SunOS': if salt.utils.platform.is_smartos(): # See https://github.com/joyent/smartos-live/issues/224 if HAS_UNAME: uname_v = os.uname()[3] # format: joyent_20161101T004406Z else: uname_v = os.name uname_v = uname_v[uname_v.index('_')+1:] grains['os'] = grains['osfullname'] = 'SmartOS' # store a parsed version of YYYY.MM.DD as osrelease grains['osrelease'] = ".".join([ uname_v.split('T')[0][0:4], uname_v.split('T')[0][4:6], uname_v.split('T')[0][6:8], ]) # store a untouched copy of the timestamp in osrelease_stamp grains['osrelease_stamp'] = uname_v elif os.path.isfile('/etc/release'): with salt.utils.files.fopen('/etc/release', 'r') as fp_: rel_data = fp_.read() try: release_re = re.compile( r'((?:Open|Oracle )?Solaris|OpenIndiana|OmniOS) (Development)?' r'\s*(\d+\.?\d*|v\d+)\s?[A-Z]*\s?(r\d+|\d+\/\d+|oi_\S+|snv_\S+)?' ) osname, development, osmajorrelease, osminorrelease = release_re.search(rel_data).groups() except AttributeError: # Set a blank osrelease grain and fallback to 'Solaris' # as the 'os' grain. grains['os'] = grains['osfullname'] = 'Solaris' grains['osrelease'] = '' else: if development is not None: osname = ' '.join((osname, development)) if HAS_UNAME: uname_v = os.uname()[3] else: uname_v = os.name grains['os'] = grains['osfullname'] = osname if osname in ['Oracle Solaris'] and uname_v.startswith(osmajorrelease): # Oracla Solars 11 and up have minor version in uname grains['osrelease'] = uname_v elif osname in ['OmniOS']: # OmniOS osrelease = [] osrelease.append(osmajorrelease[1:]) osrelease.append(osminorrelease[1:]) grains['osrelease'] = ".".join(osrelease) grains['osrelease_stamp'] = uname_v else: # Sun Solaris 10 and earlier/comparable osrelease = [] osrelease.append(osmajorrelease) if osminorrelease: osrelease.append(osminorrelease) grains['osrelease'] = ".".join(osrelease) grains['osrelease_stamp'] = uname_v grains.update(_sunos_cpudata()) elif grains['kernel'] == 'VMkernel': grains['os'] = 'ESXi' elif grains['kernel'] == 'Darwin': osrelease = __salt__['cmd.run']('sw_vers -productVersion') osname = __salt__['cmd.run']('sw_vers -productName') osbuild = __salt__['cmd.run']('sw_vers -buildVersion') grains['os'] = 'MacOS' grains['os_family'] = 'MacOS' grains['osfullname'] = "{0} {1}".format(osname, osrelease) grains['osrelease'] = osrelease grains['osbuild'] = osbuild grains['init'] = 'launchd' grains.update(_bsd_cpudata(grains)) grains.update(_osx_gpudata()) grains.update(_osx_platform_data()) elif grains['kernel'] == 'AIX': osrelease = __salt__['cmd.run']('oslevel') osrelease_techlevel = __salt__['cmd.run']('oslevel -r') osname = __salt__['cmd.run']('uname') grains['os'] = 'AIX' grains['osfullname'] = osname grains['osrelease'] = osrelease grains['osrelease_techlevel'] = osrelease_techlevel grains.update(_aix_cpudata()) else: grains['os'] = grains['kernel'] if grains['kernel'] == 'FreeBSD': try: grains['osrelease'] = __salt__['cmd.run']('freebsd-version -u').split('-')[0] except salt.exceptions.CommandExecutionError: # freebsd-version was introduced in 10.0. # derive osrelease from kernelversion prior to that grains['osrelease'] = grains['kernelrelease'].split('-')[0] grains.update(_bsd_cpudata(grains)) if grains['kernel'] in ('OpenBSD', 'NetBSD'): grains.update(_bsd_cpudata(grains)) grains['osrelease'] = grains['kernelrelease'].split('-')[0] if grains['kernel'] == 'NetBSD': grains.update(_netbsd_gpu_data()) if not grains['os']: grains['os'] = 'Unknown {0}'.format(grains['kernel']) grains['os_family'] = 'Unknown' else: # this assigns family names based on the os name # family defaults to the os name if not found grains['os_family'] = _OS_FAMILY_MAP.get(grains['os'], grains['os']) # Build the osarch grain. This grain will be used for platform-specific # considerations such as package management. Fall back to the CPU # architecture. if grains.get('os_family') == 'Debian': osarch = __salt__['cmd.run']('dpkg --print-architecture').strip() elif grains.get('os_family') in ['RedHat', 'Suse']: osarch = salt.utils.pkg.rpm.get_osarch() elif grains.get('os_family') in ('NILinuxRT', 'Poky'): archinfo = {} for line in __salt__['cmd.run']('opkg print-architecture').splitlines(): if line.startswith('arch'): _, arch, priority = line.split() archinfo[arch.strip()] = int(priority.strip()) # Return osarch in priority order (higher to lower) osarch = sorted(archinfo, key=archinfo.get, reverse=True) else: osarch = grains['cpuarch'] grains['osarch'] = osarch grains.update(_memdata(grains)) # Get the hardware and bios data grains.update(_hw_data(grains)) # Load the virtual machine info grains.update(_virtual(grains)) grains.update(_virtual_hv(grains)) grains.update(_ps(grains)) if grains.get('osrelease', ''): osrelease_info = grains['osrelease'].split('.') for idx, value in enumerate(osrelease_info): if not value.isdigit(): continue osrelease_info[idx] = int(value) grains['osrelease_info'] = tuple(osrelease_info) try: grains['osmajorrelease'] = int(grains['osrelease_info'][0]) except (IndexError, TypeError, ValueError): log.debug( 'Unable to derive osmajorrelease from osrelease_info \'%s\'. ' 'The osmajorrelease grain will not be set.', grains['osrelease_info'] ) os_name = grains['os' if grains.get('os') in ( 'Debian', 'FreeBSD', 'OpenBSD', 'NetBSD', 'Mac', 'Raspbian') else 'osfullname'] grains['osfinger'] = '{0}-{1}'.format( os_name, grains['osrelease'] if os_name in ('Ubuntu',) else grains['osrelease_info'][0]) return grains def locale_info(): ''' Provides defaultlanguage defaultencoding ''' grains = {} grains['locale_info'] = {} if salt.utils.platform.is_proxy(): return grains try: ( grains['locale_info']['defaultlanguage'], grains['locale_info']['defaultencoding'] ) = locale.getdefaultlocale() except Exception: # locale.getdefaultlocale can ValueError!! Catch anything else it # might do, per #2205 grains['locale_info']['defaultlanguage'] = 'unknown' grains['locale_info']['defaultencoding'] = 'unknown' grains['locale_info']['detectedencoding'] = __salt_system_encoding__ if _DATEUTIL_TZ: grains['locale_info']['timezone'] = datetime.datetime.now(dateutil.tz.tzlocal()).tzname() return grains def hostname(): ''' Return fqdn, hostname, domainname ''' # This is going to need some work # Provides: # fqdn # host # localhost # domain global __FQDN__ grains = {} if salt.utils.platform.is_proxy(): return grains grains['localhost'] = socket.gethostname() if __FQDN__ is None: __FQDN__ = salt.utils.network.get_fqhostname() # On some distros (notably FreeBSD) if there is no hostname set # salt.utils.network.get_fqhostname() will return None. # In this case we punt and log a message at error level, but force the # hostname and domain to be localhost.localdomain # Otherwise we would stacktrace below if __FQDN__ is None: # still! log.error('Having trouble getting a hostname. Does this machine have its hostname and domain set properly?') __FQDN__ = 'localhost.localdomain' grains['fqdn'] = __FQDN__ (grains['host'], grains['domain']) = grains['fqdn'].partition('.')[::2] return grains def append_domain(): ''' Return append_domain if set ''' grain = {} if salt.utils.platform.is_proxy(): return grain if 'append_domain' in __opts__: grain['append_domain'] = __opts__['append_domain'] return grain def fqdns(): ''' Return all known FQDNs for the system by enumerating all interfaces and then trying to reverse resolve them (excluding 'lo' interface). ''' # Provides: # fqdns grains = {} fqdns = set() addresses = salt.utils.network.ip_addrs(include_loopback=False, interface_data=_get_interfaces()) addresses.extend(salt.utils.network.ip_addrs6(include_loopback=False, interface_data=_get_interfaces())) err_message = 'Exception during resolving address: %s' for ip in addresses: try: name, aliaslist, addresslist = socket.gethostbyaddr(ip) fqdns.update([socket.getfqdn(name)] + [als for als in aliaslist if salt.utils.network.is_fqdn(als)]) except socket.herror as err: if err.errno == 0: # No FQDN for this IP address, so we don't need to know this all the time. log.debug("Unable to resolve address %s: %s", ip, err) else: log.error(err_message, err) except (socket.error, socket.gaierror, socket.timeout) as err: log.error(err_message, err) return {"fqdns": sorted(list(fqdns))} def ip_fqdn(): ''' Return ip address and FQDN grains ''' if salt.utils.platform.is_proxy(): return {} ret = {} ret['ipv4'] = salt.utils.network.ip_addrs(include_loopback=True) ret['ipv6'] = salt.utils.network.ip_addrs6(include_loopback=True) _fqdn = hostname()['fqdn'] for socket_type, ipv_num in ((socket.AF_INET, '4'), (socket.AF_INET6, '6')): key = 'fqdn_ip' + ipv_num if not ret['ipv' + ipv_num]: ret[key] = [] else: try: start_time = datetime.datetime.utcnow() info = socket.getaddrinfo(_fqdn, None, socket_type) ret[key] = list(set(item[4][0] for item in info)) except socket.error: timediff = datetime.datetime.utcnow() - start_time if timediff.seconds > 5 and __opts__['__role'] == 'master': log.warning( 'Unable to find IPv%s record for "%s" causing a %s ' 'second timeout when rendering grains. Set the dns or ' '/etc/hosts for IPv%s to clear this.', ipv_num, _fqdn, timediff, ipv_num ) ret[key] = [] return ret def ip_interfaces(): ''' Provide a dict of the connected interfaces and their ip addresses The addresses will be passed as a list for each interface ''' # Provides: # ip_interfaces if salt.utils.platform.is_proxy(): return {} ret = {} ifaces = _get_interfaces() for face in ifaces: iface_ips = [] for inet in ifaces[face].get('inet', []): if 'address' in inet: iface_ips.append(inet['address']) for inet in ifaces[face].get('inet6', []): if 'address' in inet: iface_ips.append(inet['address']) for secondary in ifaces[face].get('secondary', []): if 'address' in secondary: iface_ips.append(secondary['address']) ret[face] = iface_ips return {'ip_interfaces': ret} def ip4_interfaces(): ''' Provide a dict of the connected interfaces and their ip4 addresses The addresses will be passed as a list for each interface ''' # Provides: # ip_interfaces if salt.utils.platform.is_proxy(): return {} ret = {} ifaces = _get_interfaces() for face in ifaces: iface_ips = [] for inet in ifaces[face].get('inet', []): if 'address' in inet: iface_ips.append(inet['address']) for secondary in ifaces[face].get('secondary', []): if 'address' in secondary: iface_ips.append(secondary['address']) ret[face] = iface_ips return {'ip4_interfaces': ret} def ip6_interfaces(): ''' Provide a dict of the connected interfaces and their ip6 addresses The addresses will be passed as a list for each interface ''' # Provides: # ip_interfaces if salt.utils.platform.is_proxy(): return {} ret = {} ifaces = _get_interfaces() for face in ifaces: iface_ips = [] for inet in ifaces[face].get('inet6', []): if 'address' in inet: iface_ips.append(inet['address']) for secondary in ifaces[face].get('secondary', []): if 'address' in secondary: iface_ips.append(secondary['address']) ret[face] = iface_ips return {'ip6_interfaces': ret} def hwaddr_interfaces(): ''' Provide a dict of the connected interfaces and their hw addresses (Mac Address) ''' # Provides: # hwaddr_interfaces ret = {} ifaces = _get_interfaces() for face in ifaces: if 'hwaddr' in ifaces[face]: ret[face] = ifaces[face]['hwaddr'] return {'hwaddr_interfaces': ret} def dns(): ''' Parse the resolver configuration file .. versionadded:: 2016.3.0 ''' # Provides: # dns if salt.utils.platform.is_windows() or 'proxyminion' in __opts__: return {} resolv = salt.utils.dns.parse_resolv() for key in ('nameservers', 'ip4_nameservers', 'ip6_nameservers', 'sortlist'): if key in resolv: resolv[key] = [six.text_type(i) for i in resolv[key]] return {'dns': resolv} if resolv else {} def get_machine_id(): ''' Provide the machine-id for machine/virtualization combination ''' # Provides: # machine-id if platform.system() == 'AIX': return _aix_get_machine_id() locations = ['/etc/machine-id', '/var/lib/dbus/machine-id'] existing_locations = [loc for loc in locations if os.path.exists(loc)] if not existing_locations: return {} else: with salt.utils.files.fopen(existing_locations[0]) as machineid: return {'machine_id': machineid.read().strip()} def cwd(): ''' Current working directory ''' return {'cwd': os.getcwd()} def path(): ''' Return the path ''' # Provides: # path return {'path': os.environ.get('PATH', '').strip()} def pythonversion(): ''' Return the Python version ''' # Provides: # pythonversion return {'pythonversion': list(sys.version_info)} def pythonpath(): ''' Return the Python path ''' # Provides: # pythonpath return {'pythonpath': sys.path} def pythonexecutable(): ''' Return the python executable in use ''' # Provides: # pythonexecutable return {'pythonexecutable': sys.executable} def saltpath(): ''' Return the path of the salt module ''' # Provides: # saltpath salt_path = os.path.abspath(os.path.join(__file__, os.path.pardir)) return {'saltpath': os.path.dirname(salt_path)} def saltversion(): ''' Return the version of salt ''' # Provides: # saltversion from salt.version import __version__ return {'saltversion': __version__} def zmqversion(): ''' Return the zeromq version ''' # Provides: # zmqversion try: import zmq return {'zmqversion': zmq.zmq_version()} # pylint: disable=no-member except ImportError: return {} def saltversioninfo(): ''' Return the version_info of salt .. versionadded:: 0.17.0 ''' # Provides: # saltversioninfo from salt.version import __version_info__ return {'saltversioninfo': list(__version_info__)} def _hw_data(osdata): ''' Get system specific hardware data from dmidecode Provides biosversion productname manufacturer serialnumber biosreleasedate uuid .. versionadded:: 0.9.5 ''' if salt.utils.platform.is_proxy(): return {} grains = {} if osdata['kernel'] == 'Linux' and os.path.exists('/sys/class/dmi/id'): # On many Linux distributions basic firmware information is available via sysfs # requires CONFIG_DMIID to be enabled in the Linux kernel configuration sysfs_firmware_info = { 'biosversion': 'bios_version', 'productname': 'product_name', 'manufacturer': 'sys_vendor', 'biosreleasedate': 'bios_date', 'uuid': 'product_uuid', 'serialnumber': 'product_serial' } for key, fw_file in sysfs_firmware_info.items(): contents_file = os.path.join('/sys/class/dmi/id', fw_file) if os.path.exists(contents_file): try: with salt.utils.files.fopen(contents_file, 'r') as ifile: grains[key] = salt.utils.stringutils.to_unicode(ifile.read().strip(), errors='replace') if key == 'uuid': grains['uuid'] = grains['uuid'].lower() except (IOError, OSError) as err: # PermissionError is new to Python 3, but corresponds to the EACESS and # EPERM error numbers. Use those instead here for PY2 compatibility. if err.errno == EACCES or err.errno == EPERM: # Skip the grain if non-root user has no access to the file. pass elif salt.utils.path.which_bin(['dmidecode', 'smbios']) is not None and not ( salt.utils.platform.is_smartos() or ( # SunOS on SPARC - 'smbios: failed to load SMBIOS: System does not export an SMBIOS table' osdata['kernel'] == 'SunOS' and osdata['cpuarch'].startswith('sparc') )): # On SmartOS (possibly SunOS also) smbios only works in the global zone # smbios is also not compatible with linux's smbios (smbios -s = print summarized) grains = { 'biosversion': __salt__['smbios.get']('bios-version'), 'productname': __salt__['smbios.get']('system-product-name'), 'manufacturer': __salt__['smbios.get']('system-manufacturer'), 'biosreleasedate': __salt__['smbios.get']('bios-release-date'), 'uuid': __salt__['smbios.get']('system-uuid') } grains = dict([(key, val) for key, val in grains.items() if val is not None]) uuid = __salt__['smbios.get']('system-uuid') if uuid is not None: grains['uuid'] = uuid.lower() for serial in ('system-serial-number', 'chassis-serial-number', 'baseboard-serial-number'): serial = __salt__['smbios.get'](serial) if serial is not None: grains['serialnumber'] = serial break elif salt.utils.path.which_bin(['fw_printenv']) is not None: # ARM Linux devices expose UBOOT env variables via fw_printenv hwdata = { 'manufacturer': 'manufacturer', 'serialnumber': 'serial#', 'productname': 'DeviceDesc', } for grain_name, cmd_key in six.iteritems(hwdata): result = __salt__['cmd.run_all']('fw_printenv {0}'.format(cmd_key)) if result['retcode'] == 0: uboot_keyval = result['stdout'].split('=') grains[grain_name] = _clean_value(grain_name, uboot_keyval[1]) elif osdata['kernel'] == 'FreeBSD': # On FreeBSD /bin/kenv (already in base system) # can be used instead of dmidecode kenv = salt.utils.path.which('kenv') if kenv: # In theory, it will be easier to add new fields to this later fbsd_hwdata = { 'biosversion': 'smbios.bios.version', 'manufacturer': 'smbios.system.maker', 'serialnumber': 'smbios.system.serial', 'productname': 'smbios.system.product', 'biosreleasedate': 'smbios.bios.reldate', 'uuid': 'smbios.system.uuid', } for key, val in six.iteritems(fbsd_hwdata): value = __salt__['cmd.run']('{0} {1}'.format(kenv, val)) grains[key] = _clean_value(key, value) elif osdata['kernel'] == 'OpenBSD': sysctl = salt.utils.path.which('sysctl') hwdata = {'biosversion': 'hw.version', 'manufacturer': 'hw.vendor', 'productname': 'hw.product', 'serialnumber': 'hw.serialno', 'uuid': 'hw.uuid'} for key, oid in six.iteritems(hwdata): value = __salt__['cmd.run']('{0} -n {1}'.format(sysctl, oid)) if not value.endswith(' value is not available'): grains[key] = _clean_value(key, value) elif osdata['kernel'] == 'NetBSD': sysctl = salt.utils.path.which('sysctl') nbsd_hwdata = { 'biosversion': 'machdep.dmi.board-version', 'manufacturer': 'machdep.dmi.system-vendor', 'serialnumber': 'machdep.dmi.system-serial', 'productname': 'machdep.dmi.system-product', 'biosreleasedate': 'machdep.dmi.bios-date', 'uuid': 'machdep.dmi.system-uuid', } for key, oid in six.iteritems(nbsd_hwdata): result = __salt__['cmd.run_all']('{0} -n {1}'.format(sysctl, oid)) if result['retcode'] == 0: grains[key] = _clean_value(key, result['stdout']) elif osdata['kernel'] == 'Darwin': grains['manufacturer'] = 'Apple Inc.' sysctl = salt.utils.path.which('sysctl') hwdata = {'productname': 'hw.model'} for key, oid in hwdata.items(): value = __salt__['cmd.run']('{0} -b {1}'.format(sysctl, oid)) if not value.endswith(' is invalid'): grains[key] = _clean_value(key, value) elif osdata['kernel'] == 'SunOS' and osdata['cpuarch'].startswith('sparc'): # Depending on the hardware model, commands can report different bits # of information. With that said, consolidate the output from various # commands and attempt various lookups. data = "" for (cmd, args) in (('/usr/sbin/prtdiag', '-v'), ('/usr/sbin/prtconf', '-vp'), ('/usr/sbin/virtinfo', '-a')): if salt.utils.path.which(cmd): # Also verifies that cmd is executable data += __salt__['cmd.run']('{0} {1}'.format(cmd, args)) data += '\n' sn_regexes = [ re.compile(r) for r in [ r'(?im)^\s*Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag r'(?im)^\s*chassis-sn:\s*(\S+)', # prtconf r'(?im)^\s*Chassis\s+Serial#:\s*(\S+)', # virtinfo ] ] obp_regexes = [ re.compile(r) for r in [ r'(?im)^\s*System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag r'(?im)^\s*version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf ] ] fw_regexes = [ re.compile(r) for r in [ r'(?im)^\s*Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag ] ] uuid_regexes = [ re.compile(r) for r in [ r'(?im)^\s*Domain\s+UUID:\s*(\S+)', # virtinfo ] ] manufacture_regexes = [ re.compile(r) for r in [ r'(?im)^\s*System\s+Configuration:\s*(.*)(?=sun)', # prtdiag ] ] product_regexes = [ re.compile(r) for r in [ r'(?im)^\s*System\s+Configuration:\s*.*?sun\d\S+[^\S\r\n]*(.*)', # prtdiag r'(?im)^[^\S\r\n]*banner-name:[^\S\r\n]*(.*)', # prtconf r'(?im)^[^\S\r\n]*product-name:[^\S\r\n]*(.*)', # prtconf ] ] sn_regexes = [ re.compile(r) for r in [ r'(?im)Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag r'(?i)Chassis\s+Serial#:\s*(\S+)', # virtinfo r'(?i)chassis-sn:\s*(\S+)', # prtconf ] ] obp_regexes = [ re.compile(r) for r in [ r'(?im)System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag r'(?im)version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf ] ] fw_regexes = [ re.compile(r) for r in [ r'(?i)Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag ] ] uuid_regexes = [ re.compile(r) for r in [ r'(?i)Domain\s+UUID:\s+(\S+)', # virtinfo ] ] for regex in sn_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: grains['serialnumber'] = res.group(1).strip().replace("'", "") break for regex in obp_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: obp_rev, obp_date = res.groups()[0:2] # Limit the number in case we found the data in multiple places grains['biosversion'] = obp_rev.strip().replace("'", "") grains['biosreleasedate'] = obp_date.strip().replace("'", "") for regex in fw_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: fw_rev, fw_date = res.groups()[0:2] grains['systemfirmware'] = fw_rev.strip().replace("'", "") grains['systemfirmwaredate'] = fw_date.strip().replace("'", "") break for regex in uuid_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: grains['uuid'] = res.group(1).strip().replace("'", "") break for regex in manufacture_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: grains['manufacture'] = res.group(1).strip().replace("'", "") break for regex in product_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: t_productname = res.group(1).strip().replace("'", "") if t_productname: grains['product'] = t_productname grains['productname'] = t_productname break elif osdata['kernel'] == 'AIX': cmd = salt.utils.path.which('prtconf') if cmd: data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'), ('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')): for regex in [re.compile(r) for r in [regstring]]: res = regex.search(data) if res and len(res.groups()) >= 1: grains[dest] = res.group(1).strip().replace("'", '') product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')] for regex in product_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",") break else: log.error('The \'prtconf\' binary was not found in $PATH.') elif osdata['kernel'] == 'AIX': cmd = salt.utils.path.which('prtconf') if data: data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'), ('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')): for regex in [re.compile(r) for r in [regstring]]: res = regex.search(data) if res and len(res.groups()) >= 1: grains[dest] = res.group(1).strip().replace("'", '') product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')] for regex in product_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",") break else: log.error('The \'prtconf\' binary was not found in $PATH.') return grains def _get_hash_by_shell(): ''' Shell-out Python 3 for compute reliable hash :return: ''' id_ = __opts__.get('id', '') id_hash = None py_ver = sys.version_info[:2] if py_ver >= (3, 3): # Python 3.3 enabled hash randomization, so we need to shell out to get # a reliable hash. id_hash = __salt__['cmd.run']([sys.executable, '-c', 'print(hash("{0}"))'.format(id_)], env={'PYTHONHASHSEED': '0'}) try: id_hash = int(id_hash) except (TypeError, ValueError): log.debug('Failed to hash the ID to get the server_id grain. Result of hash command: %s', id_hash) id_hash = None if id_hash is None: # Python < 3.3 or error encountered above id_hash = hash(id_) return abs(id_hash % (2 ** 31)) def get_server_id(): ''' Provides an integer based on the FQDN of a machine. Useful as server-id in MySQL replication or anywhere else you'll need an ID like this. ''' # Provides: # server_id if salt.utils.platform.is_proxy(): server_id = {} else: use_crc = __opts__.get('server_id_use_crc') if bool(use_crc): id_hash = getattr(zlib, use_crc, zlib.adler32)(__opts__.get('id', '').encode()) & 0xffffffff else: log.debug('This server_id is computed not by Adler32 nor by CRC32. ' 'Please use "server_id_use_crc" option and define algorithm you ' 'prefer (default "Adler32"). Starting with Sodium, the ' 'server_id will be computed with Adler32 by default.') id_hash = _get_hash_by_shell() server_id = {'server_id': id_hash} return server_id def get_master(): ''' Provides the minion with the name of its master. This is useful in states to target other services running on the master. ''' # Provides: # master return {'master': __opts__.get('master', '')} def kernelparams(): ''' Return the kernel boot parameters ''' if salt.utils.platform.is_windows(): # TODO: add grains using `bcdedit /enum {current}` return {} else: try: with salt.utils.files.fopen('/proc/cmdline', 'r') as fhr: cmdline = fhr.read() grains = {'kernelparams': []} for data in [item.split('=') for item in salt.utils.args.shlex_split(cmdline)]: value = None if len(data) == 2: value = data[1].strip('"') grains['kernelparams'] += [(data[0], value)] except IOError as exc: grains = {} log.debug('Failed to read /proc/cmdline: %s', exc) return grains
saltstack/salt
salt/grains/core.py
kernelparams
python
def kernelparams(): ''' Return the kernel boot parameters ''' if salt.utils.platform.is_windows(): # TODO: add grains using `bcdedit /enum {current}` return {} else: try: with salt.utils.files.fopen('/proc/cmdline', 'r') as fhr: cmdline = fhr.read() grains = {'kernelparams': []} for data in [item.split('=') for item in salt.utils.args.shlex_split(cmdline)]: value = None if len(data) == 2: value = data[1].strip('"') grains['kernelparams'] += [(data[0], value)] except IOError as exc: grains = {} log.debug('Failed to read /proc/cmdline: %s', exc) return grains
Return the kernel boot parameters
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/grains/core.py#L2847-L2869
null
# -*- coding: utf-8 -*- ''' The static grains, these are the core, or built in grains. When grains are loaded they are not loaded in the same way that modules are loaded, grain functions are detected and executed, the functions MUST return a dict which will be applied to the main grains dict. This module will always be executed first, so that any grains loaded here in the core module can be overwritten just by returning dict keys with the same value as those returned here ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import socket import sys import re import platform import logging import locale import uuid import zlib from errno import EACCES, EPERM import datetime import warnings # pylint: disable=import-error try: import dateutil.tz _DATEUTIL_TZ = True except ImportError: _DATEUTIL_TZ = False __proxyenabled__ = ['*'] __FQDN__ = None # Extend the default list of supported distros. This will be used for the # /etc/DISTRO-release checking that is part of linux_distribution() from platform import _supported_dists _supported_dists += ('arch', 'mageia', 'meego', 'vmware', 'bluewhite64', 'slamd64', 'ovs', 'system', 'mint', 'oracle', 'void') # linux_distribution deprecated in py3.7 try: from platform import linux_distribution as _deprecated_linux_distribution def linux_distribution(**kwargs): with warnings.catch_warnings(): warnings.simplefilter("ignore") return _deprecated_linux_distribution(**kwargs) except ImportError: from distro import linux_distribution # Import salt libs import salt.exceptions import salt.log import salt.utils.args import salt.utils.dns import salt.utils.files import salt.utils.network import salt.utils.path import salt.utils.pkg.rpm import salt.utils.platform import salt.utils.stringutils import salt.utils.versions from salt.ext import six from salt.ext.six.moves import range if salt.utils.platform.is_windows(): import salt.utils.win_osinfo # Solve the Chicken and egg problem where grains need to run before any # of the modules are loaded and are generally available for any usage. import salt.modules.cmdmod import salt.modules.smbios __salt__ = { 'cmd.run': salt.modules.cmdmod._run_quiet, 'cmd.retcode': salt.modules.cmdmod._retcode_quiet, 'cmd.run_all': salt.modules.cmdmod._run_all_quiet, 'smbios.records': salt.modules.smbios.records, 'smbios.get': salt.modules.smbios.get, } log = logging.getLogger(__name__) HAS_WMI = False if salt.utils.platform.is_windows(): # attempt to import the python wmi module # the Windows minion uses WMI for some of its grains try: import wmi # pylint: disable=import-error import salt.utils.winapi import win32api import salt.utils.win_reg HAS_WMI = True except ImportError: log.exception( 'Unable to import Python wmi module, some core grains ' 'will be missing' ) HAS_UNAME = True if not hasattr(os, 'uname'): HAS_UNAME = False _INTERFACES = {} def _windows_cpudata(): ''' Return some CPU information on Windows minions ''' # Provides: # num_cpus # cpu_model grains = {} if 'NUMBER_OF_PROCESSORS' in os.environ: # Cast to int so that the logic isn't broken when used as a # conditional in templating. Also follows _linux_cpudata() try: grains['num_cpus'] = int(os.environ['NUMBER_OF_PROCESSORS']) except ValueError: grains['num_cpus'] = 1 grains['cpu_model'] = salt.utils.win_reg.read_value( hive="HKEY_LOCAL_MACHINE", key="HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", vname="ProcessorNameString").get('vdata') return grains def _linux_cpudata(): ''' Return some CPU information for Linux minions ''' # Provides: # num_cpus # cpu_model # cpu_flags grains = {} cpuinfo = '/proc/cpuinfo' # Parse over the cpuinfo file if os.path.isfile(cpuinfo): with salt.utils.files.fopen(cpuinfo, 'r') as _fp: grains['num_cpus'] = 0 for line in _fp: comps = line.split(':') if not len(comps) > 1: continue key = comps[0].strip() val = comps[1].strip() if key == 'processor': grains['num_cpus'] += 1 elif key == 'model name': grains['cpu_model'] = val elif key == 'flags': grains['cpu_flags'] = val.split() elif key == 'Features': grains['cpu_flags'] = val.split() # ARM support - /proc/cpuinfo # # Processor : ARMv6-compatible processor rev 7 (v6l) # BogoMIPS : 697.95 # Features : swp half thumb fastmult vfp edsp java tls # CPU implementer : 0x41 # CPU architecture: 7 # CPU variant : 0x0 # CPU part : 0xb76 # CPU revision : 7 # # Hardware : BCM2708 # Revision : 0002 # Serial : 00000000 elif key == 'Processor': grains['cpu_model'] = val.split('-')[0] grains['num_cpus'] = 1 if 'num_cpus' not in grains: grains['num_cpus'] = 0 if 'cpu_model' not in grains: grains['cpu_model'] = 'Unknown' if 'cpu_flags' not in grains: grains['cpu_flags'] = [] return grains def _linux_gpu_data(): ''' num_gpus: int gpus: - vendor: nvidia|amd|ati|... model: string ''' if __opts__.get('enable_lspci', True) is False: return {} if __opts__.get('enable_gpu_grains', True) is False: return {} lspci = salt.utils.path.which('lspci') if not lspci: log.debug( 'The `lspci` binary is not available on the system. GPU grains ' 'will not be available.' ) return {} # dominant gpu vendors to search for (MUST be lowercase for matching below) known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed'] gpu_classes = ('vga compatible controller', '3d controller') devs = [] try: lspci_out = __salt__['cmd.run']('{0} -vmm'.format(lspci)) cur_dev = {} error = False # Add a blank element to the lspci_out.splitlines() list, # otherwise the last device is not evaluated as a cur_dev and ignored. lspci_list = lspci_out.splitlines() lspci_list.append('') for line in lspci_list: # check for record-separating empty lines if line == '': if cur_dev.get('Class', '').lower() in gpu_classes: devs.append(cur_dev) cur_dev = {} continue if re.match(r'^\w+:\s+.*', line): key, val = line.split(':', 1) cur_dev[key.strip()] = val.strip() else: error = True log.debug('Unexpected lspci output: \'%s\'', line) if error: log.warning( 'Error loading grains, unexpected linux_gpu_data output, ' 'check that you have a valid shell configured and ' 'permissions to run lspci command' ) except OSError: pass gpus = [] for gpu in devs: vendor_strings = re.split('[^A-Za-z0-9]', gpu['Vendor'].lower()) # default vendor to 'unknown', overwrite if we match a known one vendor = 'unknown' for name in known_vendors: # search for an 'expected' vendor name in the list of strings if name in vendor_strings: vendor = name break gpus.append({'vendor': vendor, 'model': gpu['Device']}) grains = {} grains['num_gpus'] = len(gpus) grains['gpus'] = gpus return grains def _netbsd_gpu_data(): ''' num_gpus: int gpus: - vendor: nvidia|amd|ati|... model: string ''' known_vendors = ['nvidia', 'amd', 'ati', 'intel', 'cirrus logic', 'vmware', 'matrox', 'aspeed'] gpus = [] try: pcictl_out = __salt__['cmd.run']('pcictl pci0 list') for line in pcictl_out.splitlines(): for vendor in known_vendors: vendor_match = re.match( r'[0-9:]+ ({0}) (.+) \(VGA .+\)'.format(vendor), line, re.IGNORECASE ) if vendor_match: gpus.append({'vendor': vendor_match.group(1), 'model': vendor_match.group(2)}) except OSError: pass grains = {} grains['num_gpus'] = len(gpus) grains['gpus'] = gpus return grains def _osx_gpudata(): ''' num_gpus: int gpus: - vendor: nvidia|amd|ati|... model: string ''' gpus = [] try: pcictl_out = __salt__['cmd.run']('system_profiler SPDisplaysDataType') for line in pcictl_out.splitlines(): fieldname, _, fieldval = line.partition(': ') if fieldname.strip() == "Chipset Model": vendor, _, model = fieldval.partition(' ') vendor = vendor.lower() gpus.append({'vendor': vendor, 'model': model}) except OSError: pass grains = {} grains['num_gpus'] = len(gpus) grains['gpus'] = gpus return grains def _bsd_cpudata(osdata): ''' Return CPU information for BSD-like systems ''' # Provides: # cpuarch # num_cpus # cpu_model # cpu_flags sysctl = salt.utils.path.which('sysctl') arch = salt.utils.path.which('arch') cmds = {} if sysctl: cmds.update({ 'num_cpus': '{0} -n hw.ncpu'.format(sysctl), 'cpuarch': '{0} -n hw.machine'.format(sysctl), 'cpu_model': '{0} -n hw.model'.format(sysctl), }) if arch and osdata['kernel'] == 'OpenBSD': cmds['cpuarch'] = '{0} -s'.format(arch) if osdata['kernel'] == 'Darwin': cmds['cpu_model'] = '{0} -n machdep.cpu.brand_string'.format(sysctl) cmds['cpu_flags'] = '{0} -n machdep.cpu.features'.format(sysctl) grains = dict([(k, __salt__['cmd.run'](v)) for k, v in six.iteritems(cmds)]) if 'cpu_flags' in grains and isinstance(grains['cpu_flags'], six.string_types): grains['cpu_flags'] = grains['cpu_flags'].split(' ') if osdata['kernel'] == 'NetBSD': grains['cpu_flags'] = [] for line in __salt__['cmd.run']('cpuctl identify 0').splitlines(): cpu_match = re.match(r'cpu[0-9]:\ features[0-9]?\ .+<(.+)>', line) if cpu_match: flag = cpu_match.group(1).split(',') grains['cpu_flags'].extend(flag) if osdata['kernel'] == 'FreeBSD' and os.path.isfile('/var/run/dmesg.boot'): grains['cpu_flags'] = [] # TODO: at least it needs to be tested for BSD other then FreeBSD with salt.utils.files.fopen('/var/run/dmesg.boot', 'r') as _fp: cpu_here = False for line in _fp: if line.startswith('CPU: '): cpu_here = True # starts CPU descr continue if cpu_here: if not line.startswith(' '): break # game over if 'Features' in line: start = line.find('<') end = line.find('>') if start > 0 and end > 0: flag = line[start + 1:end].split(',') grains['cpu_flags'].extend(flag) try: grains['num_cpus'] = int(grains['num_cpus']) except ValueError: grains['num_cpus'] = 1 return grains def _sunos_cpudata(): ''' Return the CPU information for Solaris-like systems ''' # Provides: # cpuarch # num_cpus # cpu_model # cpu_flags grains = {} grains['cpu_flags'] = [] grains['cpuarch'] = __salt__['cmd.run']('isainfo -k') psrinfo = '/usr/sbin/psrinfo 2>/dev/null' grains['num_cpus'] = len(__salt__['cmd.run'](psrinfo, python_shell=True).splitlines()) kstat_info = 'kstat -p cpu_info:*:*:brand' for line in __salt__['cmd.run'](kstat_info).splitlines(): match = re.match(r'(\w+:\d+:\w+\d+:\w+)\s+(.+)', line) if match: grains['cpu_model'] = match.group(2) isainfo = 'isainfo -n -v' for line in __salt__['cmd.run'](isainfo).splitlines(): match = re.match(r'^\s+(.+)', line) if match: cpu_flags = match.group(1).split() grains['cpu_flags'].extend(cpu_flags) return grains def _aix_cpudata(): ''' Return CPU information for AIX systems ''' # Provides: # cpuarch # num_cpus # cpu_model # cpu_flags grains = {} cmd = salt.utils.path.which('prtconf') if cmd: data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep for dest, regstring in (('cpuarch', r'(?im)^\s*Processor\s+Type:\s+(\S+)'), ('cpu_flags', r'(?im)^\s*Processor\s+Version:\s+(\S+)'), ('cpu_model', r'(?im)^\s*Processor\s+Implementation\s+Mode:\s+(.*)'), ('num_cpus', r'(?im)^\s*Number\s+Of\s+Processors:\s+(\S+)')): for regex in [re.compile(r) for r in [regstring]]: res = regex.search(data) if res and len(res.groups()) >= 1: grains[dest] = res.group(1).strip().replace("'", '') else: log.error('The \'prtconf\' binary was not found in $PATH.') return grains def _linux_memdata(): ''' Return the memory information for Linux-like systems ''' grains = {'mem_total': 0, 'swap_total': 0} meminfo = '/proc/meminfo' if os.path.isfile(meminfo): with salt.utils.files.fopen(meminfo, 'r') as ifile: for line in ifile: comps = line.rstrip('\n').split(':') if not len(comps) > 1: continue if comps[0].strip() == 'MemTotal': # Use floor division to force output to be an integer grains['mem_total'] = int(comps[1].split()[0]) // 1024 if comps[0].strip() == 'SwapTotal': # Use floor division to force output to be an integer grains['swap_total'] = int(comps[1].split()[0]) // 1024 return grains def _osx_memdata(): ''' Return the memory information for BSD-like systems ''' grains = {'mem_total': 0, 'swap_total': 0} sysctl = salt.utils.path.which('sysctl') if sysctl: mem = __salt__['cmd.run']('{0} -n hw.memsize'.format(sysctl)) swap_total = __salt__['cmd.run']('{0} -n vm.swapusage'.format(sysctl)).split()[2].replace(',', '.') if swap_total.endswith('K'): _power = 2**10 elif swap_total.endswith('M'): _power = 2**20 elif swap_total.endswith('G'): _power = 2**30 swap_total = float(swap_total[:-1]) * _power grains['mem_total'] = int(mem) // 1024 // 1024 grains['swap_total'] = int(swap_total) // 1024 // 1024 return grains def _bsd_memdata(osdata): ''' Return the memory information for BSD-like systems ''' grains = {'mem_total': 0, 'swap_total': 0} sysctl = salt.utils.path.which('sysctl') if sysctl: mem = __salt__['cmd.run']('{0} -n hw.physmem'.format(sysctl)) if osdata['kernel'] == 'NetBSD' and mem.startswith('-'): mem = __salt__['cmd.run']('{0} -n hw.physmem64'.format(sysctl)) grains['mem_total'] = int(mem) // 1024 // 1024 if osdata['kernel'] in ['OpenBSD', 'NetBSD']: swapctl = salt.utils.path.which('swapctl') swap_data = __salt__['cmd.run']('{0} -sk'.format(swapctl)) if swap_data == 'no swap devices configured': swap_total = 0 else: swap_total = swap_data.split(' ')[1] else: swap_total = __salt__['cmd.run']('{0} -n vm.swap_total'.format(sysctl)) grains['swap_total'] = int(swap_total) // 1024 // 1024 return grains def _sunos_memdata(): ''' Return the memory information for SunOS-like systems ''' grains = {'mem_total': 0, 'swap_total': 0} prtconf = '/usr/sbin/prtconf 2>/dev/null' for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines(): comps = line.split(' ') if comps[0].strip() == 'Memory' and comps[1].strip() == 'size:': grains['mem_total'] = int(comps[2].strip()) swap_cmd = salt.utils.path.which('swap') swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split() try: swap_avail = int(swap_data[-2][:-1]) swap_used = int(swap_data[-4][:-1]) swap_total = (swap_avail + swap_used) // 1024 except ValueError: swap_total = None grains['swap_total'] = swap_total return grains def _aix_memdata(): ''' Return the memory information for AIX systems ''' grains = {'mem_total': 0, 'swap_total': 0} prtconf = salt.utils.path.which('prtconf') if prtconf: for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines(): comps = [x for x in line.strip().split(' ') if x] if len(comps) > 2 and 'Memory' in comps[0] and 'Size' in comps[1]: grains['mem_total'] = int(comps[2]) break else: log.error('The \'prtconf\' binary was not found in $PATH.') swap_cmd = salt.utils.path.which('swap') if swap_cmd: swap_data = __salt__['cmd.run']('{0} -s'.format(swap_cmd)).split() try: swap_total = (int(swap_data[-2]) + int(swap_data[-6])) * 4 except ValueError: swap_total = None grains['swap_total'] = swap_total else: log.error('The \'swap\' binary was not found in $PATH.') return grains def _windows_memdata(): ''' Return the memory information for Windows systems ''' grains = {'mem_total': 0} # get the Total Physical memory as reported by msinfo32 tot_bytes = win32api.GlobalMemoryStatusEx()['TotalPhys'] # return memory info in gigabytes grains['mem_total'] = int(tot_bytes / (1024 ** 2)) return grains def _memdata(osdata): ''' Gather information about the system memory ''' # Provides: # mem_total # swap_total, for supported systems. grains = {'mem_total': 0} if osdata['kernel'] == 'Linux': grains.update(_linux_memdata()) elif osdata['kernel'] in ('FreeBSD', 'OpenBSD', 'NetBSD'): grains.update(_bsd_memdata(osdata)) elif osdata['kernel'] == 'Darwin': grains.update(_osx_memdata()) elif osdata['kernel'] == 'SunOS': grains.update(_sunos_memdata()) elif osdata['kernel'] == 'AIX': grains.update(_aix_memdata()) elif osdata['kernel'] == 'Windows' and HAS_WMI: grains.update(_windows_memdata()) return grains def _aix_get_machine_id(): ''' Parse the output of lsattr -El sys0 for os_uuid ''' grains = {} cmd = salt.utils.path.which('lsattr') if cmd: data = __salt__['cmd.run']('{0} -El sys0'.format(cmd)) + os.linesep uuid_regexes = [re.compile(r'(?im)^\s*os_uuid\s+(\S+)\s+(.*)')] for regex in uuid_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: grains['machine_id'] = res.group(1).strip() break else: log.error('The \'lsattr\' binary was not found in $PATH.') return grains def _windows_virtual(osdata): ''' Returns what type of virtual hardware is under the hood, kvm or physical ''' # Provides: # virtual # virtual_subtype grains = dict() if osdata['kernel'] != 'Windows': return grains grains['virtual'] = 'physical' # It is possible that the 'manufacturer' and/or 'productname' grains # exist but have a value of None. manufacturer = osdata.get('manufacturer', '') if manufacturer is None: manufacturer = '' productname = osdata.get('productname', '') if productname is None: productname = '' if 'QEMU' in manufacturer: # FIXME: Make this detect between kvm or qemu grains['virtual'] = 'kvm' if 'Bochs' in manufacturer: grains['virtual'] = 'kvm' # Product Name: (oVirt) www.ovirt.org # Red Hat Community virtualization Project based on kvm elif 'oVirt' in productname: grains['virtual'] = 'kvm' grains['virtual_subtype'] = 'oVirt' # Red Hat Enterprise Virtualization elif 'RHEV Hypervisor' in productname: grains['virtual'] = 'kvm' grains['virtual_subtype'] = 'rhev' # Product Name: VirtualBox elif 'VirtualBox' in productname: grains['virtual'] = 'VirtualBox' # Product Name: VMware Virtual Platform elif 'VMware Virtual Platform' in productname: grains['virtual'] = 'VMware' # Manufacturer: Microsoft Corporation # Product Name: Virtual Machine elif 'Microsoft' in manufacturer and \ 'Virtual Machine' in productname: grains['virtual'] = 'VirtualPC' # Manufacturer: Parallels Software International Inc. elif 'Parallels Software' in manufacturer: grains['virtual'] = 'Parallels' # Apache CloudStack elif 'CloudStack KVM Hypervisor' in productname: grains['virtual'] = 'kvm' grains['virtual_subtype'] = 'cloudstack' return grains def _virtual(osdata): ''' Returns what type of virtual hardware is under the hood, kvm or physical ''' # This is going to be a monster, if you are running a vm you can test this # grain with please submit patches! # Provides: # virtual # virtual_subtype grains = {'virtual': 'physical'} # Skip the below loop on platforms which have none of the desired cmds # This is a temporary measure until we can write proper virtual hardware # detection. skip_cmds = ('AIX',) # list of commands to be executed to determine the 'virtual' grain _cmds = ['systemd-detect-virt', 'virt-what', 'dmidecode'] # test first for virt-what, which covers most of the desired functionality # on most platforms if not salt.utils.platform.is_windows() and osdata['kernel'] not in skip_cmds: if salt.utils.path.which('virt-what'): _cmds = ['virt-what'] # Check if enable_lspci is True or False if __opts__.get('enable_lspci', True) is True: # /proc/bus/pci does not exists, lspci will fail if os.path.exists('/proc/bus/pci'): _cmds += ['lspci'] # Add additional last resort commands if osdata['kernel'] in skip_cmds: _cmds = () # Quick backout for BrandZ (Solaris LX Branded zones) # Don't waste time trying other commands to detect the virtual grain if HAS_UNAME and osdata['kernel'] == 'Linux' and 'BrandZ virtual linux' in os.uname(): grains['virtual'] = 'zone' return grains failed_commands = set() for command in _cmds: args = [] if osdata['kernel'] == 'Darwin': command = 'system_profiler' args = ['SPDisplaysDataType'] elif osdata['kernel'] == 'SunOS': virtinfo = salt.utils.path.which('virtinfo') if virtinfo: try: ret = __salt__['cmd.run_all']('{0} -a'.format(virtinfo)) except salt.exceptions.CommandExecutionError: if salt.log.is_logging_configured(): failed_commands.add(virtinfo) else: if ret['stdout'].endswith('not supported'): command = 'prtdiag' else: command = 'virtinfo' else: command = 'prtdiag' cmd = salt.utils.path.which(command) if not cmd: continue cmd = '{0} {1}'.format(cmd, ' '.join(args)) try: ret = __salt__['cmd.run_all'](cmd) if ret['retcode'] > 0: if salt.log.is_logging_configured(): # systemd-detect-virt always returns > 0 on non-virtualized # systems # prtdiag only works in the global zone, skip if it fails if salt.utils.platform.is_windows() or 'systemd-detect-virt' in cmd or 'prtdiag' in cmd: continue failed_commands.add(command) continue except salt.exceptions.CommandExecutionError: if salt.log.is_logging_configured(): if salt.utils.platform.is_windows(): continue failed_commands.add(command) continue output = ret['stdout'] if command == "system_profiler": macoutput = output.lower() if '0x1ab8' in macoutput: grains['virtual'] = 'Parallels' if 'parallels' in macoutput: grains['virtual'] = 'Parallels' if 'vmware' in macoutput: grains['virtual'] = 'VMware' if '0x15ad' in macoutput: grains['virtual'] = 'VMware' if 'virtualbox' in macoutput: grains['virtual'] = 'VirtualBox' # Break out of the loop so the next log message is not issued break elif command == 'systemd-detect-virt': if output in ('qemu', 'kvm', 'oracle', 'xen', 'bochs', 'chroot', 'uml', 'systemd-nspawn'): grains['virtual'] = output break elif 'vmware' in output: grains['virtual'] = 'VMware' break elif 'microsoft' in output: grains['virtual'] = 'VirtualPC' break elif 'lxc' in output: grains['virtual'] = 'LXC' break elif 'systemd-nspawn' in output: grains['virtual'] = 'LXC' break elif command == 'virt-what': try: output = output.splitlines()[-1] except IndexError: pass if output in ('kvm', 'qemu', 'uml', 'xen', 'lxc'): grains['virtual'] = output break elif 'vmware' in output: grains['virtual'] = 'VMware' break elif 'parallels' in output: grains['virtual'] = 'Parallels' break elif 'hyperv' in output: grains['virtual'] = 'HyperV' break elif command == 'dmidecode': # Product Name: VirtualBox if 'Vendor: QEMU' in output: # FIXME: Make this detect between kvm or qemu grains['virtual'] = 'kvm' if 'Manufacturer: QEMU' in output: grains['virtual'] = 'kvm' if 'Vendor: Bochs' in output: grains['virtual'] = 'kvm' if 'Manufacturer: Bochs' in output: grains['virtual'] = 'kvm' if 'BHYVE' in output: grains['virtual'] = 'bhyve' # Product Name: (oVirt) www.ovirt.org # Red Hat Community virtualization Project based on kvm elif 'Manufacturer: oVirt' in output: grains['virtual'] = 'kvm' grains['virtual_subtype'] = 'ovirt' # Red Hat Enterprise Virtualization elif 'Product Name: RHEV Hypervisor' in output: grains['virtual'] = 'kvm' grains['virtual_subtype'] = 'rhev' elif 'VirtualBox' in output: grains['virtual'] = 'VirtualBox' # Product Name: VMware Virtual Platform elif 'VMware' in output: grains['virtual'] = 'VMware' # Manufacturer: Microsoft Corporation # Product Name: Virtual Machine elif ': Microsoft' in output and 'Virtual Machine' in output: grains['virtual'] = 'VirtualPC' # Manufacturer: Parallels Software International Inc. elif 'Parallels Software' in output: grains['virtual'] = 'Parallels' elif 'Manufacturer: Google' in output: grains['virtual'] = 'kvm' # Proxmox KVM elif 'Vendor: SeaBIOS' in output: grains['virtual'] = 'kvm' # Break out of the loop, lspci parsing is not necessary break elif command == 'lspci': # dmidecode not available or the user does not have the necessary # permissions model = output.lower() if 'vmware' in model: grains['virtual'] = 'VMware' # 00:04.0 System peripheral: InnoTek Systemberatung GmbH # VirtualBox Guest Service elif 'virtualbox' in model: grains['virtual'] = 'VirtualBox' elif 'qemu' in model: grains['virtual'] = 'kvm' elif 'virtio' in model: grains['virtual'] = 'kvm' # Break out of the loop so the next log message is not issued break elif command == 'prtdiag': model = output.lower().split("\n")[0] if 'vmware' in model: grains['virtual'] = 'VMware' elif 'virtualbox' in model: grains['virtual'] = 'VirtualBox' elif 'qemu' in model: grains['virtual'] = 'kvm' elif 'joyent smartdc hvm' in model: grains['virtual'] = 'kvm' break elif command == 'virtinfo': grains['virtual'] = 'LDOM' break choices = ('Linux', 'HP-UX') isdir = os.path.isdir sysctl = salt.utils.path.which('sysctl') if osdata['kernel'] in choices: if os.path.isdir('/proc'): try: self_root = os.stat('/') init_root = os.stat('/proc/1/root/.') if self_root != init_root: grains['virtual_subtype'] = 'chroot' except (IOError, OSError): pass if isdir('/proc/vz'): if os.path.isfile('/proc/vz/version'): grains['virtual'] = 'openvzhn' elif os.path.isfile('/proc/vz/veinfo'): grains['virtual'] = 'openvzve' # a posteriori, it's expected for these to have failed: failed_commands.discard('lspci') failed_commands.discard('dmidecode') # Provide additional detection for OpenVZ if os.path.isfile('/proc/self/status'): with salt.utils.files.fopen('/proc/self/status') as status_file: vz_re = re.compile(r'^envID:\s+(\d+)$') for line in status_file: vz_match = vz_re.match(line.rstrip('\n')) if vz_match and int(vz_match.groups()[0]) != 0: grains['virtual'] = 'openvzve' elif vz_match and int(vz_match.groups()[0]) == 0: grains['virtual'] = 'openvzhn' if isdir('/proc/sys/xen') or \ isdir('/sys/bus/xen') or isdir('/proc/xen'): if os.path.isfile('/proc/xen/xsd_kva'): # Tested on CentOS 5.3 / 2.6.18-194.26.1.el5xen # Tested on CentOS 5.4 / 2.6.18-164.15.1.el5xen grains['virtual_subtype'] = 'Xen Dom0' else: if osdata.get('productname', '') == 'HVM domU': # Requires dmidecode! grains['virtual_subtype'] = 'Xen HVM DomU' elif os.path.isfile('/proc/xen/capabilities') and \ os.access('/proc/xen/capabilities', os.R_OK): with salt.utils.files.fopen('/proc/xen/capabilities') as fhr: if 'control_d' not in fhr.read(): # Tested on CentOS 5.5 / 2.6.18-194.3.1.el5xen grains['virtual_subtype'] = 'Xen PV DomU' else: # Shouldn't get to this, but just in case grains['virtual_subtype'] = 'Xen Dom0' # Tested on Fedora 10 / 2.6.27.30-170.2.82 with xen # Tested on Fedora 15 / 2.6.41.4-1 without running xen elif isdir('/sys/bus/xen'): if 'xen:' in __salt__['cmd.run']('dmesg').lower(): grains['virtual_subtype'] = 'Xen PV DomU' elif os.path.isfile('/sys/bus/xen/drivers/xenconsole'): # An actual DomU will have the xenconsole driver grains['virtual_subtype'] = 'Xen PV DomU' # If a Dom0 or DomU was detected, obviously this is xen if 'dom' in grains.get('virtual_subtype', '').lower(): grains['virtual'] = 'xen' # Check container type after hypervisors, to avoid variable overwrite on containers running in virtual environment. if os.path.isfile('/proc/1/cgroup'): try: with salt.utils.files.fopen('/proc/1/cgroup', 'r') as fhr: fhr_contents = fhr.read() if ':/lxc/' in fhr_contents: grains['virtual_subtype'] = 'LXC' elif ':/kubepods/' in fhr_contents: grains['virtual_subtype'] = 'kubernetes' elif ':/libpod_parent/' in fhr_contents: grains['virtual_subtype'] = 'libpod' else: if any(x in fhr_contents for x in (':/system.slice/docker', ':/docker/', ':/docker-ce/')): grains['virtual_subtype'] = 'Docker' except IOError: pass if os.path.isfile('/proc/cpuinfo'): with salt.utils.files.fopen('/proc/cpuinfo', 'r') as fhr: if 'QEMU Virtual CPU' in fhr.read(): grains['virtual'] = 'kvm' if os.path.isfile('/sys/devices/virtual/dmi/id/product_name'): try: with salt.utils.files.fopen('/sys/devices/virtual/dmi/id/product_name', 'r') as fhr: output = salt.utils.stringutils.to_unicode(fhr.read(), errors='replace') if 'VirtualBox' in output: grains['virtual'] = 'VirtualBox' elif 'RHEV Hypervisor' in output: grains['virtual'] = 'kvm' grains['virtual_subtype'] = 'rhev' elif 'oVirt Node' in output: grains['virtual'] = 'kvm' grains['virtual_subtype'] = 'ovirt' elif 'Google' in output: grains['virtual'] = 'gce' elif 'BHYVE' in output: grains['virtual'] = 'bhyve' except IOError: pass elif osdata['kernel'] == 'FreeBSD': kenv = salt.utils.path.which('kenv') if kenv: product = __salt__['cmd.run']( '{0} smbios.system.product'.format(kenv) ) maker = __salt__['cmd.run']( '{0} smbios.system.maker'.format(kenv) ) if product.startswith('VMware'): grains['virtual'] = 'VMware' if product.startswith('VirtualBox'): grains['virtual'] = 'VirtualBox' if maker.startswith('Xen'): grains['virtual_subtype'] = '{0} {1}'.format(maker, product) grains['virtual'] = 'xen' if maker.startswith('Microsoft') and product.startswith('Virtual'): grains['virtual'] = 'VirtualPC' if maker.startswith('OpenStack'): grains['virtual'] = 'OpenStack' if maker.startswith('Bochs'): grains['virtual'] = 'kvm' if sysctl: hv_vendor = __salt__['cmd.run']('{0} hw.hv_vendor'.format(sysctl)) model = __salt__['cmd.run']('{0} hw.model'.format(sysctl)) jail = __salt__['cmd.run']( '{0} -n security.jail.jailed'.format(sysctl) ) if 'bhyve' in hv_vendor: grains['virtual'] = 'bhyve' if jail == '1': grains['virtual_subtype'] = 'jail' if 'QEMU Virtual CPU' in model: grains['virtual'] = 'kvm' elif osdata['kernel'] == 'OpenBSD': if 'manufacturer' in osdata: if osdata['manufacturer'] in ['QEMU', 'Red Hat', 'Joyent']: grains['virtual'] = 'kvm' if osdata['manufacturer'] == 'OpenBSD': grains['virtual'] = 'vmm' elif osdata['kernel'] == 'SunOS': if grains['virtual'] == 'LDOM': roles = [] for role in ('control', 'io', 'root', 'service'): subtype_cmd = '{0} -c current get -H -o value {1}-role'.format(cmd, role) ret = __salt__['cmd.run_all']('{0}'.format(subtype_cmd)) if ret['stdout'] == 'true': roles.append(role) if roles: grains['virtual_subtype'] = roles else: # Check if it's a "regular" zone. (i.e. Solaris 10/11 zone) zonename = salt.utils.path.which('zonename') if zonename: zone = __salt__['cmd.run']('{0}'.format(zonename)) if zone != 'global': grains['virtual'] = 'zone' # Check if it's a branded zone (i.e. Solaris 8/9 zone) if isdir('/.SUNWnative'): grains['virtual'] = 'zone' elif osdata['kernel'] == 'NetBSD': if sysctl: if 'QEMU Virtual CPU' in __salt__['cmd.run']( '{0} -n machdep.cpu_brand'.format(sysctl)): grains['virtual'] = 'kvm' elif 'invalid' not in __salt__['cmd.run']( '{0} -n machdep.xen.suspend'.format(sysctl)): grains['virtual'] = 'Xen PV DomU' elif 'VMware' in __salt__['cmd.run']( '{0} -n machdep.dmi.system-vendor'.format(sysctl)): grains['virtual'] = 'VMware' # NetBSD has Xen dom0 support elif __salt__['cmd.run']( '{0} -n machdep.idle-mechanism'.format(sysctl)) == 'xen': if os.path.isfile('/var/run/xenconsoled.pid'): grains['virtual_subtype'] = 'Xen Dom0' for command in failed_commands: log.info( "Although '%s' was found in path, the current user " 'cannot execute it. Grains output might not be ' 'accurate.', command ) return grains def _virtual_hv(osdata): ''' Returns detailed hypervisor information from sysfs Currently this seems to be used only by Xen ''' grains = {} # Bail early if we're not running on Xen try: if 'xen' not in osdata['virtual']: return grains except KeyError: return grains # Try to get the exact hypervisor version from sysfs try: version = {} for fn in ('major', 'minor', 'extra'): with salt.utils.files.fopen('/sys/hypervisor/version/{}'.format(fn), 'r') as fhr: version[fn] = salt.utils.stringutils.to_unicode(fhr.read().strip()) grains['virtual_hv_version'] = '{}.{}{}'.format(version['major'], version['minor'], version['extra']) grains['virtual_hv_version_info'] = [version['major'], version['minor'], version['extra']] except (IOError, OSError, KeyError): pass # Try to read and decode the supported feature set of the hypervisor # Based on https://github.com/brendangregg/Misc/blob/master/xen/xen-features.py # Table data from include/xen/interface/features.h xen_feature_table = {0: 'writable_page_tables', 1: 'writable_descriptor_tables', 2: 'auto_translated_physmap', 3: 'supervisor_mode_kernel', 4: 'pae_pgdir_above_4gb', 5: 'mmu_pt_update_preserve_ad', 7: 'gnttab_map_avail_bits', 8: 'hvm_callback_vector', 9: 'hvm_safe_pvclock', 10: 'hvm_pirqs', 11: 'dom0', 12: 'grant_map_identity', 13: 'memory_op_vnode_supported', 14: 'ARM_SMCCC_supported'} try: with salt.utils.files.fopen('/sys/hypervisor/properties/features', 'r') as fhr: features = salt.utils.stringutils.to_unicode(fhr.read().strip()) enabled_features = [] for bit, feat in six.iteritems(xen_feature_table): if int(features, 16) & (1 << bit): enabled_features.append(feat) grains['virtual_hv_features'] = features grains['virtual_hv_features_list'] = enabled_features except (IOError, OSError, KeyError): pass return grains def _ps(osdata): ''' Return the ps grain ''' grains = {} bsd_choices = ('FreeBSD', 'NetBSD', 'OpenBSD', 'MacOS') if osdata['os'] in bsd_choices: grains['ps'] = 'ps auxwww' elif osdata['os_family'] == 'Solaris': grains['ps'] = '/usr/ucb/ps auxwww' elif osdata['os'] == 'Windows': grains['ps'] = 'tasklist.exe' elif osdata.get('virtual', '') == 'openvzhn': grains['ps'] = ( 'ps -fH -p $(grep -l \"^envID:[[:space:]]*0\\$\" ' '/proc/[0-9]*/status | sed -e \"s=/proc/\\([0-9]*\\)/.*=\\1=\") ' '| awk \'{ $7=\"\"; print }\'' ) elif osdata['os_family'] == 'AIX': grains['ps'] = '/usr/bin/ps auxww' elif osdata['os_family'] == 'NILinuxRT': grains['ps'] = 'ps -o user,pid,ppid,tty,time,comm' else: grains['ps'] = 'ps -efHww' return grains def _clean_value(key, val): ''' Clean out well-known bogus values. If it isn't clean (for example has value 'None'), return None. Otherwise, return the original value. NOTE: This logic also exists in the smbios module. This function is for use when not using smbios to retrieve the value. ''' if (val is None or not val or re.match('none', val, flags=re.IGNORECASE)): return None elif 'uuid' in key: # Try each version (1-5) of RFC4122 to check if it's actually a UUID for uuidver in range(1, 5): try: uuid.UUID(val, version=uuidver) return val except ValueError: continue log.trace('HW %s value %s is an invalid UUID', key, val.replace('\n', ' ')) return None elif re.search('serial|part|version', key): # 'To be filled by O.E.M. # 'Not applicable' etc. # 'Not specified' etc. # 0000000, 1234567 etc. # begone! if (re.match(r'^[0]+$', val) or re.match(r'[0]?1234567[8]?[9]?[0]?', val) or re.search(r'sernum|part[_-]?number|specified|filled|applicable', val, flags=re.IGNORECASE)): return None elif re.search('asset|manufacturer', key): # AssetTag0. Manufacturer04. Begone. if re.search(r'manufacturer|to be filled|available|asset|^no(ne|t)', val, flags=re.IGNORECASE): return None else: # map unspecified, undefined, unknown & whatever to None if (re.search(r'to be filled', val, flags=re.IGNORECASE) or re.search(r'un(known|specified)|no(t|ne)? (asset|provided|defined|available|present|specified)', val, flags=re.IGNORECASE)): return None return val def _windows_platform_data(): ''' Use the platform module for as much as we can. ''' # Provides: # kernelrelease # kernelversion # osversion # osrelease # osservicepack # osmanufacturer # manufacturer # productname # biosversion # serialnumber # osfullname # timezone # windowsdomain # windowsdomaintype # motherboard.productname # motherboard.serialnumber # virtual if not HAS_WMI: return {} with salt.utils.winapi.Com(): wmi_c = wmi.WMI() # http://msdn.microsoft.com/en-us/library/windows/desktop/aa394102%28v=vs.85%29.aspx systeminfo = wmi_c.Win32_ComputerSystem()[0] # https://msdn.microsoft.com/en-us/library/aa394239(v=vs.85).aspx osinfo = wmi_c.Win32_OperatingSystem()[0] # http://msdn.microsoft.com/en-us/library/windows/desktop/aa394077(v=vs.85).aspx biosinfo = wmi_c.Win32_BIOS()[0] # http://msdn.microsoft.com/en-us/library/windows/desktop/aa394498(v=vs.85).aspx timeinfo = wmi_c.Win32_TimeZone()[0] # http://msdn.microsoft.com/en-us/library/windows/desktop/aa394072(v=vs.85).aspx motherboard = {'product': None, 'serial': None} try: motherboardinfo = wmi_c.Win32_BaseBoard()[0] motherboard['product'] = motherboardinfo.Product motherboard['serial'] = motherboardinfo.SerialNumber except IndexError: log.debug('Motherboard info not available on this system') os_release = platform.release() kernel_version = platform.version() info = salt.utils.win_osinfo.get_os_version_info() net_info = salt.utils.win_osinfo.get_join_info() service_pack = None if info['ServicePackMajor'] > 0: service_pack = ''.join(['SP', six.text_type(info['ServicePackMajor'])]) # This creates the osrelease grain based on the Windows Operating # System Product Name. As long as Microsoft maintains a similar format # this should be future proof version = 'Unknown' release = '' if 'Server' in osinfo.Caption: for item in osinfo.Caption.split(' '): # If it's all digits, then it's version if re.match(r'\d+', item): version = item # If it starts with R and then numbers, it's the release # ie: R2 if re.match(r'^R\d+$', item): release = item os_release = '{0}Server{1}'.format(version, release) else: for item in osinfo.Caption.split(' '): # If it's a number, decimal number, Thin or Vista, then it's the # version if re.match(r'^(\d+(\.\d+)?)|Thin|Vista$', item): version = item os_release = version grains = { 'kernelrelease': _clean_value('kernelrelease', osinfo.Version), 'kernelversion': _clean_value('kernelversion', kernel_version), 'osversion': _clean_value('osversion', osinfo.Version), 'osrelease': _clean_value('osrelease', os_release), 'osservicepack': _clean_value('osservicepack', service_pack), 'osmanufacturer': _clean_value('osmanufacturer', osinfo.Manufacturer), 'manufacturer': _clean_value('manufacturer', systeminfo.Manufacturer), 'productname': _clean_value('productname', systeminfo.Model), # bios name had a bunch of whitespace appended to it in my testing # 'PhoenixBIOS 4.0 Release 6.0 ' 'biosversion': _clean_value('biosversion', biosinfo.Name.strip()), 'serialnumber': _clean_value('serialnumber', biosinfo.SerialNumber), 'osfullname': _clean_value('osfullname', osinfo.Caption), 'timezone': _clean_value('timezone', timeinfo.Description), 'windowsdomain': _clean_value('windowsdomain', net_info['Domain']), 'windowsdomaintype': _clean_value('windowsdomaintype', net_info['DomainType']), 'motherboard': { 'productname': _clean_value('motherboard.productname', motherboard['product']), 'serialnumber': _clean_value('motherboard.serialnumber', motherboard['serial']), } } # test for virtualized environments # I only had VMware available so the rest are unvalidated if 'VRTUAL' in biosinfo.Version: # (not a typo) grains['virtual'] = 'HyperV' elif 'A M I' in biosinfo.Version: grains['virtual'] = 'VirtualPC' elif 'VMware' in systeminfo.Model: grains['virtual'] = 'VMware' elif 'VirtualBox' in systeminfo.Model: grains['virtual'] = 'VirtualBox' elif 'Xen' in biosinfo.Version: grains['virtual'] = 'Xen' if 'HVM domU' in systeminfo.Model: grains['virtual_subtype'] = 'HVM domU' elif 'OpenStack' in systeminfo.Model: grains['virtual'] = 'OpenStack' return grains def _osx_platform_data(): ''' Additional data for macOS systems Returns: A dictionary containing values for the following: - model_name - boot_rom_version - smc_version - system_serialnumber ''' cmd = 'system_profiler SPHardwareDataType' hardware = __salt__['cmd.run'](cmd) grains = {} for line in hardware.splitlines(): field_name, _, field_val = line.partition(': ') if field_name.strip() == "Model Name": key = 'model_name' grains[key] = _clean_value(key, field_val) if field_name.strip() == "Boot ROM Version": key = 'boot_rom_version' grains[key] = _clean_value(key, field_val) if field_name.strip() == "SMC Version (system)": key = 'smc_version' grains[key] = _clean_value(key, field_val) if field_name.strip() == "Serial Number (system)": key = 'system_serialnumber' grains[key] = _clean_value(key, field_val) return grains def id_(): ''' Return the id ''' return {'id': __opts__.get('id', '')} _REPLACE_LINUX_RE = re.compile(r'\W(?:gnu/)?linux', re.IGNORECASE) # This maps (at most) the first ten characters (no spaces, lowercased) of # 'osfullname' to the 'os' grain that Salt traditionally uses. # Please see os_data() and _supported_dists. # If your system is not detecting properly it likely needs an entry here. _OS_NAME_MAP = { 'redhatente': 'RedHat', 'gentoobase': 'Gentoo', 'archarm': 'Arch ARM', 'arch': 'Arch', 'debian': 'Debian', 'raspbian': 'Raspbian', 'fedoraremi': 'Fedora', 'chapeau': 'Chapeau', 'korora': 'Korora', 'amazonami': 'Amazon', 'alt': 'ALT', 'enterprise': 'OEL', 'oracleserv': 'OEL', 'cloudserve': 'CloudLinux', 'cloudlinux': 'CloudLinux', 'pidora': 'Fedora', 'scientific': 'ScientificLinux', 'synology': 'Synology', 'nilrt': 'NILinuxRT', 'poky': 'Poky', 'manjaro': 'Manjaro', 'manjarolin': 'Manjaro', 'univention': 'Univention', 'antergos': 'Antergos', 'sles': 'SUSE', 'void': 'Void', 'slesexpand': 'RES', 'linuxmint': 'Mint', 'neon': 'KDE neon', } # Map the 'os' grain to the 'os_family' grain # These should always be capitalized entries as the lookup comes # post-_OS_NAME_MAP. If your system is having trouble with detection, please # make sure that the 'os' grain is capitalized and working correctly first. _OS_FAMILY_MAP = { 'Ubuntu': 'Debian', 'Fedora': 'RedHat', 'Chapeau': 'RedHat', 'Korora': 'RedHat', 'FedBerry': 'RedHat', 'CentOS': 'RedHat', 'GoOSe': 'RedHat', 'Scientific': 'RedHat', 'Amazon': 'RedHat', 'CloudLinux': 'RedHat', 'OVS': 'RedHat', 'OEL': 'RedHat', 'XCP': 'RedHat', 'XCP-ng': 'RedHat', 'XenServer': 'RedHat', 'RES': 'RedHat', 'Sangoma': 'RedHat', 'Mandrake': 'Mandriva', 'ESXi': 'VMware', 'Mint': 'Debian', 'VMwareESX': 'VMware', 'Bluewhite64': 'Bluewhite', 'Slamd64': 'Slackware', 'SLES': 'Suse', 'SUSE Enterprise Server': 'Suse', 'SUSE Enterprise Server': 'Suse', 'SLED': 'Suse', 'openSUSE': 'Suse', 'SUSE': 'Suse', 'openSUSE Leap': 'Suse', 'openSUSE Tumbleweed': 'Suse', 'SLES_SAP': 'Suse', 'Solaris': 'Solaris', 'SmartOS': 'Solaris', 'OmniOS': 'Solaris', 'OpenIndiana Development': 'Solaris', 'OpenIndiana': 'Solaris', 'OpenSolaris Development': 'Solaris', 'OpenSolaris': 'Solaris', 'Oracle Solaris': 'Solaris', 'Arch ARM': 'Arch', 'Manjaro': 'Arch', 'Antergos': 'Arch', 'ALT': 'RedHat', 'Trisquel': 'Debian', 'GCEL': 'Debian', 'Linaro': 'Debian', 'elementary OS': 'Debian', 'elementary': 'Debian', 'Univention': 'Debian', 'ScientificLinux': 'RedHat', 'Raspbian': 'Debian', 'Devuan': 'Debian', 'antiX': 'Debian', 'Kali': 'Debian', 'neon': 'Debian', 'Cumulus': 'Debian', 'Deepin': 'Debian', 'NILinuxRT': 'NILinuxRT', 'KDE neon': 'Debian', 'Void': 'Void', 'IDMS': 'Debian', 'Funtoo': 'Gentoo', 'AIX': 'AIX', 'TurnKey': 'Debian', } # Matches any possible format: # DISTRIB_ID="Ubuntu" # DISTRIB_ID='Mageia' # DISTRIB_ID=Fedora # DISTRIB_RELEASE='10.10' # DISTRIB_CODENAME='squeeze' # DISTRIB_DESCRIPTION='Ubuntu 10.10' _LSB_REGEX = re.compile(( '^(DISTRIB_(?:ID|RELEASE|CODENAME|DESCRIPTION))=(?:\'|")?' '([\\w\\s\\.\\-_]+)(?:\'|")?' )) def _linux_bin_exists(binary): ''' Does a binary exist in linux (depends on which, type, or whereis) ''' for search_cmd in ('which', 'type -ap'): try: return __salt__['cmd.retcode']( '{0} {1}'.format(search_cmd, binary) ) == 0 except salt.exceptions.CommandExecutionError: pass try: return len(__salt__['cmd.run_all']( 'whereis -b {0}'.format(binary) )['stdout'].split()) > 1 except salt.exceptions.CommandExecutionError: return False def _get_interfaces(): ''' Provide a dict of the connected interfaces and their ip addresses ''' global _INTERFACES if not _INTERFACES: _INTERFACES = salt.utils.network.interfaces() return _INTERFACES def _parse_lsb_release(): ret = {} try: log.trace('Attempting to parse /etc/lsb-release') with salt.utils.files.fopen('/etc/lsb-release') as ifile: for line in ifile: try: key, value = _LSB_REGEX.match(line.rstrip('\n')).groups()[:2] except AttributeError: pass else: # Adds lsb_distrib_{id,release,codename,description} ret['lsb_{0}'.format(key.lower())] = value.rstrip() except (IOError, OSError) as exc: log.trace('Failed to parse /etc/lsb-release: %s', exc) return ret def _parse_os_release(*os_release_files): ''' Parse os-release and return a parameter dictionary See http://www.freedesktop.org/software/systemd/man/os-release.html for specification of the file format. ''' ret = {} for filename in os_release_files: try: with salt.utils.files.fopen(filename) as ifile: regex = re.compile('^([\\w]+)=(?:\'|")?(.*?)(?:\'|")?$') for line in ifile: match = regex.match(line.strip()) if match: # Shell special characters ("$", quotes, backslash, # backtick) are escaped with backslashes ret[match.group(1)] = re.sub( r'\\([$"\'\\`])', r'\1', match.group(2) ) break except (IOError, OSError): pass return ret def _parse_cpe_name(cpe): ''' Parse CPE_NAME data from the os-release Info: https://csrc.nist.gov/projects/security-content-automation-protocol/scap-specifications/cpe :param cpe: :return: ''' part = { 'o': 'operating system', 'h': 'hardware', 'a': 'application', } ret = {} cpe = (cpe or '').split(':') if len(cpe) > 4 and cpe[0] == 'cpe': if cpe[1].startswith('/'): # WFN to URI ret['vendor'], ret['product'], ret['version'] = cpe[2:5] ret['phase'] = cpe[5] if len(cpe) > 5 else None ret['part'] = part.get(cpe[1][1:]) elif len(cpe) == 13 and cpe[1] == '2.3': # WFN to a string ret['vendor'], ret['product'], ret['version'], ret['phase'] = [x if x != '*' else None for x in cpe[3:7]] ret['part'] = part.get(cpe[2]) return ret def os_data(): ''' Return grains pertaining to the operating system ''' grains = { 'num_gpus': 0, 'gpus': [], } # Windows Server 2008 64-bit # ('Windows', 'MINIONNAME', '2008ServerR2', '6.1.7601', 'AMD64', # 'Intel64 Fam ily 6 Model 23 Stepping 6, GenuineIntel') # Ubuntu 10.04 # ('Linux', 'MINIONNAME', '2.6.32-38-server', # '#83-Ubuntu SMP Wed Jan 4 11:26:59 UTC 2012', 'x86_64', '') # pylint: disable=unpacking-non-sequence (grains['kernel'], grains['nodename'], grains['kernelrelease'], grains['kernelversion'], grains['cpuarch'], _) = platform.uname() # pylint: enable=unpacking-non-sequence if salt.utils.platform.is_proxy(): grains['kernel'] = 'proxy' grains['kernelrelease'] = 'proxy' grains['kernelversion'] = 'proxy' grains['osrelease'] = 'proxy' grains['os'] = 'proxy' grains['os_family'] = 'proxy' grains['osfullname'] = 'proxy' elif salt.utils.platform.is_windows(): grains['os'] = 'Windows' grains['os_family'] = 'Windows' grains.update(_memdata(grains)) grains.update(_windows_platform_data()) grains.update(_windows_cpudata()) grains.update(_windows_virtual(grains)) grains.update(_ps(grains)) if 'Server' in grains['osrelease']: osrelease_info = grains['osrelease'].split('Server', 1) osrelease_info[1] = osrelease_info[1].lstrip('R') else: osrelease_info = grains['osrelease'].split('.') for idx, value in enumerate(osrelease_info): if not value.isdigit(): continue osrelease_info[idx] = int(value) grains['osrelease_info'] = tuple(osrelease_info) grains['osfinger'] = '{os}-{ver}'.format( os=grains['os'], ver=grains['osrelease']) grains['init'] = 'Windows' return grains elif salt.utils.platform.is_linux(): # Add SELinux grain, if you have it if _linux_bin_exists('selinuxenabled'): log.trace('Adding selinux grains') grains['selinux'] = {} grains['selinux']['enabled'] = __salt__['cmd.retcode']( 'selinuxenabled' ) == 0 if _linux_bin_exists('getenforce'): grains['selinux']['enforced'] = __salt__['cmd.run']( 'getenforce' ).strip() # Add systemd grain, if you have it if _linux_bin_exists('systemctl') and _linux_bin_exists('localectl'): log.trace('Adding systemd grains') grains['systemd'] = {} systemd_info = __salt__['cmd.run']( 'systemctl --version' ).splitlines() grains['systemd']['version'] = systemd_info[0].split()[1] grains['systemd']['features'] = systemd_info[1] # Add init grain grains['init'] = 'unknown' log.trace('Adding init grain') try: os.stat('/run/systemd/system') grains['init'] = 'systemd' except (OSError, IOError): try: with salt.utils.files.fopen('/proc/1/cmdline') as fhr: init_cmdline = fhr.read().replace('\x00', ' ').split() except (IOError, OSError): pass else: try: init_bin = salt.utils.path.which(init_cmdline[0]) except IndexError: # Emtpy init_cmdline init_bin = None log.warning('Unable to fetch data from /proc/1/cmdline') if init_bin is not None and init_bin.endswith('bin/init'): supported_inits = (b'upstart', b'sysvinit', b'systemd') edge_len = max(len(x) for x in supported_inits) - 1 try: buf_size = __opts__['file_buffer_size'] except KeyError: # Default to the value of file_buffer_size for the minion buf_size = 262144 try: with salt.utils.files.fopen(init_bin, 'rb') as fp_: edge = b'' buf = fp_.read(buf_size).lower() while buf: buf = edge + buf for item in supported_inits: if item in buf: if six.PY3: item = item.decode('utf-8') grains['init'] = item buf = b'' break edge = buf[-edge_len:] buf = fp_.read(buf_size).lower() except (IOError, OSError) as exc: log.error( 'Unable to read from init_bin (%s): %s', init_bin, exc ) elif salt.utils.path.which('supervisord') in init_cmdline: grains['init'] = 'supervisord' elif salt.utils.path.which('dumb-init') in init_cmdline: # https://github.com/Yelp/dumb-init grains['init'] = 'dumb-init' elif salt.utils.path.which('tini') in init_cmdline: # https://github.com/krallin/tini grains['init'] = 'tini' elif init_cmdline == ['runit']: grains['init'] = 'runit' elif '/sbin/my_init' in init_cmdline: # Phusion Base docker container use runit for srv mgmt, but # my_init as pid1 grains['init'] = 'runit' else: log.debug( 'Could not determine init system from command line: (%s)', ' '.join(init_cmdline) ) # Add lsb grains on any distro with lsb-release. Note that this import # can fail on systems with lsb-release installed if the system package # does not install the python package for the python interpreter used by # Salt (i.e. python2 or python3) try: log.trace('Getting lsb_release distro information') import lsb_release # pylint: disable=import-error release = lsb_release.get_distro_information() for key, value in six.iteritems(release): key = key.lower() lsb_param = 'lsb_{0}{1}'.format( '' if key.startswith('distrib_') else 'distrib_', key ) grains[lsb_param] = value # Catch a NameError to workaround possible breakage in lsb_release # See https://github.com/saltstack/salt/issues/37867 except (ImportError, NameError): # if the python library isn't available, try to parse # /etc/lsb-release using regex log.trace('lsb_release python bindings not available') grains.update(_parse_lsb_release()) if grains.get('lsb_distrib_description', '').lower().startswith('antergos'): # Antergos incorrectly configures their /etc/lsb-release, # setting the DISTRIB_ID to "Arch". This causes the "os" grain # to be incorrectly set to "Arch". grains['osfullname'] = 'Antergos Linux' elif 'lsb_distrib_id' not in grains: log.trace( 'Failed to get lsb_distrib_id, trying to parse os-release' ) os_release = _parse_os_release('/etc/os-release', '/usr/lib/os-release') if os_release: if 'NAME' in os_release: grains['lsb_distrib_id'] = os_release['NAME'].strip() if 'VERSION_ID' in os_release: grains['lsb_distrib_release'] = os_release['VERSION_ID'] if 'VERSION_CODENAME' in os_release: grains['lsb_distrib_codename'] = os_release['VERSION_CODENAME'] elif 'PRETTY_NAME' in os_release: codename = os_release['PRETTY_NAME'] # https://github.com/saltstack/salt/issues/44108 if os_release['ID'] == 'debian': codename_match = re.search(r'\((\w+)\)$', codename) if codename_match: codename = codename_match.group(1) grains['lsb_distrib_codename'] = codename if 'CPE_NAME' in os_release: cpe = _parse_cpe_name(os_release['CPE_NAME']) if not cpe: log.error('Broken CPE_NAME format in /etc/os-release!') elif cpe.get('vendor', '').lower() in ['suse', 'opensuse']: grains['os'] = "SUSE" # openSUSE `osfullname` grain normalization if os_release.get("NAME") == "openSUSE Leap": grains['osfullname'] = "Leap" elif os_release.get("VERSION") == "Tumbleweed": grains['osfullname'] = os_release["VERSION"] # Override VERSION_ID, if CPE_NAME around if cpe.get('version') and cpe.get('vendor') == 'opensuse': # Keep VERSION_ID for SLES grains['lsb_distrib_release'] = cpe['version'] elif os.path.isfile('/etc/SuSE-release'): log.trace('Parsing distrib info from /etc/SuSE-release') grains['lsb_distrib_id'] = 'SUSE' version = '' patch = '' with salt.utils.files.fopen('/etc/SuSE-release') as fhr: for line in fhr: if 'enterprise' in line.lower(): grains['lsb_distrib_id'] = 'SLES' grains['lsb_distrib_codename'] = re.sub(r'\(.+\)', '', line).strip() elif 'version' in line.lower(): version = re.sub(r'[^0-9]', '', line) elif 'patchlevel' in line.lower(): patch = re.sub(r'[^0-9]', '', line) grains['lsb_distrib_release'] = version if patch: grains['lsb_distrib_release'] += '.' + patch patchstr = 'SP' + patch if grains['lsb_distrib_codename'] and patchstr not in grains['lsb_distrib_codename']: grains['lsb_distrib_codename'] += ' ' + patchstr if not grains.get('lsb_distrib_codename'): grains['lsb_distrib_codename'] = 'n.a' elif os.path.isfile('/etc/altlinux-release'): log.trace('Parsing distrib info from /etc/altlinux-release') # ALT Linux grains['lsb_distrib_id'] = 'altlinux' with salt.utils.files.fopen('/etc/altlinux-release') as ifile: # This file is symlinked to from: # /etc/fedora-release # /etc/redhat-release # /etc/system-release for line in ifile: # ALT Linux Sisyphus (unstable) comps = line.split() if comps[0] == 'ALT': grains['lsb_distrib_release'] = comps[2] grains['lsb_distrib_codename'] = \ comps[3].replace('(', '').replace(')', '') elif os.path.isfile('/etc/centos-release'): log.trace('Parsing distrib info from /etc/centos-release') # Maybe CentOS Linux; could also be SUSE Expanded Support. # SUSE ES has both, centos-release and redhat-release. if os.path.isfile('/etc/redhat-release'): with salt.utils.files.fopen('/etc/redhat-release') as ifile: for line in ifile: if "red hat enterprise linux server" in line.lower(): # This is a SUSE Expanded Support Rhel installation grains['lsb_distrib_id'] = 'RedHat' break grains.setdefault('lsb_distrib_id', 'CentOS') with salt.utils.files.fopen('/etc/centos-release') as ifile: for line in ifile: # Need to pull out the version and codename # in the case of custom content in /etc/centos-release find_release = re.compile(r'\d+\.\d+') find_codename = re.compile(r'(?<=\()(.*?)(?=\))') release = find_release.search(line) codename = find_codename.search(line) if release is not None: grains['lsb_distrib_release'] = release.group() if codename is not None: grains['lsb_distrib_codename'] = codename.group() elif os.path.isfile('/etc.defaults/VERSION') \ and os.path.isfile('/etc.defaults/synoinfo.conf'): grains['osfullname'] = 'Synology' log.trace( 'Parsing Synology distrib info from /etc/.defaults/VERSION' ) with salt.utils.files.fopen('/etc.defaults/VERSION', 'r') as fp_: synoinfo = {} for line in fp_: try: key, val = line.rstrip('\n').split('=') except ValueError: continue if key in ('majorversion', 'minorversion', 'buildnumber'): synoinfo[key] = val.strip('"') if len(synoinfo) != 3: log.warning( 'Unable to determine Synology version info. ' 'Please report this, as it is likely a bug.' ) else: grains['osrelease'] = ( '{majorversion}.{minorversion}-{buildnumber}' .format(**synoinfo) ) # Use the already intelligent platform module to get distro info # (though apparently it's not intelligent enough to strip quotes) log.trace( 'Getting OS name, release, and codename from ' 'distro.linux_distribution()' ) (osname, osrelease, oscodename) = \ [x.strip('"').strip("'") for x in linux_distribution(supported_dists=_supported_dists)] # Try to assign these three names based on the lsb info, they tend to # be more accurate than what python gets from /etc/DISTRO-release. # It's worth noting that Ubuntu has patched their Python distribution # so that linux_distribution() does the /etc/lsb-release parsing, but # we do it anyway here for the sake for full portability. if 'osfullname' not in grains: # If NI Linux RT distribution, set the grains['osfullname'] to 'nilrt' if grains.get('lsb_distrib_id', '').lower().startswith('nilrt'): grains['osfullname'] = 'nilrt' else: grains['osfullname'] = grains.get('lsb_distrib_id', osname).strip() if 'osrelease' not in grains: # NOTE: This is a workaround for CentOS 7 os-release bug # https://bugs.centos.org/view.php?id=8359 # /etc/os-release contains no minor distro release number so we fall back to parse # /etc/centos-release file instead. # Commit introducing this comment should be reverted after the upstream bug is released. if 'CentOS Linux 7' in grains.get('lsb_distrib_codename', ''): grains.pop('lsb_distrib_release', None) grains['osrelease'] = grains.get('lsb_distrib_release', osrelease).strip() grains['oscodename'] = grains.get('lsb_distrib_codename', '').strip() or oscodename if 'Red Hat' in grains['oscodename']: grains['oscodename'] = oscodename distroname = _REPLACE_LINUX_RE.sub('', grains['osfullname']).strip() # return the first ten characters with no spaces, lowercased shortname = distroname.replace(' ', '').lower()[:10] # this maps the long names from the /etc/DISTRO-release files to the # traditional short names that Salt has used. if 'os' not in grains: grains['os'] = _OS_NAME_MAP.get(shortname, distroname) grains.update(_linux_cpudata()) grains.update(_linux_gpu_data()) elif grains['kernel'] == 'SunOS': if salt.utils.platform.is_smartos(): # See https://github.com/joyent/smartos-live/issues/224 if HAS_UNAME: uname_v = os.uname()[3] # format: joyent_20161101T004406Z else: uname_v = os.name uname_v = uname_v[uname_v.index('_')+1:] grains['os'] = grains['osfullname'] = 'SmartOS' # store a parsed version of YYYY.MM.DD as osrelease grains['osrelease'] = ".".join([ uname_v.split('T')[0][0:4], uname_v.split('T')[0][4:6], uname_v.split('T')[0][6:8], ]) # store a untouched copy of the timestamp in osrelease_stamp grains['osrelease_stamp'] = uname_v elif os.path.isfile('/etc/release'): with salt.utils.files.fopen('/etc/release', 'r') as fp_: rel_data = fp_.read() try: release_re = re.compile( r'((?:Open|Oracle )?Solaris|OpenIndiana|OmniOS) (Development)?' r'\s*(\d+\.?\d*|v\d+)\s?[A-Z]*\s?(r\d+|\d+\/\d+|oi_\S+|snv_\S+)?' ) osname, development, osmajorrelease, osminorrelease = release_re.search(rel_data).groups() except AttributeError: # Set a blank osrelease grain and fallback to 'Solaris' # as the 'os' grain. grains['os'] = grains['osfullname'] = 'Solaris' grains['osrelease'] = '' else: if development is not None: osname = ' '.join((osname, development)) if HAS_UNAME: uname_v = os.uname()[3] else: uname_v = os.name grains['os'] = grains['osfullname'] = osname if osname in ['Oracle Solaris'] and uname_v.startswith(osmajorrelease): # Oracla Solars 11 and up have minor version in uname grains['osrelease'] = uname_v elif osname in ['OmniOS']: # OmniOS osrelease = [] osrelease.append(osmajorrelease[1:]) osrelease.append(osminorrelease[1:]) grains['osrelease'] = ".".join(osrelease) grains['osrelease_stamp'] = uname_v else: # Sun Solaris 10 and earlier/comparable osrelease = [] osrelease.append(osmajorrelease) if osminorrelease: osrelease.append(osminorrelease) grains['osrelease'] = ".".join(osrelease) grains['osrelease_stamp'] = uname_v grains.update(_sunos_cpudata()) elif grains['kernel'] == 'VMkernel': grains['os'] = 'ESXi' elif grains['kernel'] == 'Darwin': osrelease = __salt__['cmd.run']('sw_vers -productVersion') osname = __salt__['cmd.run']('sw_vers -productName') osbuild = __salt__['cmd.run']('sw_vers -buildVersion') grains['os'] = 'MacOS' grains['os_family'] = 'MacOS' grains['osfullname'] = "{0} {1}".format(osname, osrelease) grains['osrelease'] = osrelease grains['osbuild'] = osbuild grains['init'] = 'launchd' grains.update(_bsd_cpudata(grains)) grains.update(_osx_gpudata()) grains.update(_osx_platform_data()) elif grains['kernel'] == 'AIX': osrelease = __salt__['cmd.run']('oslevel') osrelease_techlevel = __salt__['cmd.run']('oslevel -r') osname = __salt__['cmd.run']('uname') grains['os'] = 'AIX' grains['osfullname'] = osname grains['osrelease'] = osrelease grains['osrelease_techlevel'] = osrelease_techlevel grains.update(_aix_cpudata()) else: grains['os'] = grains['kernel'] if grains['kernel'] == 'FreeBSD': try: grains['osrelease'] = __salt__['cmd.run']('freebsd-version -u').split('-')[0] except salt.exceptions.CommandExecutionError: # freebsd-version was introduced in 10.0. # derive osrelease from kernelversion prior to that grains['osrelease'] = grains['kernelrelease'].split('-')[0] grains.update(_bsd_cpudata(grains)) if grains['kernel'] in ('OpenBSD', 'NetBSD'): grains.update(_bsd_cpudata(grains)) grains['osrelease'] = grains['kernelrelease'].split('-')[0] if grains['kernel'] == 'NetBSD': grains.update(_netbsd_gpu_data()) if not grains['os']: grains['os'] = 'Unknown {0}'.format(grains['kernel']) grains['os_family'] = 'Unknown' else: # this assigns family names based on the os name # family defaults to the os name if not found grains['os_family'] = _OS_FAMILY_MAP.get(grains['os'], grains['os']) # Build the osarch grain. This grain will be used for platform-specific # considerations such as package management. Fall back to the CPU # architecture. if grains.get('os_family') == 'Debian': osarch = __salt__['cmd.run']('dpkg --print-architecture').strip() elif grains.get('os_family') in ['RedHat', 'Suse']: osarch = salt.utils.pkg.rpm.get_osarch() elif grains.get('os_family') in ('NILinuxRT', 'Poky'): archinfo = {} for line in __salt__['cmd.run']('opkg print-architecture').splitlines(): if line.startswith('arch'): _, arch, priority = line.split() archinfo[arch.strip()] = int(priority.strip()) # Return osarch in priority order (higher to lower) osarch = sorted(archinfo, key=archinfo.get, reverse=True) else: osarch = grains['cpuarch'] grains['osarch'] = osarch grains.update(_memdata(grains)) # Get the hardware and bios data grains.update(_hw_data(grains)) # Load the virtual machine info grains.update(_virtual(grains)) grains.update(_virtual_hv(grains)) grains.update(_ps(grains)) if grains.get('osrelease', ''): osrelease_info = grains['osrelease'].split('.') for idx, value in enumerate(osrelease_info): if not value.isdigit(): continue osrelease_info[idx] = int(value) grains['osrelease_info'] = tuple(osrelease_info) try: grains['osmajorrelease'] = int(grains['osrelease_info'][0]) except (IndexError, TypeError, ValueError): log.debug( 'Unable to derive osmajorrelease from osrelease_info \'%s\'. ' 'The osmajorrelease grain will not be set.', grains['osrelease_info'] ) os_name = grains['os' if grains.get('os') in ( 'Debian', 'FreeBSD', 'OpenBSD', 'NetBSD', 'Mac', 'Raspbian') else 'osfullname'] grains['osfinger'] = '{0}-{1}'.format( os_name, grains['osrelease'] if os_name in ('Ubuntu',) else grains['osrelease_info'][0]) return grains def locale_info(): ''' Provides defaultlanguage defaultencoding ''' grains = {} grains['locale_info'] = {} if salt.utils.platform.is_proxy(): return grains try: ( grains['locale_info']['defaultlanguage'], grains['locale_info']['defaultencoding'] ) = locale.getdefaultlocale() except Exception: # locale.getdefaultlocale can ValueError!! Catch anything else it # might do, per #2205 grains['locale_info']['defaultlanguage'] = 'unknown' grains['locale_info']['defaultencoding'] = 'unknown' grains['locale_info']['detectedencoding'] = __salt_system_encoding__ if _DATEUTIL_TZ: grains['locale_info']['timezone'] = datetime.datetime.now(dateutil.tz.tzlocal()).tzname() return grains def hostname(): ''' Return fqdn, hostname, domainname ''' # This is going to need some work # Provides: # fqdn # host # localhost # domain global __FQDN__ grains = {} if salt.utils.platform.is_proxy(): return grains grains['localhost'] = socket.gethostname() if __FQDN__ is None: __FQDN__ = salt.utils.network.get_fqhostname() # On some distros (notably FreeBSD) if there is no hostname set # salt.utils.network.get_fqhostname() will return None. # In this case we punt and log a message at error level, but force the # hostname and domain to be localhost.localdomain # Otherwise we would stacktrace below if __FQDN__ is None: # still! log.error('Having trouble getting a hostname. Does this machine have its hostname and domain set properly?') __FQDN__ = 'localhost.localdomain' grains['fqdn'] = __FQDN__ (grains['host'], grains['domain']) = grains['fqdn'].partition('.')[::2] return grains def append_domain(): ''' Return append_domain if set ''' grain = {} if salt.utils.platform.is_proxy(): return grain if 'append_domain' in __opts__: grain['append_domain'] = __opts__['append_domain'] return grain def fqdns(): ''' Return all known FQDNs for the system by enumerating all interfaces and then trying to reverse resolve them (excluding 'lo' interface). ''' # Provides: # fqdns grains = {} fqdns = set() addresses = salt.utils.network.ip_addrs(include_loopback=False, interface_data=_get_interfaces()) addresses.extend(salt.utils.network.ip_addrs6(include_loopback=False, interface_data=_get_interfaces())) err_message = 'Exception during resolving address: %s' for ip in addresses: try: name, aliaslist, addresslist = socket.gethostbyaddr(ip) fqdns.update([socket.getfqdn(name)] + [als for als in aliaslist if salt.utils.network.is_fqdn(als)]) except socket.herror as err: if err.errno == 0: # No FQDN for this IP address, so we don't need to know this all the time. log.debug("Unable to resolve address %s: %s", ip, err) else: log.error(err_message, err) except (socket.error, socket.gaierror, socket.timeout) as err: log.error(err_message, err) return {"fqdns": sorted(list(fqdns))} def ip_fqdn(): ''' Return ip address and FQDN grains ''' if salt.utils.platform.is_proxy(): return {} ret = {} ret['ipv4'] = salt.utils.network.ip_addrs(include_loopback=True) ret['ipv6'] = salt.utils.network.ip_addrs6(include_loopback=True) _fqdn = hostname()['fqdn'] for socket_type, ipv_num in ((socket.AF_INET, '4'), (socket.AF_INET6, '6')): key = 'fqdn_ip' + ipv_num if not ret['ipv' + ipv_num]: ret[key] = [] else: try: start_time = datetime.datetime.utcnow() info = socket.getaddrinfo(_fqdn, None, socket_type) ret[key] = list(set(item[4][0] for item in info)) except socket.error: timediff = datetime.datetime.utcnow() - start_time if timediff.seconds > 5 and __opts__['__role'] == 'master': log.warning( 'Unable to find IPv%s record for "%s" causing a %s ' 'second timeout when rendering grains. Set the dns or ' '/etc/hosts for IPv%s to clear this.', ipv_num, _fqdn, timediff, ipv_num ) ret[key] = [] return ret def ip_interfaces(): ''' Provide a dict of the connected interfaces and their ip addresses The addresses will be passed as a list for each interface ''' # Provides: # ip_interfaces if salt.utils.platform.is_proxy(): return {} ret = {} ifaces = _get_interfaces() for face in ifaces: iface_ips = [] for inet in ifaces[face].get('inet', []): if 'address' in inet: iface_ips.append(inet['address']) for inet in ifaces[face].get('inet6', []): if 'address' in inet: iface_ips.append(inet['address']) for secondary in ifaces[face].get('secondary', []): if 'address' in secondary: iface_ips.append(secondary['address']) ret[face] = iface_ips return {'ip_interfaces': ret} def ip4_interfaces(): ''' Provide a dict of the connected interfaces and their ip4 addresses The addresses will be passed as a list for each interface ''' # Provides: # ip_interfaces if salt.utils.platform.is_proxy(): return {} ret = {} ifaces = _get_interfaces() for face in ifaces: iface_ips = [] for inet in ifaces[face].get('inet', []): if 'address' in inet: iface_ips.append(inet['address']) for secondary in ifaces[face].get('secondary', []): if 'address' in secondary: iface_ips.append(secondary['address']) ret[face] = iface_ips return {'ip4_interfaces': ret} def ip6_interfaces(): ''' Provide a dict of the connected interfaces and their ip6 addresses The addresses will be passed as a list for each interface ''' # Provides: # ip_interfaces if salt.utils.platform.is_proxy(): return {} ret = {} ifaces = _get_interfaces() for face in ifaces: iface_ips = [] for inet in ifaces[face].get('inet6', []): if 'address' in inet: iface_ips.append(inet['address']) for secondary in ifaces[face].get('secondary', []): if 'address' in secondary: iface_ips.append(secondary['address']) ret[face] = iface_ips return {'ip6_interfaces': ret} def hwaddr_interfaces(): ''' Provide a dict of the connected interfaces and their hw addresses (Mac Address) ''' # Provides: # hwaddr_interfaces ret = {} ifaces = _get_interfaces() for face in ifaces: if 'hwaddr' in ifaces[face]: ret[face] = ifaces[face]['hwaddr'] return {'hwaddr_interfaces': ret} def dns(): ''' Parse the resolver configuration file .. versionadded:: 2016.3.0 ''' # Provides: # dns if salt.utils.platform.is_windows() or 'proxyminion' in __opts__: return {} resolv = salt.utils.dns.parse_resolv() for key in ('nameservers', 'ip4_nameservers', 'ip6_nameservers', 'sortlist'): if key in resolv: resolv[key] = [six.text_type(i) for i in resolv[key]] return {'dns': resolv} if resolv else {} def get_machine_id(): ''' Provide the machine-id for machine/virtualization combination ''' # Provides: # machine-id if platform.system() == 'AIX': return _aix_get_machine_id() locations = ['/etc/machine-id', '/var/lib/dbus/machine-id'] existing_locations = [loc for loc in locations if os.path.exists(loc)] if not existing_locations: return {} else: with salt.utils.files.fopen(existing_locations[0]) as machineid: return {'machine_id': machineid.read().strip()} def cwd(): ''' Current working directory ''' return {'cwd': os.getcwd()} def path(): ''' Return the path ''' # Provides: # path return {'path': os.environ.get('PATH', '').strip()} def pythonversion(): ''' Return the Python version ''' # Provides: # pythonversion return {'pythonversion': list(sys.version_info)} def pythonpath(): ''' Return the Python path ''' # Provides: # pythonpath return {'pythonpath': sys.path} def pythonexecutable(): ''' Return the python executable in use ''' # Provides: # pythonexecutable return {'pythonexecutable': sys.executable} def saltpath(): ''' Return the path of the salt module ''' # Provides: # saltpath salt_path = os.path.abspath(os.path.join(__file__, os.path.pardir)) return {'saltpath': os.path.dirname(salt_path)} def saltversion(): ''' Return the version of salt ''' # Provides: # saltversion from salt.version import __version__ return {'saltversion': __version__} def zmqversion(): ''' Return the zeromq version ''' # Provides: # zmqversion try: import zmq return {'zmqversion': zmq.zmq_version()} # pylint: disable=no-member except ImportError: return {} def saltversioninfo(): ''' Return the version_info of salt .. versionadded:: 0.17.0 ''' # Provides: # saltversioninfo from salt.version import __version_info__ return {'saltversioninfo': list(__version_info__)} def _hw_data(osdata): ''' Get system specific hardware data from dmidecode Provides biosversion productname manufacturer serialnumber biosreleasedate uuid .. versionadded:: 0.9.5 ''' if salt.utils.platform.is_proxy(): return {} grains = {} if osdata['kernel'] == 'Linux' and os.path.exists('/sys/class/dmi/id'): # On many Linux distributions basic firmware information is available via sysfs # requires CONFIG_DMIID to be enabled in the Linux kernel configuration sysfs_firmware_info = { 'biosversion': 'bios_version', 'productname': 'product_name', 'manufacturer': 'sys_vendor', 'biosreleasedate': 'bios_date', 'uuid': 'product_uuid', 'serialnumber': 'product_serial' } for key, fw_file in sysfs_firmware_info.items(): contents_file = os.path.join('/sys/class/dmi/id', fw_file) if os.path.exists(contents_file): try: with salt.utils.files.fopen(contents_file, 'r') as ifile: grains[key] = salt.utils.stringutils.to_unicode(ifile.read().strip(), errors='replace') if key == 'uuid': grains['uuid'] = grains['uuid'].lower() except (IOError, OSError) as err: # PermissionError is new to Python 3, but corresponds to the EACESS and # EPERM error numbers. Use those instead here for PY2 compatibility. if err.errno == EACCES or err.errno == EPERM: # Skip the grain if non-root user has no access to the file. pass elif salt.utils.path.which_bin(['dmidecode', 'smbios']) is not None and not ( salt.utils.platform.is_smartos() or ( # SunOS on SPARC - 'smbios: failed to load SMBIOS: System does not export an SMBIOS table' osdata['kernel'] == 'SunOS' and osdata['cpuarch'].startswith('sparc') )): # On SmartOS (possibly SunOS also) smbios only works in the global zone # smbios is also not compatible with linux's smbios (smbios -s = print summarized) grains = { 'biosversion': __salt__['smbios.get']('bios-version'), 'productname': __salt__['smbios.get']('system-product-name'), 'manufacturer': __salt__['smbios.get']('system-manufacturer'), 'biosreleasedate': __salt__['smbios.get']('bios-release-date'), 'uuid': __salt__['smbios.get']('system-uuid') } grains = dict([(key, val) for key, val in grains.items() if val is not None]) uuid = __salt__['smbios.get']('system-uuid') if uuid is not None: grains['uuid'] = uuid.lower() for serial in ('system-serial-number', 'chassis-serial-number', 'baseboard-serial-number'): serial = __salt__['smbios.get'](serial) if serial is not None: grains['serialnumber'] = serial break elif salt.utils.path.which_bin(['fw_printenv']) is not None: # ARM Linux devices expose UBOOT env variables via fw_printenv hwdata = { 'manufacturer': 'manufacturer', 'serialnumber': 'serial#', 'productname': 'DeviceDesc', } for grain_name, cmd_key in six.iteritems(hwdata): result = __salt__['cmd.run_all']('fw_printenv {0}'.format(cmd_key)) if result['retcode'] == 0: uboot_keyval = result['stdout'].split('=') grains[grain_name] = _clean_value(grain_name, uboot_keyval[1]) elif osdata['kernel'] == 'FreeBSD': # On FreeBSD /bin/kenv (already in base system) # can be used instead of dmidecode kenv = salt.utils.path.which('kenv') if kenv: # In theory, it will be easier to add new fields to this later fbsd_hwdata = { 'biosversion': 'smbios.bios.version', 'manufacturer': 'smbios.system.maker', 'serialnumber': 'smbios.system.serial', 'productname': 'smbios.system.product', 'biosreleasedate': 'smbios.bios.reldate', 'uuid': 'smbios.system.uuid', } for key, val in six.iteritems(fbsd_hwdata): value = __salt__['cmd.run']('{0} {1}'.format(kenv, val)) grains[key] = _clean_value(key, value) elif osdata['kernel'] == 'OpenBSD': sysctl = salt.utils.path.which('sysctl') hwdata = {'biosversion': 'hw.version', 'manufacturer': 'hw.vendor', 'productname': 'hw.product', 'serialnumber': 'hw.serialno', 'uuid': 'hw.uuid'} for key, oid in six.iteritems(hwdata): value = __salt__['cmd.run']('{0} -n {1}'.format(sysctl, oid)) if not value.endswith(' value is not available'): grains[key] = _clean_value(key, value) elif osdata['kernel'] == 'NetBSD': sysctl = salt.utils.path.which('sysctl') nbsd_hwdata = { 'biosversion': 'machdep.dmi.board-version', 'manufacturer': 'machdep.dmi.system-vendor', 'serialnumber': 'machdep.dmi.system-serial', 'productname': 'machdep.dmi.system-product', 'biosreleasedate': 'machdep.dmi.bios-date', 'uuid': 'machdep.dmi.system-uuid', } for key, oid in six.iteritems(nbsd_hwdata): result = __salt__['cmd.run_all']('{0} -n {1}'.format(sysctl, oid)) if result['retcode'] == 0: grains[key] = _clean_value(key, result['stdout']) elif osdata['kernel'] == 'Darwin': grains['manufacturer'] = 'Apple Inc.' sysctl = salt.utils.path.which('sysctl') hwdata = {'productname': 'hw.model'} for key, oid in hwdata.items(): value = __salt__['cmd.run']('{0} -b {1}'.format(sysctl, oid)) if not value.endswith(' is invalid'): grains[key] = _clean_value(key, value) elif osdata['kernel'] == 'SunOS' and osdata['cpuarch'].startswith('sparc'): # Depending on the hardware model, commands can report different bits # of information. With that said, consolidate the output from various # commands and attempt various lookups. data = "" for (cmd, args) in (('/usr/sbin/prtdiag', '-v'), ('/usr/sbin/prtconf', '-vp'), ('/usr/sbin/virtinfo', '-a')): if salt.utils.path.which(cmd): # Also verifies that cmd is executable data += __salt__['cmd.run']('{0} {1}'.format(cmd, args)) data += '\n' sn_regexes = [ re.compile(r) for r in [ r'(?im)^\s*Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag r'(?im)^\s*chassis-sn:\s*(\S+)', # prtconf r'(?im)^\s*Chassis\s+Serial#:\s*(\S+)', # virtinfo ] ] obp_regexes = [ re.compile(r) for r in [ r'(?im)^\s*System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag r'(?im)^\s*version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf ] ] fw_regexes = [ re.compile(r) for r in [ r'(?im)^\s*Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag ] ] uuid_regexes = [ re.compile(r) for r in [ r'(?im)^\s*Domain\s+UUID:\s*(\S+)', # virtinfo ] ] manufacture_regexes = [ re.compile(r) for r in [ r'(?im)^\s*System\s+Configuration:\s*(.*)(?=sun)', # prtdiag ] ] product_regexes = [ re.compile(r) for r in [ r'(?im)^\s*System\s+Configuration:\s*.*?sun\d\S+[^\S\r\n]*(.*)', # prtdiag r'(?im)^[^\S\r\n]*banner-name:[^\S\r\n]*(.*)', # prtconf r'(?im)^[^\S\r\n]*product-name:[^\S\r\n]*(.*)', # prtconf ] ] sn_regexes = [ re.compile(r) for r in [ r'(?im)Chassis\s+Serial\s+Number\n-+\n(\S+)', # prtdiag r'(?i)Chassis\s+Serial#:\s*(\S+)', # virtinfo r'(?i)chassis-sn:\s*(\S+)', # prtconf ] ] obp_regexes = [ re.compile(r) for r in [ r'(?im)System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)', # prtdiag r'(?im)version:\s*\'OBP\s+(\S+)\s+(\S+)', # prtconf ] ] fw_regexes = [ re.compile(r) for r in [ r'(?i)Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)', # prtdiag ] ] uuid_regexes = [ re.compile(r) for r in [ r'(?i)Domain\s+UUID:\s+(\S+)', # virtinfo ] ] for regex in sn_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: grains['serialnumber'] = res.group(1).strip().replace("'", "") break for regex in obp_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: obp_rev, obp_date = res.groups()[0:2] # Limit the number in case we found the data in multiple places grains['biosversion'] = obp_rev.strip().replace("'", "") grains['biosreleasedate'] = obp_date.strip().replace("'", "") for regex in fw_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: fw_rev, fw_date = res.groups()[0:2] grains['systemfirmware'] = fw_rev.strip().replace("'", "") grains['systemfirmwaredate'] = fw_date.strip().replace("'", "") break for regex in uuid_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: grains['uuid'] = res.group(1).strip().replace("'", "") break for regex in manufacture_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: grains['manufacture'] = res.group(1).strip().replace("'", "") break for regex in product_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: t_productname = res.group(1).strip().replace("'", "") if t_productname: grains['product'] = t_productname grains['productname'] = t_productname break elif osdata['kernel'] == 'AIX': cmd = salt.utils.path.which('prtconf') if cmd: data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'), ('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')): for regex in [re.compile(r) for r in [regstring]]: res = regex.search(data) if res and len(res.groups()) >= 1: grains[dest] = res.group(1).strip().replace("'", '') product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')] for regex in product_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",") break else: log.error('The \'prtconf\' binary was not found in $PATH.') elif osdata['kernel'] == 'AIX': cmd = salt.utils.path.which('prtconf') if data: data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'), ('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')): for regex in [re.compile(r) for r in [regstring]]: res = regex.search(data) if res and len(res.groups()) >= 1: grains[dest] = res.group(1).strip().replace("'", '') product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')] for regex in product_regexes: res = regex.search(data) if res and len(res.groups()) >= 1: grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",") break else: log.error('The \'prtconf\' binary was not found in $PATH.') return grains def _get_hash_by_shell(): ''' Shell-out Python 3 for compute reliable hash :return: ''' id_ = __opts__.get('id', '') id_hash = None py_ver = sys.version_info[:2] if py_ver >= (3, 3): # Python 3.3 enabled hash randomization, so we need to shell out to get # a reliable hash. id_hash = __salt__['cmd.run']([sys.executable, '-c', 'print(hash("{0}"))'.format(id_)], env={'PYTHONHASHSEED': '0'}) try: id_hash = int(id_hash) except (TypeError, ValueError): log.debug('Failed to hash the ID to get the server_id grain. Result of hash command: %s', id_hash) id_hash = None if id_hash is None: # Python < 3.3 or error encountered above id_hash = hash(id_) return abs(id_hash % (2 ** 31)) def get_server_id(): ''' Provides an integer based on the FQDN of a machine. Useful as server-id in MySQL replication or anywhere else you'll need an ID like this. ''' # Provides: # server_id if salt.utils.platform.is_proxy(): server_id = {} else: use_crc = __opts__.get('server_id_use_crc') if bool(use_crc): id_hash = getattr(zlib, use_crc, zlib.adler32)(__opts__.get('id', '').encode()) & 0xffffffff else: log.debug('This server_id is computed not by Adler32 nor by CRC32. ' 'Please use "server_id_use_crc" option and define algorithm you ' 'prefer (default "Adler32"). Starting with Sodium, the ' 'server_id will be computed with Adler32 by default.') id_hash = _get_hash_by_shell() server_id = {'server_id': id_hash} return server_id def get_master(): ''' Provides the minion with the name of its master. This is useful in states to target other services running on the master. ''' # Provides: # master return {'master': __opts__.get('master', '')} def default_gateway(): ''' Populates grains which describe whether a server has a default gateway configured or not. Uses `ip -4 route show` and `ip -6 route show` and greps for a `default` at the beginning of any line. Assuming the standard `default via <ip>` format for default gateways, it will also parse out the ip address of the default gateway, and put it in ip4_gw or ip6_gw. If the `ip` command is unavailable, no grains will be populated. Currently does not support multiple default gateways. The grains will be set to the first default gateway found. List of grains: ip4_gw: True # ip/True/False if default ipv4 gateway ip6_gw: True # ip/True/False if default ipv6 gateway ip_gw: True # True if either of the above is True, False otherwise ''' grains = {} ip_bin = salt.utils.path.which('ip') if not ip_bin: return {} grains['ip_gw'] = False grains['ip4_gw'] = False grains['ip6_gw'] = False for ip_version in ('4', '6'): try: out = __salt__['cmd.run']([ip_bin, '-' + ip_version, 'route', 'show']) for line in out.splitlines(): if line.startswith('default'): grains['ip_gw'] = True grains['ip{0}_gw'.format(ip_version)] = True try: via, gw_ip = line.split()[1:3] except ValueError: pass else: if via == 'via': grains['ip{0}_gw'.format(ip_version)] = gw_ip break except Exception: continue return grains
saltstack/salt
salt/modules/osquery.py
_table_attrs
python
def _table_attrs(table): ''' Helper function to find valid table attributes ''' cmd = ['osqueryi'] + ['--json'] + ['pragma table_info({0})'.format(table)] res = __salt__['cmd.run_all'](cmd) if res['retcode'] == 0: attrs = [] text = salt.utils.json.loads(res['stdout']) for item in text: attrs.append(item['name']) return attrs return False
Helper function to find valid table attributes
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/osquery.py#L36-L48
null
# -*- coding: utf-8 -*- ''' Support for OSQuery - https://osquery.io. .. versionadded:: 2015.8.0 ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import logging # Import Salt libs import salt.utils.json import salt.utils.path import salt.utils.platform log = logging.getLogger(__name__) __func_alias__ = { 'file_': 'file', 'hash_': 'hash', 'time_': 'time', } __virtualname__ = 'osquery' def __virtual__(): if salt.utils.path.which('osqueryi'): return __virtualname__ return (False, 'The osquery execution module cannot be loaded: ' 'osqueryi binary is not in the path.') def _osquery(sql, format='json'): ''' Helper function to run raw osquery queries ''' ret = { 'result': True, } cmd = ['osqueryi'] + ['--json'] + [sql] res = __salt__['cmd.run_all'](cmd) if res['stderr']: ret['result'] = False ret['error'] = res['stderr'] else: ret['data'] = salt.utils.json.loads(res['stdout']) log.debug('== %s ==', ret) return ret def _osquery_cmd(table, attrs=None, where=None, format='json'): ''' Helper function to run osquery queries ''' ret = { 'result': True, } if attrs: if isinstance(attrs, list): valid_attrs = _table_attrs(table) if valid_attrs: for a in attrs: if a not in valid_attrs: ret['result'] = False ret['comment'] = '{0} is not a valid attribute for table {1}'.format(a, table) return ret _attrs = ','.join(attrs) else: ret['result'] = False ret['comment'] = 'Invalid table {0}.'.format(table) return ret else: ret['comment'] = 'attrs must be specified as a list.' ret['result'] = False return ret else: _attrs = '*' sql = 'select {0} from {1}'.format(_attrs, table) if where: sql = '{0} where {1}'.format(sql, where) sql = '{0};'.format(sql) res = _osquery(sql) if res['result']: ret['data'] = res['data'] else: ret['comment'] = res['error'] return ret def version(): ''' Return version of osquery CLI Example: .. code-block:: bash salt '*' osquery.version ''' _false_return = {'result': False, 'comment': 'OSQuery version unavailable.'} res = _osquery_cmd(table='osquery_info', attrs=['version']) if 'result' in res and res['result']: if 'data' in res and isinstance(res['data'], list): return res['data'][0].get('version', '') or _false_return return _false_return def rpm_packages(attrs=None, where=None): ''' Return cpuid information from osquery CLI Example: .. code-block:: bash salt '*' osquery.rpm_packages ''' if __grains__['os_family'] == 'RedHat': return _osquery_cmd(table='rpm_packages', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat based systems.'} def kernel_integrity(attrs=None, where=None): ''' Return kernel_integrity information from osquery CLI Example: .. code-block:: bash salt '*' osquery.kernel_integrity ''' if __grains__['os_family'] in ['RedHat', 'Debian']: return _osquery_cmd(table='kernel_integrity', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat or Debian based systems.'} def kernel_modules(attrs=None, where=None): ''' Return kernel_modules information from osquery CLI Example: .. code-block:: bash salt '*' osquery.kernel_modules ''' if __grains__['os_family'] in ['RedHat', 'Debian']: return _osquery_cmd(table='kernel_modules', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat or Debian based systems.'} def memory_map(attrs=None, where=None): ''' Return memory_map information from osquery CLI Example: .. code-block:: bash salt '*' osquery.memory_map ''' if __grains__['os_family'] in ['RedHat', 'Debian']: return _osquery_cmd(table='memory_map', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat or Debian based systems.'} def process_memory_map(attrs=None, where=None): ''' Return process_memory_map information from osquery CLI Example: .. code-block:: bash salt '*' osquery.process_memory_map ''' if __grains__['os_family'] in ['RedHat', 'Debian']: return _osquery_cmd(table='process_memory_map', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat or Debian based systems.'} def shared_memory(attrs=None, where=None): ''' Return shared_memory information from osquery CLI Example: .. code-block:: bash salt '*' osquery.shared_memory ''' if __grains__['os_family'] in ['RedHat', 'Debian']: return _osquery_cmd(table='shared_memory', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat or Debian based systems.'} def apt_sources(attrs=None, where=None): ''' Return apt_sources information from osquery CLI Example: .. code-block:: bash salt '*' osquery.apt_sources ''' if __grains__['os_family'] == 'Debian': return _osquery_cmd(table='apt_sources', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Debian based systems.'} def deb_packages(attrs=None, where=None): ''' Return deb_packages information from osquery CLI Example: .. code-block:: bash salt '*' osquery.deb_packages ''' if __grains__['os_family'] == 'Debian': return _osquery_cmd(table='deb_packages', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Debian based systems.'} def acpi_tables(attrs=None, where=None): ''' Return acpi_tables information from osquery CLI Example: .. code-block:: bash salt '*' osquery.acpi_tables ''' return _osquery_cmd(table='acpi_tables', attrs=attrs, where=where) def arp_cache(attrs=None, where=None): ''' Return arp_cache information from osquery CLI Example: .. code-block:: bash salt '*' osquery.arp_cache ''' return _osquery_cmd(table='arp_cache', attrs=attrs, where=where) def block_devices(attrs=None, where=None): ''' Return block_devices information from osquery CLI Example: .. code-block:: bash salt '*' osquery.block_devices ''' return _osquery_cmd(table='block_devices', attrs=attrs, where=where) def cpuid(attrs=None, where=None): ''' Return cpuid information from osquery CLI Example: .. code-block:: bash salt '*' osquery.cpuid ''' return _osquery_cmd(table='cpuid', attrs=attrs, where=where) def crontab(attrs=None, where=None): ''' Return crontab information from osquery CLI Example: .. code-block:: bash salt '*' osquery.crontab ''' return _osquery_cmd(table='crontab', attrs=attrs, where=where) def etc_hosts(attrs=None, where=None): ''' Return etc_hosts information from osquery CLI Example: .. code-block:: bash salt '*' osquery.etc_hosts ''' return _osquery_cmd(table='etc_hosts', attrs=attrs, where=where) def etc_services(attrs=None, where=None): ''' Return etc_services information from osquery CLI Example: .. code-block:: bash salt '*' osquery.etc_services ''' return _osquery_cmd(table='etc_services', attrs=attrs, where=where) def file_changes(attrs=None, where=None): ''' Return file_changes information from osquery CLI Example: .. code-block:: bash salt '*' osquery.file_changes ''' return _osquery_cmd(table='file_changes', attrs=attrs, where=where) def groups(attrs=None, where=None): ''' Return groups information from osquery CLI Example: .. code-block:: bash salt '*' osquery.groups ''' return _osquery_cmd(table='groups', attrs=attrs, where=where) def hardware_events(attrs=None, where=None): ''' Return hardware_events information from osquery CLI Example: .. code-block:: bash salt '*' osquery.hardware_events ''' return _osquery_cmd(table='hardware_events', attrs=attrs, where=where) def interface_addresses(attrs=None, where=None): ''' Return interface_addresses information from osquery CLI Example: .. code-block:: bash salt '*' osquery.interface_addresses ''' return _osquery_cmd(table='interface_addresses', attrs=attrs, where=where) def interface_details(attrs=None, where=None): ''' Return interface_details information from osquery CLI Example: .. code-block:: bash salt '*' osquery.interface_details ''' return _osquery_cmd(table='interface_details', attrs=attrs, where=where) def kernel_info(attrs=None, where=None): ''' Return kernel_info information from osquery CLI Example: .. code-block:: bash salt '*' osquery.kernel_info ''' return _osquery_cmd(table='kernel_info', attrs=attrs, where=where) def last(attrs=None, where=None): ''' Return last information from osquery CLI Example: .. code-block:: bash salt '*' osquery.last ''' return _osquery_cmd(table='last', attrs=attrs, where=where) def listening_ports(attrs=None, where=None): r''' Return listening_ports information from osquery CLI Example: .. code-block:: bash salt '*' osquery.listening_ports ''' return _osquery_cmd(table='listening_ports', attrs=attrs, where=where) def logged_in_users(attrs=None, where=None): r''' Return logged_in_users information from osquery CLI Example: .. code-block:: bash salt '*' osquery.logged_in_users ''' return _osquery_cmd(table='logged_in_users', attrs=attrs, where=where) def mounts(attrs=None, where=None): r''' Return mounts information from osquery CLI Example: .. code-block:: bash salt '*' osquery.mounts ''' return _osquery_cmd(table='mounts', attrs=attrs, where=where) def os_version(attrs=None, where=None): ''' Return os_version information from osquery CLI Example: .. code-block:: bash salt '*' osquery.os_version ''' return _osquery_cmd(table='os_version', attrs=attrs, where=where) def passwd_changes(attrs=None, where=None): ''' Return passwd_changes information from osquery CLI Example: .. code-block:: bash salt '*' osquery.passwd_changes ''' return _osquery_cmd(table='passwd_changes', attrs=attrs, where=where) def pci_devices(attrs=None, where=None): ''' Return pci_devices information from osquery CLI Example: .. code-block:: bash salt '*' osquery.pci_devices ''' return _osquery_cmd(table='pci_devices', attrs=attrs, where=where) def process_envs(attrs=None, where=None): ''' Return process_envs information from osquery CLI Example: .. code-block:: bash salt '*' osquery.process_envs ''' return _osquery_cmd(table='process_envs', attrs=attrs, where=where) def process_open_files(attrs=None, where=None): ''' Return process_open_files information from osquery CLI Example: .. code-block:: bash salt '*' osquery.process_open_files ''' return _osquery_cmd(table='process_open_files', attrs=attrs, where=where) def process_open_sockets(attrs=None, where=None): ''' Return process_open_sockets information from osquery CLI Example: .. code-block:: bash salt '*' osquery.process_open_sockets ''' return _osquery_cmd(table='process_open_sockets', attrs=attrs, where=where) def processes(attrs=None, where=None): ''' Return processes information from osquery CLI Example: .. code-block:: bash salt '*' osquery.processes ''' return _osquery_cmd(table='processes', attrs=attrs, where=where) def routes(attrs=None, where=None): ''' Return routes information from osquery CLI Example: .. code-block:: bash salt '*' osquery.routes ''' return _osquery_cmd(table='routes', attrs=attrs, where=where) def shell_history(attrs=None, where=None): ''' Return shell_history information from osquery CLI Example: .. code-block:: bash salt '*' osquery.shell_history ''' return _osquery_cmd(table='shell_history', attrs=attrs, where=where) def smbios_tables(attrs=None, where=None): ''' Return smbios_tables information from osquery CLI Example: .. code-block:: bash salt '*' osquery.smbios_tables ''' return _osquery_cmd(table='smbios_tables', attrs=attrs, where=where) def suid_bin(attrs=None, where=None): ''' Return suid_bin information from osquery CLI Example: .. code-block:: bash salt '*' osquery.suid_bin ''' return _osquery_cmd(table='suid_bin', attrs=attrs, where=where) def system_controls(attrs=None, where=None): ''' Return system_controls information from osquery CLI Example: .. code-block:: bash salt '*' osquery.system_controls ''' return _osquery_cmd(table='system_controls', attrs=attrs, where=where) def usb_devices(attrs=None, where=None): ''' Return usb_devices information from osquery CLI Example: .. code-block:: bash salt '*' osquery.usb_devices ''' return _osquery_cmd(table='usb_devices', attrs=attrs, where=where) def users(attrs=None, where=None): ''' Return users information from osquery CLI Example: .. code-block:: bash salt '*' osquery.users ''' return _osquery_cmd(table='users', attrs=attrs, where=where) def alf(attrs=None, where=None): ''' Return alf information from osquery CLI Example: .. code-block:: bash salt '*' osquery.alf ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='alf', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def alf_exceptions(attrs=None, where=None): ''' Return alf_exceptions information from osquery CLI Example: .. code-block:: bash salt '*' osquery.alf_exceptions ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='alf_exceptions', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def alf_explicit_auths(attrs=None, where=None): ''' Return alf_explicit_auths information from osquery CLI Example: .. code-block:: bash salt '*' osquery.alf_explicit_auths ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='alf_explicit_auths', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def alf_services(attrs=None, where=None): ''' Return alf_services information from osquery CLI Example: .. code-block:: bash salt '*' osquery.alf_services ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='alf_services', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def apps(attrs=None, where=None): ''' Return apps information from osquery CLI Example: .. code-block:: bash salt '*' osquery.apps ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='apps', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def certificates(attrs=None, where=None): ''' Return certificates information from osquery CLI Example: .. code-block:: bash salt '*' osquery.certificates ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='certificates', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def chrome_extensions(attrs=None, where=None): ''' Return chrome_extensions information from osquery CLI Example: .. code-block:: bash salt '*' osquery.chrome_extensions ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='chrome_extensions', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def firefox_addons(attrs=None, where=None): ''' Return firefox_addons information from osquery CLI Example: .. code-block:: bash salt '*' osquery.firefox_addons ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='firefox_addons', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def homebrew_packages(attrs=None, where=None): ''' Return homebrew_packages information from osquery CLI Example: .. code-block:: bash salt '*' osquery.homebrew_packages ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='homebrew_packages', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def iokit_devicetree(attrs=None, where=None): ''' Return iokit_devicetree information from osquery CLI Example: .. code-block:: bash salt '*' osquery.iokit_devicetree ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='iokit_devicetree', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def iokit_registry(attrs=None, where=None): ''' Return iokit_registry information from osquery CLI Example: .. code-block:: bash salt '*' osquery.iokit_registry ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='iokit_registry', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def kernel_extensions(attrs=None, where=None): ''' Return kernel_extensions information from osquery CLI Example: .. code-block:: bash salt '*' osquery.kernel_extensions ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='kernel_extensions', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def keychain_items(attrs=None, where=None): ''' Return keychain_items information from osquery CLI Example: .. code-block:: bash salt '*' osquery.keychain_items ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='keychain_items', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def launchd(attrs=None, where=None): ''' Return launchd information from osquery CLI Example: .. code-block:: bash salt '*' osquery.launchd ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='launchd', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def nfs_shares(attrs=None, where=None): ''' Return nfs_shares information from osquery CLI Example: .. code-block:: bash salt '*' osquery.nfs_shares ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='nfs_shares', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def nvram(attrs=None, where=None): ''' Return nvram information from osquery CLI Example: .. code-block:: bash salt '*' osquery.nvram ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='nvram', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def preferences(attrs=None, where=None): ''' Return preferences information from osquery CLI Example: .. code-block:: bash salt '*' osquery.preferences ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='preferences', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def quarantine(attrs=None, where=None): ''' Return quarantine information from osquery CLI Example: .. code-block:: bash salt '*' osquery.quarantine ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='quarantine', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def safari_extensions(attrs=None, where=None): ''' Return safari_extensions information from osquery CLI Example: .. code-block:: bash salt '*' osquery.safari_extensions ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='safari_extensions', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def startup_items(attrs=None, where=None): ''' Return startup_items information from osquery CLI Example: .. code-block:: bash salt '*' osquery.startup_items ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='startup_items', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def xattr_where_from(attrs=None, where=None): ''' Return xattr_where_from information from osquery CLI Example: .. code-block:: bash salt '*' osquery.xattr_where_from ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='xattr_where_from', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def xprotect_entries(attrs=None, where=None): ''' Return xprotect_entries information from osquery CLI Example: .. code-block:: bash salt '*' osquery.xprotect_entries ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='xprotect_entries', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def xprotect_reports(attrs=None, where=None): ''' Return xprotect_reports information from osquery CLI Example: .. code-block:: bash salt '*' osquery.xprotect_reports ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='xprotect_reports', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def file_(attrs=None, where=None): ''' Return file information from osquery CLI Example: .. code-block:: bash salt '*' osquery.file ''' return _osquery_cmd(table='file', attrs=attrs, where=where) def hash_(attrs=None, where=None): ''' Return hash information from osquery CLI Example: .. code-block:: bash salt '*' osquery.hash ''' return _osquery_cmd(table='hash', attrs=attrs, where=where) def osquery_extensions(attrs=None, where=None): ''' Return osquery_extensions information from osquery CLI Example: .. code-block:: bash salt '*' osquery.osquery_extensions ''' return _osquery_cmd(table='osquery_extensions', attrs=attrs, where=where) def osquery_flags(attrs=None, where=None): ''' Return osquery_flags information from osquery CLI Example: .. code-block:: bash salt '*' osquery.osquery_flags ''' return _osquery_cmd(table='osquery_flags', attrs=attrs, where=where) def osquery_info(attrs=None, where=None): ''' Return osquery_info information from osquery CLI Example: .. code-block:: bash salt '*' osquery.osquery_info ''' return _osquery_cmd(table='osquery_info', attrs=attrs, where=where) def osquery_registry(attrs=None, where=None): ''' Return osquery_registry information from osquery CLI Example: .. code-block:: bash salt '*' osquery.osquery_registry ''' return _osquery_cmd(table='osquery_registry', attrs=attrs, where=where) def time_(attrs=None): ''' Return time information from osquery CLI Example: .. code-block:: bash salt '*' osquery.time ''' return _osquery_cmd(table='time', attrs=attrs) def query(sql=None): ''' Return time information from osquery CLI Example: .. code-block:: bash salt '*' osquery.query "select * from users;" ''' return _osquery(sql)
saltstack/salt
salt/modules/osquery.py
_osquery
python
def _osquery(sql, format='json'): ''' Helper function to run raw osquery queries ''' ret = { 'result': True, } cmd = ['osqueryi'] + ['--json'] + [sql] res = __salt__['cmd.run_all'](cmd) if res['stderr']: ret['result'] = False ret['error'] = res['stderr'] else: ret['data'] = salt.utils.json.loads(res['stdout']) log.debug('== %s ==', ret) return ret
Helper function to run raw osquery queries
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/osquery.py#L51-L67
[ "def loads(s, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.loads and prevents a traceback in the event that a bytestring is\n passed to the function. (Python < 3.6 cannot load bytestrings)\n\n You can pass an alternate json module (loaded via import_json() above)\n using the _json_module argument)\n '''\n json_module = kwargs.pop('_json_module', json)\n try:\n return json_module.loads(s, **kwargs)\n except TypeError as exc:\n # json.loads cannot load bytestrings in Python < 3.6\n if six.PY3 and isinstance(s, bytes):\n return json_module.loads(salt.utils.stringutils.to_unicode(s), **kwargs)\n else:\n raise exc\n" ]
# -*- coding: utf-8 -*- ''' Support for OSQuery - https://osquery.io. .. versionadded:: 2015.8.0 ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import logging # Import Salt libs import salt.utils.json import salt.utils.path import salt.utils.platform log = logging.getLogger(__name__) __func_alias__ = { 'file_': 'file', 'hash_': 'hash', 'time_': 'time', } __virtualname__ = 'osquery' def __virtual__(): if salt.utils.path.which('osqueryi'): return __virtualname__ return (False, 'The osquery execution module cannot be loaded: ' 'osqueryi binary is not in the path.') def _table_attrs(table): ''' Helper function to find valid table attributes ''' cmd = ['osqueryi'] + ['--json'] + ['pragma table_info({0})'.format(table)] res = __salt__['cmd.run_all'](cmd) if res['retcode'] == 0: attrs = [] text = salt.utils.json.loads(res['stdout']) for item in text: attrs.append(item['name']) return attrs return False def _osquery_cmd(table, attrs=None, where=None, format='json'): ''' Helper function to run osquery queries ''' ret = { 'result': True, } if attrs: if isinstance(attrs, list): valid_attrs = _table_attrs(table) if valid_attrs: for a in attrs: if a not in valid_attrs: ret['result'] = False ret['comment'] = '{0} is not a valid attribute for table {1}'.format(a, table) return ret _attrs = ','.join(attrs) else: ret['result'] = False ret['comment'] = 'Invalid table {0}.'.format(table) return ret else: ret['comment'] = 'attrs must be specified as a list.' ret['result'] = False return ret else: _attrs = '*' sql = 'select {0} from {1}'.format(_attrs, table) if where: sql = '{0} where {1}'.format(sql, where) sql = '{0};'.format(sql) res = _osquery(sql) if res['result']: ret['data'] = res['data'] else: ret['comment'] = res['error'] return ret def version(): ''' Return version of osquery CLI Example: .. code-block:: bash salt '*' osquery.version ''' _false_return = {'result': False, 'comment': 'OSQuery version unavailable.'} res = _osquery_cmd(table='osquery_info', attrs=['version']) if 'result' in res and res['result']: if 'data' in res and isinstance(res['data'], list): return res['data'][0].get('version', '') or _false_return return _false_return def rpm_packages(attrs=None, where=None): ''' Return cpuid information from osquery CLI Example: .. code-block:: bash salt '*' osquery.rpm_packages ''' if __grains__['os_family'] == 'RedHat': return _osquery_cmd(table='rpm_packages', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat based systems.'} def kernel_integrity(attrs=None, where=None): ''' Return kernel_integrity information from osquery CLI Example: .. code-block:: bash salt '*' osquery.kernel_integrity ''' if __grains__['os_family'] in ['RedHat', 'Debian']: return _osquery_cmd(table='kernel_integrity', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat or Debian based systems.'} def kernel_modules(attrs=None, where=None): ''' Return kernel_modules information from osquery CLI Example: .. code-block:: bash salt '*' osquery.kernel_modules ''' if __grains__['os_family'] in ['RedHat', 'Debian']: return _osquery_cmd(table='kernel_modules', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat or Debian based systems.'} def memory_map(attrs=None, where=None): ''' Return memory_map information from osquery CLI Example: .. code-block:: bash salt '*' osquery.memory_map ''' if __grains__['os_family'] in ['RedHat', 'Debian']: return _osquery_cmd(table='memory_map', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat or Debian based systems.'} def process_memory_map(attrs=None, where=None): ''' Return process_memory_map information from osquery CLI Example: .. code-block:: bash salt '*' osquery.process_memory_map ''' if __grains__['os_family'] in ['RedHat', 'Debian']: return _osquery_cmd(table='process_memory_map', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat or Debian based systems.'} def shared_memory(attrs=None, where=None): ''' Return shared_memory information from osquery CLI Example: .. code-block:: bash salt '*' osquery.shared_memory ''' if __grains__['os_family'] in ['RedHat', 'Debian']: return _osquery_cmd(table='shared_memory', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat or Debian based systems.'} def apt_sources(attrs=None, where=None): ''' Return apt_sources information from osquery CLI Example: .. code-block:: bash salt '*' osquery.apt_sources ''' if __grains__['os_family'] == 'Debian': return _osquery_cmd(table='apt_sources', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Debian based systems.'} def deb_packages(attrs=None, where=None): ''' Return deb_packages information from osquery CLI Example: .. code-block:: bash salt '*' osquery.deb_packages ''' if __grains__['os_family'] == 'Debian': return _osquery_cmd(table='deb_packages', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Debian based systems.'} def acpi_tables(attrs=None, where=None): ''' Return acpi_tables information from osquery CLI Example: .. code-block:: bash salt '*' osquery.acpi_tables ''' return _osquery_cmd(table='acpi_tables', attrs=attrs, where=where) def arp_cache(attrs=None, where=None): ''' Return arp_cache information from osquery CLI Example: .. code-block:: bash salt '*' osquery.arp_cache ''' return _osquery_cmd(table='arp_cache', attrs=attrs, where=where) def block_devices(attrs=None, where=None): ''' Return block_devices information from osquery CLI Example: .. code-block:: bash salt '*' osquery.block_devices ''' return _osquery_cmd(table='block_devices', attrs=attrs, where=where) def cpuid(attrs=None, where=None): ''' Return cpuid information from osquery CLI Example: .. code-block:: bash salt '*' osquery.cpuid ''' return _osquery_cmd(table='cpuid', attrs=attrs, where=where) def crontab(attrs=None, where=None): ''' Return crontab information from osquery CLI Example: .. code-block:: bash salt '*' osquery.crontab ''' return _osquery_cmd(table='crontab', attrs=attrs, where=where) def etc_hosts(attrs=None, where=None): ''' Return etc_hosts information from osquery CLI Example: .. code-block:: bash salt '*' osquery.etc_hosts ''' return _osquery_cmd(table='etc_hosts', attrs=attrs, where=where) def etc_services(attrs=None, where=None): ''' Return etc_services information from osquery CLI Example: .. code-block:: bash salt '*' osquery.etc_services ''' return _osquery_cmd(table='etc_services', attrs=attrs, where=where) def file_changes(attrs=None, where=None): ''' Return file_changes information from osquery CLI Example: .. code-block:: bash salt '*' osquery.file_changes ''' return _osquery_cmd(table='file_changes', attrs=attrs, where=where) def groups(attrs=None, where=None): ''' Return groups information from osquery CLI Example: .. code-block:: bash salt '*' osquery.groups ''' return _osquery_cmd(table='groups', attrs=attrs, where=where) def hardware_events(attrs=None, where=None): ''' Return hardware_events information from osquery CLI Example: .. code-block:: bash salt '*' osquery.hardware_events ''' return _osquery_cmd(table='hardware_events', attrs=attrs, where=where) def interface_addresses(attrs=None, where=None): ''' Return interface_addresses information from osquery CLI Example: .. code-block:: bash salt '*' osquery.interface_addresses ''' return _osquery_cmd(table='interface_addresses', attrs=attrs, where=where) def interface_details(attrs=None, where=None): ''' Return interface_details information from osquery CLI Example: .. code-block:: bash salt '*' osquery.interface_details ''' return _osquery_cmd(table='interface_details', attrs=attrs, where=where) def kernel_info(attrs=None, where=None): ''' Return kernel_info information from osquery CLI Example: .. code-block:: bash salt '*' osquery.kernel_info ''' return _osquery_cmd(table='kernel_info', attrs=attrs, where=where) def last(attrs=None, where=None): ''' Return last information from osquery CLI Example: .. code-block:: bash salt '*' osquery.last ''' return _osquery_cmd(table='last', attrs=attrs, where=where) def listening_ports(attrs=None, where=None): r''' Return listening_ports information from osquery CLI Example: .. code-block:: bash salt '*' osquery.listening_ports ''' return _osquery_cmd(table='listening_ports', attrs=attrs, where=where) def logged_in_users(attrs=None, where=None): r''' Return logged_in_users information from osquery CLI Example: .. code-block:: bash salt '*' osquery.logged_in_users ''' return _osquery_cmd(table='logged_in_users', attrs=attrs, where=where) def mounts(attrs=None, where=None): r''' Return mounts information from osquery CLI Example: .. code-block:: bash salt '*' osquery.mounts ''' return _osquery_cmd(table='mounts', attrs=attrs, where=where) def os_version(attrs=None, where=None): ''' Return os_version information from osquery CLI Example: .. code-block:: bash salt '*' osquery.os_version ''' return _osquery_cmd(table='os_version', attrs=attrs, where=where) def passwd_changes(attrs=None, where=None): ''' Return passwd_changes information from osquery CLI Example: .. code-block:: bash salt '*' osquery.passwd_changes ''' return _osquery_cmd(table='passwd_changes', attrs=attrs, where=where) def pci_devices(attrs=None, where=None): ''' Return pci_devices information from osquery CLI Example: .. code-block:: bash salt '*' osquery.pci_devices ''' return _osquery_cmd(table='pci_devices', attrs=attrs, where=where) def process_envs(attrs=None, where=None): ''' Return process_envs information from osquery CLI Example: .. code-block:: bash salt '*' osquery.process_envs ''' return _osquery_cmd(table='process_envs', attrs=attrs, where=where) def process_open_files(attrs=None, where=None): ''' Return process_open_files information from osquery CLI Example: .. code-block:: bash salt '*' osquery.process_open_files ''' return _osquery_cmd(table='process_open_files', attrs=attrs, where=where) def process_open_sockets(attrs=None, where=None): ''' Return process_open_sockets information from osquery CLI Example: .. code-block:: bash salt '*' osquery.process_open_sockets ''' return _osquery_cmd(table='process_open_sockets', attrs=attrs, where=where) def processes(attrs=None, where=None): ''' Return processes information from osquery CLI Example: .. code-block:: bash salt '*' osquery.processes ''' return _osquery_cmd(table='processes', attrs=attrs, where=where) def routes(attrs=None, where=None): ''' Return routes information from osquery CLI Example: .. code-block:: bash salt '*' osquery.routes ''' return _osquery_cmd(table='routes', attrs=attrs, where=where) def shell_history(attrs=None, where=None): ''' Return shell_history information from osquery CLI Example: .. code-block:: bash salt '*' osquery.shell_history ''' return _osquery_cmd(table='shell_history', attrs=attrs, where=where) def smbios_tables(attrs=None, where=None): ''' Return smbios_tables information from osquery CLI Example: .. code-block:: bash salt '*' osquery.smbios_tables ''' return _osquery_cmd(table='smbios_tables', attrs=attrs, where=where) def suid_bin(attrs=None, where=None): ''' Return suid_bin information from osquery CLI Example: .. code-block:: bash salt '*' osquery.suid_bin ''' return _osquery_cmd(table='suid_bin', attrs=attrs, where=where) def system_controls(attrs=None, where=None): ''' Return system_controls information from osquery CLI Example: .. code-block:: bash salt '*' osquery.system_controls ''' return _osquery_cmd(table='system_controls', attrs=attrs, where=where) def usb_devices(attrs=None, where=None): ''' Return usb_devices information from osquery CLI Example: .. code-block:: bash salt '*' osquery.usb_devices ''' return _osquery_cmd(table='usb_devices', attrs=attrs, where=where) def users(attrs=None, where=None): ''' Return users information from osquery CLI Example: .. code-block:: bash salt '*' osquery.users ''' return _osquery_cmd(table='users', attrs=attrs, where=where) def alf(attrs=None, where=None): ''' Return alf information from osquery CLI Example: .. code-block:: bash salt '*' osquery.alf ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='alf', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def alf_exceptions(attrs=None, where=None): ''' Return alf_exceptions information from osquery CLI Example: .. code-block:: bash salt '*' osquery.alf_exceptions ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='alf_exceptions', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def alf_explicit_auths(attrs=None, where=None): ''' Return alf_explicit_auths information from osquery CLI Example: .. code-block:: bash salt '*' osquery.alf_explicit_auths ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='alf_explicit_auths', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def alf_services(attrs=None, where=None): ''' Return alf_services information from osquery CLI Example: .. code-block:: bash salt '*' osquery.alf_services ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='alf_services', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def apps(attrs=None, where=None): ''' Return apps information from osquery CLI Example: .. code-block:: bash salt '*' osquery.apps ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='apps', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def certificates(attrs=None, where=None): ''' Return certificates information from osquery CLI Example: .. code-block:: bash salt '*' osquery.certificates ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='certificates', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def chrome_extensions(attrs=None, where=None): ''' Return chrome_extensions information from osquery CLI Example: .. code-block:: bash salt '*' osquery.chrome_extensions ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='chrome_extensions', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def firefox_addons(attrs=None, where=None): ''' Return firefox_addons information from osquery CLI Example: .. code-block:: bash salt '*' osquery.firefox_addons ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='firefox_addons', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def homebrew_packages(attrs=None, where=None): ''' Return homebrew_packages information from osquery CLI Example: .. code-block:: bash salt '*' osquery.homebrew_packages ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='homebrew_packages', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def iokit_devicetree(attrs=None, where=None): ''' Return iokit_devicetree information from osquery CLI Example: .. code-block:: bash salt '*' osquery.iokit_devicetree ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='iokit_devicetree', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def iokit_registry(attrs=None, where=None): ''' Return iokit_registry information from osquery CLI Example: .. code-block:: bash salt '*' osquery.iokit_registry ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='iokit_registry', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def kernel_extensions(attrs=None, where=None): ''' Return kernel_extensions information from osquery CLI Example: .. code-block:: bash salt '*' osquery.kernel_extensions ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='kernel_extensions', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def keychain_items(attrs=None, where=None): ''' Return keychain_items information from osquery CLI Example: .. code-block:: bash salt '*' osquery.keychain_items ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='keychain_items', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def launchd(attrs=None, where=None): ''' Return launchd information from osquery CLI Example: .. code-block:: bash salt '*' osquery.launchd ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='launchd', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def nfs_shares(attrs=None, where=None): ''' Return nfs_shares information from osquery CLI Example: .. code-block:: bash salt '*' osquery.nfs_shares ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='nfs_shares', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def nvram(attrs=None, where=None): ''' Return nvram information from osquery CLI Example: .. code-block:: bash salt '*' osquery.nvram ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='nvram', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def preferences(attrs=None, where=None): ''' Return preferences information from osquery CLI Example: .. code-block:: bash salt '*' osquery.preferences ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='preferences', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def quarantine(attrs=None, where=None): ''' Return quarantine information from osquery CLI Example: .. code-block:: bash salt '*' osquery.quarantine ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='quarantine', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def safari_extensions(attrs=None, where=None): ''' Return safari_extensions information from osquery CLI Example: .. code-block:: bash salt '*' osquery.safari_extensions ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='safari_extensions', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def startup_items(attrs=None, where=None): ''' Return startup_items information from osquery CLI Example: .. code-block:: bash salt '*' osquery.startup_items ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='startup_items', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def xattr_where_from(attrs=None, where=None): ''' Return xattr_where_from information from osquery CLI Example: .. code-block:: bash salt '*' osquery.xattr_where_from ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='xattr_where_from', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def xprotect_entries(attrs=None, where=None): ''' Return xprotect_entries information from osquery CLI Example: .. code-block:: bash salt '*' osquery.xprotect_entries ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='xprotect_entries', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def xprotect_reports(attrs=None, where=None): ''' Return xprotect_reports information from osquery CLI Example: .. code-block:: bash salt '*' osquery.xprotect_reports ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='xprotect_reports', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def file_(attrs=None, where=None): ''' Return file information from osquery CLI Example: .. code-block:: bash salt '*' osquery.file ''' return _osquery_cmd(table='file', attrs=attrs, where=where) def hash_(attrs=None, where=None): ''' Return hash information from osquery CLI Example: .. code-block:: bash salt '*' osquery.hash ''' return _osquery_cmd(table='hash', attrs=attrs, where=where) def osquery_extensions(attrs=None, where=None): ''' Return osquery_extensions information from osquery CLI Example: .. code-block:: bash salt '*' osquery.osquery_extensions ''' return _osquery_cmd(table='osquery_extensions', attrs=attrs, where=where) def osquery_flags(attrs=None, where=None): ''' Return osquery_flags information from osquery CLI Example: .. code-block:: bash salt '*' osquery.osquery_flags ''' return _osquery_cmd(table='osquery_flags', attrs=attrs, where=where) def osquery_info(attrs=None, where=None): ''' Return osquery_info information from osquery CLI Example: .. code-block:: bash salt '*' osquery.osquery_info ''' return _osquery_cmd(table='osquery_info', attrs=attrs, where=where) def osquery_registry(attrs=None, where=None): ''' Return osquery_registry information from osquery CLI Example: .. code-block:: bash salt '*' osquery.osquery_registry ''' return _osquery_cmd(table='osquery_registry', attrs=attrs, where=where) def time_(attrs=None): ''' Return time information from osquery CLI Example: .. code-block:: bash salt '*' osquery.time ''' return _osquery_cmd(table='time', attrs=attrs) def query(sql=None): ''' Return time information from osquery CLI Example: .. code-block:: bash salt '*' osquery.query "select * from users;" ''' return _osquery(sql)
saltstack/salt
salt/modules/osquery.py
_osquery_cmd
python
def _osquery_cmd(table, attrs=None, where=None, format='json'): ''' Helper function to run osquery queries ''' ret = { 'result': True, } if attrs: if isinstance(attrs, list): valid_attrs = _table_attrs(table) if valid_attrs: for a in attrs: if a not in valid_attrs: ret['result'] = False ret['comment'] = '{0} is not a valid attribute for table {1}'.format(a, table) return ret _attrs = ','.join(attrs) else: ret['result'] = False ret['comment'] = 'Invalid table {0}.'.format(table) return ret else: ret['comment'] = 'attrs must be specified as a list.' ret['result'] = False return ret else: _attrs = '*' sql = 'select {0} from {1}'.format(_attrs, table) if where: sql = '{0} where {1}'.format(sql, where) sql = '{0};'.format(sql) res = _osquery(sql) if res['result']: ret['data'] = res['data'] else: ret['comment'] = res['error'] return ret
Helper function to run osquery queries
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/osquery.py#L70-L111
[ "def _table_attrs(table):\n '''\n Helper function to find valid table attributes\n '''\n cmd = ['osqueryi'] + ['--json'] + ['pragma table_info({0})'.format(table)]\n res = __salt__['cmd.run_all'](cmd)\n if res['retcode'] == 0:\n attrs = []\n text = salt.utils.json.loads(res['stdout'])\n for item in text:\n attrs.append(item['name'])\n return attrs\n return False\n", "def _osquery(sql, format='json'):\n '''\n Helper function to run raw osquery queries\n '''\n ret = {\n 'result': True,\n }\n\n cmd = ['osqueryi'] + ['--json'] + [sql]\n res = __salt__['cmd.run_all'](cmd)\n if res['stderr']:\n ret['result'] = False\n ret['error'] = res['stderr']\n else:\n ret['data'] = salt.utils.json.loads(res['stdout'])\n log.debug('== %s ==', ret)\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Support for OSQuery - https://osquery.io. .. versionadded:: 2015.8.0 ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import logging # Import Salt libs import salt.utils.json import salt.utils.path import salt.utils.platform log = logging.getLogger(__name__) __func_alias__ = { 'file_': 'file', 'hash_': 'hash', 'time_': 'time', } __virtualname__ = 'osquery' def __virtual__(): if salt.utils.path.which('osqueryi'): return __virtualname__ return (False, 'The osquery execution module cannot be loaded: ' 'osqueryi binary is not in the path.') def _table_attrs(table): ''' Helper function to find valid table attributes ''' cmd = ['osqueryi'] + ['--json'] + ['pragma table_info({0})'.format(table)] res = __salt__['cmd.run_all'](cmd) if res['retcode'] == 0: attrs = [] text = salt.utils.json.loads(res['stdout']) for item in text: attrs.append(item['name']) return attrs return False def _osquery(sql, format='json'): ''' Helper function to run raw osquery queries ''' ret = { 'result': True, } cmd = ['osqueryi'] + ['--json'] + [sql] res = __salt__['cmd.run_all'](cmd) if res['stderr']: ret['result'] = False ret['error'] = res['stderr'] else: ret['data'] = salt.utils.json.loads(res['stdout']) log.debug('== %s ==', ret) return ret def version(): ''' Return version of osquery CLI Example: .. code-block:: bash salt '*' osquery.version ''' _false_return = {'result': False, 'comment': 'OSQuery version unavailable.'} res = _osquery_cmd(table='osquery_info', attrs=['version']) if 'result' in res and res['result']: if 'data' in res and isinstance(res['data'], list): return res['data'][0].get('version', '') or _false_return return _false_return def rpm_packages(attrs=None, where=None): ''' Return cpuid information from osquery CLI Example: .. code-block:: bash salt '*' osquery.rpm_packages ''' if __grains__['os_family'] == 'RedHat': return _osquery_cmd(table='rpm_packages', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat based systems.'} def kernel_integrity(attrs=None, where=None): ''' Return kernel_integrity information from osquery CLI Example: .. code-block:: bash salt '*' osquery.kernel_integrity ''' if __grains__['os_family'] in ['RedHat', 'Debian']: return _osquery_cmd(table='kernel_integrity', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat or Debian based systems.'} def kernel_modules(attrs=None, where=None): ''' Return kernel_modules information from osquery CLI Example: .. code-block:: bash salt '*' osquery.kernel_modules ''' if __grains__['os_family'] in ['RedHat', 'Debian']: return _osquery_cmd(table='kernel_modules', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat or Debian based systems.'} def memory_map(attrs=None, where=None): ''' Return memory_map information from osquery CLI Example: .. code-block:: bash salt '*' osquery.memory_map ''' if __grains__['os_family'] in ['RedHat', 'Debian']: return _osquery_cmd(table='memory_map', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat or Debian based systems.'} def process_memory_map(attrs=None, where=None): ''' Return process_memory_map information from osquery CLI Example: .. code-block:: bash salt '*' osquery.process_memory_map ''' if __grains__['os_family'] in ['RedHat', 'Debian']: return _osquery_cmd(table='process_memory_map', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat or Debian based systems.'} def shared_memory(attrs=None, where=None): ''' Return shared_memory information from osquery CLI Example: .. code-block:: bash salt '*' osquery.shared_memory ''' if __grains__['os_family'] in ['RedHat', 'Debian']: return _osquery_cmd(table='shared_memory', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat or Debian based systems.'} def apt_sources(attrs=None, where=None): ''' Return apt_sources information from osquery CLI Example: .. code-block:: bash salt '*' osquery.apt_sources ''' if __grains__['os_family'] == 'Debian': return _osquery_cmd(table='apt_sources', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Debian based systems.'} def deb_packages(attrs=None, where=None): ''' Return deb_packages information from osquery CLI Example: .. code-block:: bash salt '*' osquery.deb_packages ''' if __grains__['os_family'] == 'Debian': return _osquery_cmd(table='deb_packages', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Debian based systems.'} def acpi_tables(attrs=None, where=None): ''' Return acpi_tables information from osquery CLI Example: .. code-block:: bash salt '*' osquery.acpi_tables ''' return _osquery_cmd(table='acpi_tables', attrs=attrs, where=where) def arp_cache(attrs=None, where=None): ''' Return arp_cache information from osquery CLI Example: .. code-block:: bash salt '*' osquery.arp_cache ''' return _osquery_cmd(table='arp_cache', attrs=attrs, where=where) def block_devices(attrs=None, where=None): ''' Return block_devices information from osquery CLI Example: .. code-block:: bash salt '*' osquery.block_devices ''' return _osquery_cmd(table='block_devices', attrs=attrs, where=where) def cpuid(attrs=None, where=None): ''' Return cpuid information from osquery CLI Example: .. code-block:: bash salt '*' osquery.cpuid ''' return _osquery_cmd(table='cpuid', attrs=attrs, where=where) def crontab(attrs=None, where=None): ''' Return crontab information from osquery CLI Example: .. code-block:: bash salt '*' osquery.crontab ''' return _osquery_cmd(table='crontab', attrs=attrs, where=where) def etc_hosts(attrs=None, where=None): ''' Return etc_hosts information from osquery CLI Example: .. code-block:: bash salt '*' osquery.etc_hosts ''' return _osquery_cmd(table='etc_hosts', attrs=attrs, where=where) def etc_services(attrs=None, where=None): ''' Return etc_services information from osquery CLI Example: .. code-block:: bash salt '*' osquery.etc_services ''' return _osquery_cmd(table='etc_services', attrs=attrs, where=where) def file_changes(attrs=None, where=None): ''' Return file_changes information from osquery CLI Example: .. code-block:: bash salt '*' osquery.file_changes ''' return _osquery_cmd(table='file_changes', attrs=attrs, where=where) def groups(attrs=None, where=None): ''' Return groups information from osquery CLI Example: .. code-block:: bash salt '*' osquery.groups ''' return _osquery_cmd(table='groups', attrs=attrs, where=where) def hardware_events(attrs=None, where=None): ''' Return hardware_events information from osquery CLI Example: .. code-block:: bash salt '*' osquery.hardware_events ''' return _osquery_cmd(table='hardware_events', attrs=attrs, where=where) def interface_addresses(attrs=None, where=None): ''' Return interface_addresses information from osquery CLI Example: .. code-block:: bash salt '*' osquery.interface_addresses ''' return _osquery_cmd(table='interface_addresses', attrs=attrs, where=where) def interface_details(attrs=None, where=None): ''' Return interface_details information from osquery CLI Example: .. code-block:: bash salt '*' osquery.interface_details ''' return _osquery_cmd(table='interface_details', attrs=attrs, where=where) def kernel_info(attrs=None, where=None): ''' Return kernel_info information from osquery CLI Example: .. code-block:: bash salt '*' osquery.kernel_info ''' return _osquery_cmd(table='kernel_info', attrs=attrs, where=where) def last(attrs=None, where=None): ''' Return last information from osquery CLI Example: .. code-block:: bash salt '*' osquery.last ''' return _osquery_cmd(table='last', attrs=attrs, where=where) def listening_ports(attrs=None, where=None): r''' Return listening_ports information from osquery CLI Example: .. code-block:: bash salt '*' osquery.listening_ports ''' return _osquery_cmd(table='listening_ports', attrs=attrs, where=where) def logged_in_users(attrs=None, where=None): r''' Return logged_in_users information from osquery CLI Example: .. code-block:: bash salt '*' osquery.logged_in_users ''' return _osquery_cmd(table='logged_in_users', attrs=attrs, where=where) def mounts(attrs=None, where=None): r''' Return mounts information from osquery CLI Example: .. code-block:: bash salt '*' osquery.mounts ''' return _osquery_cmd(table='mounts', attrs=attrs, where=where) def os_version(attrs=None, where=None): ''' Return os_version information from osquery CLI Example: .. code-block:: bash salt '*' osquery.os_version ''' return _osquery_cmd(table='os_version', attrs=attrs, where=where) def passwd_changes(attrs=None, where=None): ''' Return passwd_changes information from osquery CLI Example: .. code-block:: bash salt '*' osquery.passwd_changes ''' return _osquery_cmd(table='passwd_changes', attrs=attrs, where=where) def pci_devices(attrs=None, where=None): ''' Return pci_devices information from osquery CLI Example: .. code-block:: bash salt '*' osquery.pci_devices ''' return _osquery_cmd(table='pci_devices', attrs=attrs, where=where) def process_envs(attrs=None, where=None): ''' Return process_envs information from osquery CLI Example: .. code-block:: bash salt '*' osquery.process_envs ''' return _osquery_cmd(table='process_envs', attrs=attrs, where=where) def process_open_files(attrs=None, where=None): ''' Return process_open_files information from osquery CLI Example: .. code-block:: bash salt '*' osquery.process_open_files ''' return _osquery_cmd(table='process_open_files', attrs=attrs, where=where) def process_open_sockets(attrs=None, where=None): ''' Return process_open_sockets information from osquery CLI Example: .. code-block:: bash salt '*' osquery.process_open_sockets ''' return _osquery_cmd(table='process_open_sockets', attrs=attrs, where=where) def processes(attrs=None, where=None): ''' Return processes information from osquery CLI Example: .. code-block:: bash salt '*' osquery.processes ''' return _osquery_cmd(table='processes', attrs=attrs, where=where) def routes(attrs=None, where=None): ''' Return routes information from osquery CLI Example: .. code-block:: bash salt '*' osquery.routes ''' return _osquery_cmd(table='routes', attrs=attrs, where=where) def shell_history(attrs=None, where=None): ''' Return shell_history information from osquery CLI Example: .. code-block:: bash salt '*' osquery.shell_history ''' return _osquery_cmd(table='shell_history', attrs=attrs, where=where) def smbios_tables(attrs=None, where=None): ''' Return smbios_tables information from osquery CLI Example: .. code-block:: bash salt '*' osquery.smbios_tables ''' return _osquery_cmd(table='smbios_tables', attrs=attrs, where=where) def suid_bin(attrs=None, where=None): ''' Return suid_bin information from osquery CLI Example: .. code-block:: bash salt '*' osquery.suid_bin ''' return _osquery_cmd(table='suid_bin', attrs=attrs, where=where) def system_controls(attrs=None, where=None): ''' Return system_controls information from osquery CLI Example: .. code-block:: bash salt '*' osquery.system_controls ''' return _osquery_cmd(table='system_controls', attrs=attrs, where=where) def usb_devices(attrs=None, where=None): ''' Return usb_devices information from osquery CLI Example: .. code-block:: bash salt '*' osquery.usb_devices ''' return _osquery_cmd(table='usb_devices', attrs=attrs, where=where) def users(attrs=None, where=None): ''' Return users information from osquery CLI Example: .. code-block:: bash salt '*' osquery.users ''' return _osquery_cmd(table='users', attrs=attrs, where=where) def alf(attrs=None, where=None): ''' Return alf information from osquery CLI Example: .. code-block:: bash salt '*' osquery.alf ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='alf', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def alf_exceptions(attrs=None, where=None): ''' Return alf_exceptions information from osquery CLI Example: .. code-block:: bash salt '*' osquery.alf_exceptions ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='alf_exceptions', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def alf_explicit_auths(attrs=None, where=None): ''' Return alf_explicit_auths information from osquery CLI Example: .. code-block:: bash salt '*' osquery.alf_explicit_auths ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='alf_explicit_auths', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def alf_services(attrs=None, where=None): ''' Return alf_services information from osquery CLI Example: .. code-block:: bash salt '*' osquery.alf_services ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='alf_services', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def apps(attrs=None, where=None): ''' Return apps information from osquery CLI Example: .. code-block:: bash salt '*' osquery.apps ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='apps', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def certificates(attrs=None, where=None): ''' Return certificates information from osquery CLI Example: .. code-block:: bash salt '*' osquery.certificates ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='certificates', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def chrome_extensions(attrs=None, where=None): ''' Return chrome_extensions information from osquery CLI Example: .. code-block:: bash salt '*' osquery.chrome_extensions ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='chrome_extensions', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def firefox_addons(attrs=None, where=None): ''' Return firefox_addons information from osquery CLI Example: .. code-block:: bash salt '*' osquery.firefox_addons ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='firefox_addons', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def homebrew_packages(attrs=None, where=None): ''' Return homebrew_packages information from osquery CLI Example: .. code-block:: bash salt '*' osquery.homebrew_packages ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='homebrew_packages', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def iokit_devicetree(attrs=None, where=None): ''' Return iokit_devicetree information from osquery CLI Example: .. code-block:: bash salt '*' osquery.iokit_devicetree ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='iokit_devicetree', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def iokit_registry(attrs=None, where=None): ''' Return iokit_registry information from osquery CLI Example: .. code-block:: bash salt '*' osquery.iokit_registry ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='iokit_registry', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def kernel_extensions(attrs=None, where=None): ''' Return kernel_extensions information from osquery CLI Example: .. code-block:: bash salt '*' osquery.kernel_extensions ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='kernel_extensions', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def keychain_items(attrs=None, where=None): ''' Return keychain_items information from osquery CLI Example: .. code-block:: bash salt '*' osquery.keychain_items ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='keychain_items', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def launchd(attrs=None, where=None): ''' Return launchd information from osquery CLI Example: .. code-block:: bash salt '*' osquery.launchd ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='launchd', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def nfs_shares(attrs=None, where=None): ''' Return nfs_shares information from osquery CLI Example: .. code-block:: bash salt '*' osquery.nfs_shares ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='nfs_shares', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def nvram(attrs=None, where=None): ''' Return nvram information from osquery CLI Example: .. code-block:: bash salt '*' osquery.nvram ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='nvram', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def preferences(attrs=None, where=None): ''' Return preferences information from osquery CLI Example: .. code-block:: bash salt '*' osquery.preferences ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='preferences', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def quarantine(attrs=None, where=None): ''' Return quarantine information from osquery CLI Example: .. code-block:: bash salt '*' osquery.quarantine ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='quarantine', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def safari_extensions(attrs=None, where=None): ''' Return safari_extensions information from osquery CLI Example: .. code-block:: bash salt '*' osquery.safari_extensions ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='safari_extensions', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def startup_items(attrs=None, where=None): ''' Return startup_items information from osquery CLI Example: .. code-block:: bash salt '*' osquery.startup_items ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='startup_items', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def xattr_where_from(attrs=None, where=None): ''' Return xattr_where_from information from osquery CLI Example: .. code-block:: bash salt '*' osquery.xattr_where_from ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='xattr_where_from', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def xprotect_entries(attrs=None, where=None): ''' Return xprotect_entries information from osquery CLI Example: .. code-block:: bash salt '*' osquery.xprotect_entries ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='xprotect_entries', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def xprotect_reports(attrs=None, where=None): ''' Return xprotect_reports information from osquery CLI Example: .. code-block:: bash salt '*' osquery.xprotect_reports ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='xprotect_reports', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def file_(attrs=None, where=None): ''' Return file information from osquery CLI Example: .. code-block:: bash salt '*' osquery.file ''' return _osquery_cmd(table='file', attrs=attrs, where=where) def hash_(attrs=None, where=None): ''' Return hash information from osquery CLI Example: .. code-block:: bash salt '*' osquery.hash ''' return _osquery_cmd(table='hash', attrs=attrs, where=where) def osquery_extensions(attrs=None, where=None): ''' Return osquery_extensions information from osquery CLI Example: .. code-block:: bash salt '*' osquery.osquery_extensions ''' return _osquery_cmd(table='osquery_extensions', attrs=attrs, where=where) def osquery_flags(attrs=None, where=None): ''' Return osquery_flags information from osquery CLI Example: .. code-block:: bash salt '*' osquery.osquery_flags ''' return _osquery_cmd(table='osquery_flags', attrs=attrs, where=where) def osquery_info(attrs=None, where=None): ''' Return osquery_info information from osquery CLI Example: .. code-block:: bash salt '*' osquery.osquery_info ''' return _osquery_cmd(table='osquery_info', attrs=attrs, where=where) def osquery_registry(attrs=None, where=None): ''' Return osquery_registry information from osquery CLI Example: .. code-block:: bash salt '*' osquery.osquery_registry ''' return _osquery_cmd(table='osquery_registry', attrs=attrs, where=where) def time_(attrs=None): ''' Return time information from osquery CLI Example: .. code-block:: bash salt '*' osquery.time ''' return _osquery_cmd(table='time', attrs=attrs) def query(sql=None): ''' Return time information from osquery CLI Example: .. code-block:: bash salt '*' osquery.query "select * from users;" ''' return _osquery(sql)
saltstack/salt
salt/modules/osquery.py
version
python
def version(): ''' Return version of osquery CLI Example: .. code-block:: bash salt '*' osquery.version ''' _false_return = {'result': False, 'comment': 'OSQuery version unavailable.'} res = _osquery_cmd(table='osquery_info', attrs=['version']) if 'result' in res and res['result']: if 'data' in res and isinstance(res['data'], list): return res['data'][0].get('version', '') or _false_return return _false_return
Return version of osquery CLI Example: .. code-block:: bash salt '*' osquery.version
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/osquery.py#L114-L130
[ "def _osquery_cmd(table, attrs=None, where=None, format='json'):\n '''\n Helper function to run osquery queries\n '''\n ret = {\n 'result': True,\n }\n\n if attrs:\n if isinstance(attrs, list):\n valid_attrs = _table_attrs(table)\n if valid_attrs:\n for a in attrs:\n if a not in valid_attrs:\n ret['result'] = False\n ret['comment'] = '{0} is not a valid attribute for table {1}'.format(a, table)\n return ret\n _attrs = ','.join(attrs)\n else:\n ret['result'] = False\n ret['comment'] = 'Invalid table {0}.'.format(table)\n return ret\n else:\n ret['comment'] = 'attrs must be specified as a list.'\n ret['result'] = False\n return ret\n else:\n _attrs = '*'\n\n sql = 'select {0} from {1}'.format(_attrs, table)\n\n if where:\n sql = '{0} where {1}'.format(sql, where)\n\n sql = '{0};'.format(sql)\n\n res = _osquery(sql)\n if res['result']:\n ret['data'] = res['data']\n else:\n ret['comment'] = res['error']\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Support for OSQuery - https://osquery.io. .. versionadded:: 2015.8.0 ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import logging # Import Salt libs import salt.utils.json import salt.utils.path import salt.utils.platform log = logging.getLogger(__name__) __func_alias__ = { 'file_': 'file', 'hash_': 'hash', 'time_': 'time', } __virtualname__ = 'osquery' def __virtual__(): if salt.utils.path.which('osqueryi'): return __virtualname__ return (False, 'The osquery execution module cannot be loaded: ' 'osqueryi binary is not in the path.') def _table_attrs(table): ''' Helper function to find valid table attributes ''' cmd = ['osqueryi'] + ['--json'] + ['pragma table_info({0})'.format(table)] res = __salt__['cmd.run_all'](cmd) if res['retcode'] == 0: attrs = [] text = salt.utils.json.loads(res['stdout']) for item in text: attrs.append(item['name']) return attrs return False def _osquery(sql, format='json'): ''' Helper function to run raw osquery queries ''' ret = { 'result': True, } cmd = ['osqueryi'] + ['--json'] + [sql] res = __salt__['cmd.run_all'](cmd) if res['stderr']: ret['result'] = False ret['error'] = res['stderr'] else: ret['data'] = salt.utils.json.loads(res['stdout']) log.debug('== %s ==', ret) return ret def _osquery_cmd(table, attrs=None, where=None, format='json'): ''' Helper function to run osquery queries ''' ret = { 'result': True, } if attrs: if isinstance(attrs, list): valid_attrs = _table_attrs(table) if valid_attrs: for a in attrs: if a not in valid_attrs: ret['result'] = False ret['comment'] = '{0} is not a valid attribute for table {1}'.format(a, table) return ret _attrs = ','.join(attrs) else: ret['result'] = False ret['comment'] = 'Invalid table {0}.'.format(table) return ret else: ret['comment'] = 'attrs must be specified as a list.' ret['result'] = False return ret else: _attrs = '*' sql = 'select {0} from {1}'.format(_attrs, table) if where: sql = '{0} where {1}'.format(sql, where) sql = '{0};'.format(sql) res = _osquery(sql) if res['result']: ret['data'] = res['data'] else: ret['comment'] = res['error'] return ret def rpm_packages(attrs=None, where=None): ''' Return cpuid information from osquery CLI Example: .. code-block:: bash salt '*' osquery.rpm_packages ''' if __grains__['os_family'] == 'RedHat': return _osquery_cmd(table='rpm_packages', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat based systems.'} def kernel_integrity(attrs=None, where=None): ''' Return kernel_integrity information from osquery CLI Example: .. code-block:: bash salt '*' osquery.kernel_integrity ''' if __grains__['os_family'] in ['RedHat', 'Debian']: return _osquery_cmd(table='kernel_integrity', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat or Debian based systems.'} def kernel_modules(attrs=None, where=None): ''' Return kernel_modules information from osquery CLI Example: .. code-block:: bash salt '*' osquery.kernel_modules ''' if __grains__['os_family'] in ['RedHat', 'Debian']: return _osquery_cmd(table='kernel_modules', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat or Debian based systems.'} def memory_map(attrs=None, where=None): ''' Return memory_map information from osquery CLI Example: .. code-block:: bash salt '*' osquery.memory_map ''' if __grains__['os_family'] in ['RedHat', 'Debian']: return _osquery_cmd(table='memory_map', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat or Debian based systems.'} def process_memory_map(attrs=None, where=None): ''' Return process_memory_map information from osquery CLI Example: .. code-block:: bash salt '*' osquery.process_memory_map ''' if __grains__['os_family'] in ['RedHat', 'Debian']: return _osquery_cmd(table='process_memory_map', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat or Debian based systems.'} def shared_memory(attrs=None, where=None): ''' Return shared_memory information from osquery CLI Example: .. code-block:: bash salt '*' osquery.shared_memory ''' if __grains__['os_family'] in ['RedHat', 'Debian']: return _osquery_cmd(table='shared_memory', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat or Debian based systems.'} def apt_sources(attrs=None, where=None): ''' Return apt_sources information from osquery CLI Example: .. code-block:: bash salt '*' osquery.apt_sources ''' if __grains__['os_family'] == 'Debian': return _osquery_cmd(table='apt_sources', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Debian based systems.'} def deb_packages(attrs=None, where=None): ''' Return deb_packages information from osquery CLI Example: .. code-block:: bash salt '*' osquery.deb_packages ''' if __grains__['os_family'] == 'Debian': return _osquery_cmd(table='deb_packages', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Debian based systems.'} def acpi_tables(attrs=None, where=None): ''' Return acpi_tables information from osquery CLI Example: .. code-block:: bash salt '*' osquery.acpi_tables ''' return _osquery_cmd(table='acpi_tables', attrs=attrs, where=where) def arp_cache(attrs=None, where=None): ''' Return arp_cache information from osquery CLI Example: .. code-block:: bash salt '*' osquery.arp_cache ''' return _osquery_cmd(table='arp_cache', attrs=attrs, where=where) def block_devices(attrs=None, where=None): ''' Return block_devices information from osquery CLI Example: .. code-block:: bash salt '*' osquery.block_devices ''' return _osquery_cmd(table='block_devices', attrs=attrs, where=where) def cpuid(attrs=None, where=None): ''' Return cpuid information from osquery CLI Example: .. code-block:: bash salt '*' osquery.cpuid ''' return _osquery_cmd(table='cpuid', attrs=attrs, where=where) def crontab(attrs=None, where=None): ''' Return crontab information from osquery CLI Example: .. code-block:: bash salt '*' osquery.crontab ''' return _osquery_cmd(table='crontab', attrs=attrs, where=where) def etc_hosts(attrs=None, where=None): ''' Return etc_hosts information from osquery CLI Example: .. code-block:: bash salt '*' osquery.etc_hosts ''' return _osquery_cmd(table='etc_hosts', attrs=attrs, where=where) def etc_services(attrs=None, where=None): ''' Return etc_services information from osquery CLI Example: .. code-block:: bash salt '*' osquery.etc_services ''' return _osquery_cmd(table='etc_services', attrs=attrs, where=where) def file_changes(attrs=None, where=None): ''' Return file_changes information from osquery CLI Example: .. code-block:: bash salt '*' osquery.file_changes ''' return _osquery_cmd(table='file_changes', attrs=attrs, where=where) def groups(attrs=None, where=None): ''' Return groups information from osquery CLI Example: .. code-block:: bash salt '*' osquery.groups ''' return _osquery_cmd(table='groups', attrs=attrs, where=where) def hardware_events(attrs=None, where=None): ''' Return hardware_events information from osquery CLI Example: .. code-block:: bash salt '*' osquery.hardware_events ''' return _osquery_cmd(table='hardware_events', attrs=attrs, where=where) def interface_addresses(attrs=None, where=None): ''' Return interface_addresses information from osquery CLI Example: .. code-block:: bash salt '*' osquery.interface_addresses ''' return _osquery_cmd(table='interface_addresses', attrs=attrs, where=where) def interface_details(attrs=None, where=None): ''' Return interface_details information from osquery CLI Example: .. code-block:: bash salt '*' osquery.interface_details ''' return _osquery_cmd(table='interface_details', attrs=attrs, where=where) def kernel_info(attrs=None, where=None): ''' Return kernel_info information from osquery CLI Example: .. code-block:: bash salt '*' osquery.kernel_info ''' return _osquery_cmd(table='kernel_info', attrs=attrs, where=where) def last(attrs=None, where=None): ''' Return last information from osquery CLI Example: .. code-block:: bash salt '*' osquery.last ''' return _osquery_cmd(table='last', attrs=attrs, where=where) def listening_ports(attrs=None, where=None): r''' Return listening_ports information from osquery CLI Example: .. code-block:: bash salt '*' osquery.listening_ports ''' return _osquery_cmd(table='listening_ports', attrs=attrs, where=where) def logged_in_users(attrs=None, where=None): r''' Return logged_in_users information from osquery CLI Example: .. code-block:: bash salt '*' osquery.logged_in_users ''' return _osquery_cmd(table='logged_in_users', attrs=attrs, where=where) def mounts(attrs=None, where=None): r''' Return mounts information from osquery CLI Example: .. code-block:: bash salt '*' osquery.mounts ''' return _osquery_cmd(table='mounts', attrs=attrs, where=where) def os_version(attrs=None, where=None): ''' Return os_version information from osquery CLI Example: .. code-block:: bash salt '*' osquery.os_version ''' return _osquery_cmd(table='os_version', attrs=attrs, where=where) def passwd_changes(attrs=None, where=None): ''' Return passwd_changes information from osquery CLI Example: .. code-block:: bash salt '*' osquery.passwd_changes ''' return _osquery_cmd(table='passwd_changes', attrs=attrs, where=where) def pci_devices(attrs=None, where=None): ''' Return pci_devices information from osquery CLI Example: .. code-block:: bash salt '*' osquery.pci_devices ''' return _osquery_cmd(table='pci_devices', attrs=attrs, where=where) def process_envs(attrs=None, where=None): ''' Return process_envs information from osquery CLI Example: .. code-block:: bash salt '*' osquery.process_envs ''' return _osquery_cmd(table='process_envs', attrs=attrs, where=where) def process_open_files(attrs=None, where=None): ''' Return process_open_files information from osquery CLI Example: .. code-block:: bash salt '*' osquery.process_open_files ''' return _osquery_cmd(table='process_open_files', attrs=attrs, where=where) def process_open_sockets(attrs=None, where=None): ''' Return process_open_sockets information from osquery CLI Example: .. code-block:: bash salt '*' osquery.process_open_sockets ''' return _osquery_cmd(table='process_open_sockets', attrs=attrs, where=where) def processes(attrs=None, where=None): ''' Return processes information from osquery CLI Example: .. code-block:: bash salt '*' osquery.processes ''' return _osquery_cmd(table='processes', attrs=attrs, where=where) def routes(attrs=None, where=None): ''' Return routes information from osquery CLI Example: .. code-block:: bash salt '*' osquery.routes ''' return _osquery_cmd(table='routes', attrs=attrs, where=where) def shell_history(attrs=None, where=None): ''' Return shell_history information from osquery CLI Example: .. code-block:: bash salt '*' osquery.shell_history ''' return _osquery_cmd(table='shell_history', attrs=attrs, where=where) def smbios_tables(attrs=None, where=None): ''' Return smbios_tables information from osquery CLI Example: .. code-block:: bash salt '*' osquery.smbios_tables ''' return _osquery_cmd(table='smbios_tables', attrs=attrs, where=where) def suid_bin(attrs=None, where=None): ''' Return suid_bin information from osquery CLI Example: .. code-block:: bash salt '*' osquery.suid_bin ''' return _osquery_cmd(table='suid_bin', attrs=attrs, where=where) def system_controls(attrs=None, where=None): ''' Return system_controls information from osquery CLI Example: .. code-block:: bash salt '*' osquery.system_controls ''' return _osquery_cmd(table='system_controls', attrs=attrs, where=where) def usb_devices(attrs=None, where=None): ''' Return usb_devices information from osquery CLI Example: .. code-block:: bash salt '*' osquery.usb_devices ''' return _osquery_cmd(table='usb_devices', attrs=attrs, where=where) def users(attrs=None, where=None): ''' Return users information from osquery CLI Example: .. code-block:: bash salt '*' osquery.users ''' return _osquery_cmd(table='users', attrs=attrs, where=where) def alf(attrs=None, where=None): ''' Return alf information from osquery CLI Example: .. code-block:: bash salt '*' osquery.alf ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='alf', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def alf_exceptions(attrs=None, where=None): ''' Return alf_exceptions information from osquery CLI Example: .. code-block:: bash salt '*' osquery.alf_exceptions ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='alf_exceptions', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def alf_explicit_auths(attrs=None, where=None): ''' Return alf_explicit_auths information from osquery CLI Example: .. code-block:: bash salt '*' osquery.alf_explicit_auths ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='alf_explicit_auths', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def alf_services(attrs=None, where=None): ''' Return alf_services information from osquery CLI Example: .. code-block:: bash salt '*' osquery.alf_services ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='alf_services', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def apps(attrs=None, where=None): ''' Return apps information from osquery CLI Example: .. code-block:: bash salt '*' osquery.apps ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='apps', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def certificates(attrs=None, where=None): ''' Return certificates information from osquery CLI Example: .. code-block:: bash salt '*' osquery.certificates ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='certificates', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def chrome_extensions(attrs=None, where=None): ''' Return chrome_extensions information from osquery CLI Example: .. code-block:: bash salt '*' osquery.chrome_extensions ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='chrome_extensions', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def firefox_addons(attrs=None, where=None): ''' Return firefox_addons information from osquery CLI Example: .. code-block:: bash salt '*' osquery.firefox_addons ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='firefox_addons', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def homebrew_packages(attrs=None, where=None): ''' Return homebrew_packages information from osquery CLI Example: .. code-block:: bash salt '*' osquery.homebrew_packages ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='homebrew_packages', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def iokit_devicetree(attrs=None, where=None): ''' Return iokit_devicetree information from osquery CLI Example: .. code-block:: bash salt '*' osquery.iokit_devicetree ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='iokit_devicetree', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def iokit_registry(attrs=None, where=None): ''' Return iokit_registry information from osquery CLI Example: .. code-block:: bash salt '*' osquery.iokit_registry ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='iokit_registry', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def kernel_extensions(attrs=None, where=None): ''' Return kernel_extensions information from osquery CLI Example: .. code-block:: bash salt '*' osquery.kernel_extensions ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='kernel_extensions', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def keychain_items(attrs=None, where=None): ''' Return keychain_items information from osquery CLI Example: .. code-block:: bash salt '*' osquery.keychain_items ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='keychain_items', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def launchd(attrs=None, where=None): ''' Return launchd information from osquery CLI Example: .. code-block:: bash salt '*' osquery.launchd ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='launchd', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def nfs_shares(attrs=None, where=None): ''' Return nfs_shares information from osquery CLI Example: .. code-block:: bash salt '*' osquery.nfs_shares ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='nfs_shares', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def nvram(attrs=None, where=None): ''' Return nvram information from osquery CLI Example: .. code-block:: bash salt '*' osquery.nvram ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='nvram', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def preferences(attrs=None, where=None): ''' Return preferences information from osquery CLI Example: .. code-block:: bash salt '*' osquery.preferences ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='preferences', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def quarantine(attrs=None, where=None): ''' Return quarantine information from osquery CLI Example: .. code-block:: bash salt '*' osquery.quarantine ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='quarantine', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def safari_extensions(attrs=None, where=None): ''' Return safari_extensions information from osquery CLI Example: .. code-block:: bash salt '*' osquery.safari_extensions ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='safari_extensions', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def startup_items(attrs=None, where=None): ''' Return startup_items information from osquery CLI Example: .. code-block:: bash salt '*' osquery.startup_items ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='startup_items', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def xattr_where_from(attrs=None, where=None): ''' Return xattr_where_from information from osquery CLI Example: .. code-block:: bash salt '*' osquery.xattr_where_from ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='xattr_where_from', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def xprotect_entries(attrs=None, where=None): ''' Return xprotect_entries information from osquery CLI Example: .. code-block:: bash salt '*' osquery.xprotect_entries ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='xprotect_entries', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def xprotect_reports(attrs=None, where=None): ''' Return xprotect_reports information from osquery CLI Example: .. code-block:: bash salt '*' osquery.xprotect_reports ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='xprotect_reports', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def file_(attrs=None, where=None): ''' Return file information from osquery CLI Example: .. code-block:: bash salt '*' osquery.file ''' return _osquery_cmd(table='file', attrs=attrs, where=where) def hash_(attrs=None, where=None): ''' Return hash information from osquery CLI Example: .. code-block:: bash salt '*' osquery.hash ''' return _osquery_cmd(table='hash', attrs=attrs, where=where) def osquery_extensions(attrs=None, where=None): ''' Return osquery_extensions information from osquery CLI Example: .. code-block:: bash salt '*' osquery.osquery_extensions ''' return _osquery_cmd(table='osquery_extensions', attrs=attrs, where=where) def osquery_flags(attrs=None, where=None): ''' Return osquery_flags information from osquery CLI Example: .. code-block:: bash salt '*' osquery.osquery_flags ''' return _osquery_cmd(table='osquery_flags', attrs=attrs, where=where) def osquery_info(attrs=None, where=None): ''' Return osquery_info information from osquery CLI Example: .. code-block:: bash salt '*' osquery.osquery_info ''' return _osquery_cmd(table='osquery_info', attrs=attrs, where=where) def osquery_registry(attrs=None, where=None): ''' Return osquery_registry information from osquery CLI Example: .. code-block:: bash salt '*' osquery.osquery_registry ''' return _osquery_cmd(table='osquery_registry', attrs=attrs, where=where) def time_(attrs=None): ''' Return time information from osquery CLI Example: .. code-block:: bash salt '*' osquery.time ''' return _osquery_cmd(table='time', attrs=attrs) def query(sql=None): ''' Return time information from osquery CLI Example: .. code-block:: bash salt '*' osquery.query "select * from users;" ''' return _osquery(sql)
saltstack/salt
salt/modules/osquery.py
rpm_packages
python
def rpm_packages(attrs=None, where=None): ''' Return cpuid information from osquery CLI Example: .. code-block:: bash salt '*' osquery.rpm_packages ''' if __grains__['os_family'] == 'RedHat': return _osquery_cmd(table='rpm_packages', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat based systems.'}
Return cpuid information from osquery CLI Example: .. code-block:: bash salt '*' osquery.rpm_packages
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/osquery.py#L133-L146
[ "def _osquery_cmd(table, attrs=None, where=None, format='json'):\n '''\n Helper function to run osquery queries\n '''\n ret = {\n 'result': True,\n }\n\n if attrs:\n if isinstance(attrs, list):\n valid_attrs = _table_attrs(table)\n if valid_attrs:\n for a in attrs:\n if a not in valid_attrs:\n ret['result'] = False\n ret['comment'] = '{0} is not a valid attribute for table {1}'.format(a, table)\n return ret\n _attrs = ','.join(attrs)\n else:\n ret['result'] = False\n ret['comment'] = 'Invalid table {0}.'.format(table)\n return ret\n else:\n ret['comment'] = 'attrs must be specified as a list.'\n ret['result'] = False\n return ret\n else:\n _attrs = '*'\n\n sql = 'select {0} from {1}'.format(_attrs, table)\n\n if where:\n sql = '{0} where {1}'.format(sql, where)\n\n sql = '{0};'.format(sql)\n\n res = _osquery(sql)\n if res['result']:\n ret['data'] = res['data']\n else:\n ret['comment'] = res['error']\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Support for OSQuery - https://osquery.io. .. versionadded:: 2015.8.0 ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import logging # Import Salt libs import salt.utils.json import salt.utils.path import salt.utils.platform log = logging.getLogger(__name__) __func_alias__ = { 'file_': 'file', 'hash_': 'hash', 'time_': 'time', } __virtualname__ = 'osquery' def __virtual__(): if salt.utils.path.which('osqueryi'): return __virtualname__ return (False, 'The osquery execution module cannot be loaded: ' 'osqueryi binary is not in the path.') def _table_attrs(table): ''' Helper function to find valid table attributes ''' cmd = ['osqueryi'] + ['--json'] + ['pragma table_info({0})'.format(table)] res = __salt__['cmd.run_all'](cmd) if res['retcode'] == 0: attrs = [] text = salt.utils.json.loads(res['stdout']) for item in text: attrs.append(item['name']) return attrs return False def _osquery(sql, format='json'): ''' Helper function to run raw osquery queries ''' ret = { 'result': True, } cmd = ['osqueryi'] + ['--json'] + [sql] res = __salt__['cmd.run_all'](cmd) if res['stderr']: ret['result'] = False ret['error'] = res['stderr'] else: ret['data'] = salt.utils.json.loads(res['stdout']) log.debug('== %s ==', ret) return ret def _osquery_cmd(table, attrs=None, where=None, format='json'): ''' Helper function to run osquery queries ''' ret = { 'result': True, } if attrs: if isinstance(attrs, list): valid_attrs = _table_attrs(table) if valid_attrs: for a in attrs: if a not in valid_attrs: ret['result'] = False ret['comment'] = '{0} is not a valid attribute for table {1}'.format(a, table) return ret _attrs = ','.join(attrs) else: ret['result'] = False ret['comment'] = 'Invalid table {0}.'.format(table) return ret else: ret['comment'] = 'attrs must be specified as a list.' ret['result'] = False return ret else: _attrs = '*' sql = 'select {0} from {1}'.format(_attrs, table) if where: sql = '{0} where {1}'.format(sql, where) sql = '{0};'.format(sql) res = _osquery(sql) if res['result']: ret['data'] = res['data'] else: ret['comment'] = res['error'] return ret def version(): ''' Return version of osquery CLI Example: .. code-block:: bash salt '*' osquery.version ''' _false_return = {'result': False, 'comment': 'OSQuery version unavailable.'} res = _osquery_cmd(table='osquery_info', attrs=['version']) if 'result' in res and res['result']: if 'data' in res and isinstance(res['data'], list): return res['data'][0].get('version', '') or _false_return return _false_return def kernel_integrity(attrs=None, where=None): ''' Return kernel_integrity information from osquery CLI Example: .. code-block:: bash salt '*' osquery.kernel_integrity ''' if __grains__['os_family'] in ['RedHat', 'Debian']: return _osquery_cmd(table='kernel_integrity', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat or Debian based systems.'} def kernel_modules(attrs=None, where=None): ''' Return kernel_modules information from osquery CLI Example: .. code-block:: bash salt '*' osquery.kernel_modules ''' if __grains__['os_family'] in ['RedHat', 'Debian']: return _osquery_cmd(table='kernel_modules', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat or Debian based systems.'} def memory_map(attrs=None, where=None): ''' Return memory_map information from osquery CLI Example: .. code-block:: bash salt '*' osquery.memory_map ''' if __grains__['os_family'] in ['RedHat', 'Debian']: return _osquery_cmd(table='memory_map', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat or Debian based systems.'} def process_memory_map(attrs=None, where=None): ''' Return process_memory_map information from osquery CLI Example: .. code-block:: bash salt '*' osquery.process_memory_map ''' if __grains__['os_family'] in ['RedHat', 'Debian']: return _osquery_cmd(table='process_memory_map', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat or Debian based systems.'} def shared_memory(attrs=None, where=None): ''' Return shared_memory information from osquery CLI Example: .. code-block:: bash salt '*' osquery.shared_memory ''' if __grains__['os_family'] in ['RedHat', 'Debian']: return _osquery_cmd(table='shared_memory', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat or Debian based systems.'} def apt_sources(attrs=None, where=None): ''' Return apt_sources information from osquery CLI Example: .. code-block:: bash salt '*' osquery.apt_sources ''' if __grains__['os_family'] == 'Debian': return _osquery_cmd(table='apt_sources', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Debian based systems.'} def deb_packages(attrs=None, where=None): ''' Return deb_packages information from osquery CLI Example: .. code-block:: bash salt '*' osquery.deb_packages ''' if __grains__['os_family'] == 'Debian': return _osquery_cmd(table='deb_packages', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Debian based systems.'} def acpi_tables(attrs=None, where=None): ''' Return acpi_tables information from osquery CLI Example: .. code-block:: bash salt '*' osquery.acpi_tables ''' return _osquery_cmd(table='acpi_tables', attrs=attrs, where=where) def arp_cache(attrs=None, where=None): ''' Return arp_cache information from osquery CLI Example: .. code-block:: bash salt '*' osquery.arp_cache ''' return _osquery_cmd(table='arp_cache', attrs=attrs, where=where) def block_devices(attrs=None, where=None): ''' Return block_devices information from osquery CLI Example: .. code-block:: bash salt '*' osquery.block_devices ''' return _osquery_cmd(table='block_devices', attrs=attrs, where=where) def cpuid(attrs=None, where=None): ''' Return cpuid information from osquery CLI Example: .. code-block:: bash salt '*' osquery.cpuid ''' return _osquery_cmd(table='cpuid', attrs=attrs, where=where) def crontab(attrs=None, where=None): ''' Return crontab information from osquery CLI Example: .. code-block:: bash salt '*' osquery.crontab ''' return _osquery_cmd(table='crontab', attrs=attrs, where=where) def etc_hosts(attrs=None, where=None): ''' Return etc_hosts information from osquery CLI Example: .. code-block:: bash salt '*' osquery.etc_hosts ''' return _osquery_cmd(table='etc_hosts', attrs=attrs, where=where) def etc_services(attrs=None, where=None): ''' Return etc_services information from osquery CLI Example: .. code-block:: bash salt '*' osquery.etc_services ''' return _osquery_cmd(table='etc_services', attrs=attrs, where=where) def file_changes(attrs=None, where=None): ''' Return file_changes information from osquery CLI Example: .. code-block:: bash salt '*' osquery.file_changes ''' return _osquery_cmd(table='file_changes', attrs=attrs, where=where) def groups(attrs=None, where=None): ''' Return groups information from osquery CLI Example: .. code-block:: bash salt '*' osquery.groups ''' return _osquery_cmd(table='groups', attrs=attrs, where=where) def hardware_events(attrs=None, where=None): ''' Return hardware_events information from osquery CLI Example: .. code-block:: bash salt '*' osquery.hardware_events ''' return _osquery_cmd(table='hardware_events', attrs=attrs, where=where) def interface_addresses(attrs=None, where=None): ''' Return interface_addresses information from osquery CLI Example: .. code-block:: bash salt '*' osquery.interface_addresses ''' return _osquery_cmd(table='interface_addresses', attrs=attrs, where=where) def interface_details(attrs=None, where=None): ''' Return interface_details information from osquery CLI Example: .. code-block:: bash salt '*' osquery.interface_details ''' return _osquery_cmd(table='interface_details', attrs=attrs, where=where) def kernel_info(attrs=None, where=None): ''' Return kernel_info information from osquery CLI Example: .. code-block:: bash salt '*' osquery.kernel_info ''' return _osquery_cmd(table='kernel_info', attrs=attrs, where=where) def last(attrs=None, where=None): ''' Return last information from osquery CLI Example: .. code-block:: bash salt '*' osquery.last ''' return _osquery_cmd(table='last', attrs=attrs, where=where) def listening_ports(attrs=None, where=None): r''' Return listening_ports information from osquery CLI Example: .. code-block:: bash salt '*' osquery.listening_ports ''' return _osquery_cmd(table='listening_ports', attrs=attrs, where=where) def logged_in_users(attrs=None, where=None): r''' Return logged_in_users information from osquery CLI Example: .. code-block:: bash salt '*' osquery.logged_in_users ''' return _osquery_cmd(table='logged_in_users', attrs=attrs, where=where) def mounts(attrs=None, where=None): r''' Return mounts information from osquery CLI Example: .. code-block:: bash salt '*' osquery.mounts ''' return _osquery_cmd(table='mounts', attrs=attrs, where=where) def os_version(attrs=None, where=None): ''' Return os_version information from osquery CLI Example: .. code-block:: bash salt '*' osquery.os_version ''' return _osquery_cmd(table='os_version', attrs=attrs, where=where) def passwd_changes(attrs=None, where=None): ''' Return passwd_changes information from osquery CLI Example: .. code-block:: bash salt '*' osquery.passwd_changes ''' return _osquery_cmd(table='passwd_changes', attrs=attrs, where=where) def pci_devices(attrs=None, where=None): ''' Return pci_devices information from osquery CLI Example: .. code-block:: bash salt '*' osquery.pci_devices ''' return _osquery_cmd(table='pci_devices', attrs=attrs, where=where) def process_envs(attrs=None, where=None): ''' Return process_envs information from osquery CLI Example: .. code-block:: bash salt '*' osquery.process_envs ''' return _osquery_cmd(table='process_envs', attrs=attrs, where=where) def process_open_files(attrs=None, where=None): ''' Return process_open_files information from osquery CLI Example: .. code-block:: bash salt '*' osquery.process_open_files ''' return _osquery_cmd(table='process_open_files', attrs=attrs, where=where) def process_open_sockets(attrs=None, where=None): ''' Return process_open_sockets information from osquery CLI Example: .. code-block:: bash salt '*' osquery.process_open_sockets ''' return _osquery_cmd(table='process_open_sockets', attrs=attrs, where=where) def processes(attrs=None, where=None): ''' Return processes information from osquery CLI Example: .. code-block:: bash salt '*' osquery.processes ''' return _osquery_cmd(table='processes', attrs=attrs, where=where) def routes(attrs=None, where=None): ''' Return routes information from osquery CLI Example: .. code-block:: bash salt '*' osquery.routes ''' return _osquery_cmd(table='routes', attrs=attrs, where=where) def shell_history(attrs=None, where=None): ''' Return shell_history information from osquery CLI Example: .. code-block:: bash salt '*' osquery.shell_history ''' return _osquery_cmd(table='shell_history', attrs=attrs, where=where) def smbios_tables(attrs=None, where=None): ''' Return smbios_tables information from osquery CLI Example: .. code-block:: bash salt '*' osquery.smbios_tables ''' return _osquery_cmd(table='smbios_tables', attrs=attrs, where=where) def suid_bin(attrs=None, where=None): ''' Return suid_bin information from osquery CLI Example: .. code-block:: bash salt '*' osquery.suid_bin ''' return _osquery_cmd(table='suid_bin', attrs=attrs, where=where) def system_controls(attrs=None, where=None): ''' Return system_controls information from osquery CLI Example: .. code-block:: bash salt '*' osquery.system_controls ''' return _osquery_cmd(table='system_controls', attrs=attrs, where=where) def usb_devices(attrs=None, where=None): ''' Return usb_devices information from osquery CLI Example: .. code-block:: bash salt '*' osquery.usb_devices ''' return _osquery_cmd(table='usb_devices', attrs=attrs, where=where) def users(attrs=None, where=None): ''' Return users information from osquery CLI Example: .. code-block:: bash salt '*' osquery.users ''' return _osquery_cmd(table='users', attrs=attrs, where=where) def alf(attrs=None, where=None): ''' Return alf information from osquery CLI Example: .. code-block:: bash salt '*' osquery.alf ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='alf', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def alf_exceptions(attrs=None, where=None): ''' Return alf_exceptions information from osquery CLI Example: .. code-block:: bash salt '*' osquery.alf_exceptions ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='alf_exceptions', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def alf_explicit_auths(attrs=None, where=None): ''' Return alf_explicit_auths information from osquery CLI Example: .. code-block:: bash salt '*' osquery.alf_explicit_auths ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='alf_explicit_auths', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def alf_services(attrs=None, where=None): ''' Return alf_services information from osquery CLI Example: .. code-block:: bash salt '*' osquery.alf_services ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='alf_services', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def apps(attrs=None, where=None): ''' Return apps information from osquery CLI Example: .. code-block:: bash salt '*' osquery.apps ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='apps', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def certificates(attrs=None, where=None): ''' Return certificates information from osquery CLI Example: .. code-block:: bash salt '*' osquery.certificates ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='certificates', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def chrome_extensions(attrs=None, where=None): ''' Return chrome_extensions information from osquery CLI Example: .. code-block:: bash salt '*' osquery.chrome_extensions ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='chrome_extensions', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def firefox_addons(attrs=None, where=None): ''' Return firefox_addons information from osquery CLI Example: .. code-block:: bash salt '*' osquery.firefox_addons ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='firefox_addons', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def homebrew_packages(attrs=None, where=None): ''' Return homebrew_packages information from osquery CLI Example: .. code-block:: bash salt '*' osquery.homebrew_packages ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='homebrew_packages', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def iokit_devicetree(attrs=None, where=None): ''' Return iokit_devicetree information from osquery CLI Example: .. code-block:: bash salt '*' osquery.iokit_devicetree ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='iokit_devicetree', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def iokit_registry(attrs=None, where=None): ''' Return iokit_registry information from osquery CLI Example: .. code-block:: bash salt '*' osquery.iokit_registry ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='iokit_registry', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def kernel_extensions(attrs=None, where=None): ''' Return kernel_extensions information from osquery CLI Example: .. code-block:: bash salt '*' osquery.kernel_extensions ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='kernel_extensions', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def keychain_items(attrs=None, where=None): ''' Return keychain_items information from osquery CLI Example: .. code-block:: bash salt '*' osquery.keychain_items ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='keychain_items', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def launchd(attrs=None, where=None): ''' Return launchd information from osquery CLI Example: .. code-block:: bash salt '*' osquery.launchd ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='launchd', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def nfs_shares(attrs=None, where=None): ''' Return nfs_shares information from osquery CLI Example: .. code-block:: bash salt '*' osquery.nfs_shares ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='nfs_shares', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def nvram(attrs=None, where=None): ''' Return nvram information from osquery CLI Example: .. code-block:: bash salt '*' osquery.nvram ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='nvram', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def preferences(attrs=None, where=None): ''' Return preferences information from osquery CLI Example: .. code-block:: bash salt '*' osquery.preferences ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='preferences', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def quarantine(attrs=None, where=None): ''' Return quarantine information from osquery CLI Example: .. code-block:: bash salt '*' osquery.quarantine ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='quarantine', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def safari_extensions(attrs=None, where=None): ''' Return safari_extensions information from osquery CLI Example: .. code-block:: bash salt '*' osquery.safari_extensions ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='safari_extensions', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def startup_items(attrs=None, where=None): ''' Return startup_items information from osquery CLI Example: .. code-block:: bash salt '*' osquery.startup_items ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='startup_items', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def xattr_where_from(attrs=None, where=None): ''' Return xattr_where_from information from osquery CLI Example: .. code-block:: bash salt '*' osquery.xattr_where_from ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='xattr_where_from', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def xprotect_entries(attrs=None, where=None): ''' Return xprotect_entries information from osquery CLI Example: .. code-block:: bash salt '*' osquery.xprotect_entries ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='xprotect_entries', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def xprotect_reports(attrs=None, where=None): ''' Return xprotect_reports information from osquery CLI Example: .. code-block:: bash salt '*' osquery.xprotect_reports ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='xprotect_reports', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def file_(attrs=None, where=None): ''' Return file information from osquery CLI Example: .. code-block:: bash salt '*' osquery.file ''' return _osquery_cmd(table='file', attrs=attrs, where=where) def hash_(attrs=None, where=None): ''' Return hash information from osquery CLI Example: .. code-block:: bash salt '*' osquery.hash ''' return _osquery_cmd(table='hash', attrs=attrs, where=where) def osquery_extensions(attrs=None, where=None): ''' Return osquery_extensions information from osquery CLI Example: .. code-block:: bash salt '*' osquery.osquery_extensions ''' return _osquery_cmd(table='osquery_extensions', attrs=attrs, where=where) def osquery_flags(attrs=None, where=None): ''' Return osquery_flags information from osquery CLI Example: .. code-block:: bash salt '*' osquery.osquery_flags ''' return _osquery_cmd(table='osquery_flags', attrs=attrs, where=where) def osquery_info(attrs=None, where=None): ''' Return osquery_info information from osquery CLI Example: .. code-block:: bash salt '*' osquery.osquery_info ''' return _osquery_cmd(table='osquery_info', attrs=attrs, where=where) def osquery_registry(attrs=None, where=None): ''' Return osquery_registry information from osquery CLI Example: .. code-block:: bash salt '*' osquery.osquery_registry ''' return _osquery_cmd(table='osquery_registry', attrs=attrs, where=where) def time_(attrs=None): ''' Return time information from osquery CLI Example: .. code-block:: bash salt '*' osquery.time ''' return _osquery_cmd(table='time', attrs=attrs) def query(sql=None): ''' Return time information from osquery CLI Example: .. code-block:: bash salt '*' osquery.query "select * from users;" ''' return _osquery(sql)
saltstack/salt
salt/modules/osquery.py
kernel_integrity
python
def kernel_integrity(attrs=None, where=None): ''' Return kernel_integrity information from osquery CLI Example: .. code-block:: bash salt '*' osquery.kernel_integrity ''' if __grains__['os_family'] in ['RedHat', 'Debian']: return _osquery_cmd(table='kernel_integrity', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat or Debian based systems.'}
Return kernel_integrity information from osquery CLI Example: .. code-block:: bash salt '*' osquery.kernel_integrity
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/osquery.py#L149-L161
[ "def _osquery_cmd(table, attrs=None, where=None, format='json'):\n '''\n Helper function to run osquery queries\n '''\n ret = {\n 'result': True,\n }\n\n if attrs:\n if isinstance(attrs, list):\n valid_attrs = _table_attrs(table)\n if valid_attrs:\n for a in attrs:\n if a not in valid_attrs:\n ret['result'] = False\n ret['comment'] = '{0} is not a valid attribute for table {1}'.format(a, table)\n return ret\n _attrs = ','.join(attrs)\n else:\n ret['result'] = False\n ret['comment'] = 'Invalid table {0}.'.format(table)\n return ret\n else:\n ret['comment'] = 'attrs must be specified as a list.'\n ret['result'] = False\n return ret\n else:\n _attrs = '*'\n\n sql = 'select {0} from {1}'.format(_attrs, table)\n\n if where:\n sql = '{0} where {1}'.format(sql, where)\n\n sql = '{0};'.format(sql)\n\n res = _osquery(sql)\n if res['result']:\n ret['data'] = res['data']\n else:\n ret['comment'] = res['error']\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Support for OSQuery - https://osquery.io. .. versionadded:: 2015.8.0 ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import logging # Import Salt libs import salt.utils.json import salt.utils.path import salt.utils.platform log = logging.getLogger(__name__) __func_alias__ = { 'file_': 'file', 'hash_': 'hash', 'time_': 'time', } __virtualname__ = 'osquery' def __virtual__(): if salt.utils.path.which('osqueryi'): return __virtualname__ return (False, 'The osquery execution module cannot be loaded: ' 'osqueryi binary is not in the path.') def _table_attrs(table): ''' Helper function to find valid table attributes ''' cmd = ['osqueryi'] + ['--json'] + ['pragma table_info({0})'.format(table)] res = __salt__['cmd.run_all'](cmd) if res['retcode'] == 0: attrs = [] text = salt.utils.json.loads(res['stdout']) for item in text: attrs.append(item['name']) return attrs return False def _osquery(sql, format='json'): ''' Helper function to run raw osquery queries ''' ret = { 'result': True, } cmd = ['osqueryi'] + ['--json'] + [sql] res = __salt__['cmd.run_all'](cmd) if res['stderr']: ret['result'] = False ret['error'] = res['stderr'] else: ret['data'] = salt.utils.json.loads(res['stdout']) log.debug('== %s ==', ret) return ret def _osquery_cmd(table, attrs=None, where=None, format='json'): ''' Helper function to run osquery queries ''' ret = { 'result': True, } if attrs: if isinstance(attrs, list): valid_attrs = _table_attrs(table) if valid_attrs: for a in attrs: if a not in valid_attrs: ret['result'] = False ret['comment'] = '{0} is not a valid attribute for table {1}'.format(a, table) return ret _attrs = ','.join(attrs) else: ret['result'] = False ret['comment'] = 'Invalid table {0}.'.format(table) return ret else: ret['comment'] = 'attrs must be specified as a list.' ret['result'] = False return ret else: _attrs = '*' sql = 'select {0} from {1}'.format(_attrs, table) if where: sql = '{0} where {1}'.format(sql, where) sql = '{0};'.format(sql) res = _osquery(sql) if res['result']: ret['data'] = res['data'] else: ret['comment'] = res['error'] return ret def version(): ''' Return version of osquery CLI Example: .. code-block:: bash salt '*' osquery.version ''' _false_return = {'result': False, 'comment': 'OSQuery version unavailable.'} res = _osquery_cmd(table='osquery_info', attrs=['version']) if 'result' in res and res['result']: if 'data' in res and isinstance(res['data'], list): return res['data'][0].get('version', '') or _false_return return _false_return def rpm_packages(attrs=None, where=None): ''' Return cpuid information from osquery CLI Example: .. code-block:: bash salt '*' osquery.rpm_packages ''' if __grains__['os_family'] == 'RedHat': return _osquery_cmd(table='rpm_packages', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat based systems.'} def kernel_modules(attrs=None, where=None): ''' Return kernel_modules information from osquery CLI Example: .. code-block:: bash salt '*' osquery.kernel_modules ''' if __grains__['os_family'] in ['RedHat', 'Debian']: return _osquery_cmd(table='kernel_modules', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat or Debian based systems.'} def memory_map(attrs=None, where=None): ''' Return memory_map information from osquery CLI Example: .. code-block:: bash salt '*' osquery.memory_map ''' if __grains__['os_family'] in ['RedHat', 'Debian']: return _osquery_cmd(table='memory_map', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat or Debian based systems.'} def process_memory_map(attrs=None, where=None): ''' Return process_memory_map information from osquery CLI Example: .. code-block:: bash salt '*' osquery.process_memory_map ''' if __grains__['os_family'] in ['RedHat', 'Debian']: return _osquery_cmd(table='process_memory_map', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat or Debian based systems.'} def shared_memory(attrs=None, where=None): ''' Return shared_memory information from osquery CLI Example: .. code-block:: bash salt '*' osquery.shared_memory ''' if __grains__['os_family'] in ['RedHat', 'Debian']: return _osquery_cmd(table='shared_memory', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat or Debian based systems.'} def apt_sources(attrs=None, where=None): ''' Return apt_sources information from osquery CLI Example: .. code-block:: bash salt '*' osquery.apt_sources ''' if __grains__['os_family'] == 'Debian': return _osquery_cmd(table='apt_sources', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Debian based systems.'} def deb_packages(attrs=None, where=None): ''' Return deb_packages information from osquery CLI Example: .. code-block:: bash salt '*' osquery.deb_packages ''' if __grains__['os_family'] == 'Debian': return _osquery_cmd(table='deb_packages', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Debian based systems.'} def acpi_tables(attrs=None, where=None): ''' Return acpi_tables information from osquery CLI Example: .. code-block:: bash salt '*' osquery.acpi_tables ''' return _osquery_cmd(table='acpi_tables', attrs=attrs, where=where) def arp_cache(attrs=None, where=None): ''' Return arp_cache information from osquery CLI Example: .. code-block:: bash salt '*' osquery.arp_cache ''' return _osquery_cmd(table='arp_cache', attrs=attrs, where=where) def block_devices(attrs=None, where=None): ''' Return block_devices information from osquery CLI Example: .. code-block:: bash salt '*' osquery.block_devices ''' return _osquery_cmd(table='block_devices', attrs=attrs, where=where) def cpuid(attrs=None, where=None): ''' Return cpuid information from osquery CLI Example: .. code-block:: bash salt '*' osquery.cpuid ''' return _osquery_cmd(table='cpuid', attrs=attrs, where=where) def crontab(attrs=None, where=None): ''' Return crontab information from osquery CLI Example: .. code-block:: bash salt '*' osquery.crontab ''' return _osquery_cmd(table='crontab', attrs=attrs, where=where) def etc_hosts(attrs=None, where=None): ''' Return etc_hosts information from osquery CLI Example: .. code-block:: bash salt '*' osquery.etc_hosts ''' return _osquery_cmd(table='etc_hosts', attrs=attrs, where=where) def etc_services(attrs=None, where=None): ''' Return etc_services information from osquery CLI Example: .. code-block:: bash salt '*' osquery.etc_services ''' return _osquery_cmd(table='etc_services', attrs=attrs, where=where) def file_changes(attrs=None, where=None): ''' Return file_changes information from osquery CLI Example: .. code-block:: bash salt '*' osquery.file_changes ''' return _osquery_cmd(table='file_changes', attrs=attrs, where=where) def groups(attrs=None, where=None): ''' Return groups information from osquery CLI Example: .. code-block:: bash salt '*' osquery.groups ''' return _osquery_cmd(table='groups', attrs=attrs, where=where) def hardware_events(attrs=None, where=None): ''' Return hardware_events information from osquery CLI Example: .. code-block:: bash salt '*' osquery.hardware_events ''' return _osquery_cmd(table='hardware_events', attrs=attrs, where=where) def interface_addresses(attrs=None, where=None): ''' Return interface_addresses information from osquery CLI Example: .. code-block:: bash salt '*' osquery.interface_addresses ''' return _osquery_cmd(table='interface_addresses', attrs=attrs, where=where) def interface_details(attrs=None, where=None): ''' Return interface_details information from osquery CLI Example: .. code-block:: bash salt '*' osquery.interface_details ''' return _osquery_cmd(table='interface_details', attrs=attrs, where=where) def kernel_info(attrs=None, where=None): ''' Return kernel_info information from osquery CLI Example: .. code-block:: bash salt '*' osquery.kernel_info ''' return _osquery_cmd(table='kernel_info', attrs=attrs, where=where) def last(attrs=None, where=None): ''' Return last information from osquery CLI Example: .. code-block:: bash salt '*' osquery.last ''' return _osquery_cmd(table='last', attrs=attrs, where=where) def listening_ports(attrs=None, where=None): r''' Return listening_ports information from osquery CLI Example: .. code-block:: bash salt '*' osquery.listening_ports ''' return _osquery_cmd(table='listening_ports', attrs=attrs, where=where) def logged_in_users(attrs=None, where=None): r''' Return logged_in_users information from osquery CLI Example: .. code-block:: bash salt '*' osquery.logged_in_users ''' return _osquery_cmd(table='logged_in_users', attrs=attrs, where=where) def mounts(attrs=None, where=None): r''' Return mounts information from osquery CLI Example: .. code-block:: bash salt '*' osquery.mounts ''' return _osquery_cmd(table='mounts', attrs=attrs, where=where) def os_version(attrs=None, where=None): ''' Return os_version information from osquery CLI Example: .. code-block:: bash salt '*' osquery.os_version ''' return _osquery_cmd(table='os_version', attrs=attrs, where=where) def passwd_changes(attrs=None, where=None): ''' Return passwd_changes information from osquery CLI Example: .. code-block:: bash salt '*' osquery.passwd_changes ''' return _osquery_cmd(table='passwd_changes', attrs=attrs, where=where) def pci_devices(attrs=None, where=None): ''' Return pci_devices information from osquery CLI Example: .. code-block:: bash salt '*' osquery.pci_devices ''' return _osquery_cmd(table='pci_devices', attrs=attrs, where=where) def process_envs(attrs=None, where=None): ''' Return process_envs information from osquery CLI Example: .. code-block:: bash salt '*' osquery.process_envs ''' return _osquery_cmd(table='process_envs', attrs=attrs, where=where) def process_open_files(attrs=None, where=None): ''' Return process_open_files information from osquery CLI Example: .. code-block:: bash salt '*' osquery.process_open_files ''' return _osquery_cmd(table='process_open_files', attrs=attrs, where=where) def process_open_sockets(attrs=None, where=None): ''' Return process_open_sockets information from osquery CLI Example: .. code-block:: bash salt '*' osquery.process_open_sockets ''' return _osquery_cmd(table='process_open_sockets', attrs=attrs, where=where) def processes(attrs=None, where=None): ''' Return processes information from osquery CLI Example: .. code-block:: bash salt '*' osquery.processes ''' return _osquery_cmd(table='processes', attrs=attrs, where=where) def routes(attrs=None, where=None): ''' Return routes information from osquery CLI Example: .. code-block:: bash salt '*' osquery.routes ''' return _osquery_cmd(table='routes', attrs=attrs, where=where) def shell_history(attrs=None, where=None): ''' Return shell_history information from osquery CLI Example: .. code-block:: bash salt '*' osquery.shell_history ''' return _osquery_cmd(table='shell_history', attrs=attrs, where=where) def smbios_tables(attrs=None, where=None): ''' Return smbios_tables information from osquery CLI Example: .. code-block:: bash salt '*' osquery.smbios_tables ''' return _osquery_cmd(table='smbios_tables', attrs=attrs, where=where) def suid_bin(attrs=None, where=None): ''' Return suid_bin information from osquery CLI Example: .. code-block:: bash salt '*' osquery.suid_bin ''' return _osquery_cmd(table='suid_bin', attrs=attrs, where=where) def system_controls(attrs=None, where=None): ''' Return system_controls information from osquery CLI Example: .. code-block:: bash salt '*' osquery.system_controls ''' return _osquery_cmd(table='system_controls', attrs=attrs, where=where) def usb_devices(attrs=None, where=None): ''' Return usb_devices information from osquery CLI Example: .. code-block:: bash salt '*' osquery.usb_devices ''' return _osquery_cmd(table='usb_devices', attrs=attrs, where=where) def users(attrs=None, where=None): ''' Return users information from osquery CLI Example: .. code-block:: bash salt '*' osquery.users ''' return _osquery_cmd(table='users', attrs=attrs, where=where) def alf(attrs=None, where=None): ''' Return alf information from osquery CLI Example: .. code-block:: bash salt '*' osquery.alf ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='alf', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def alf_exceptions(attrs=None, where=None): ''' Return alf_exceptions information from osquery CLI Example: .. code-block:: bash salt '*' osquery.alf_exceptions ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='alf_exceptions', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def alf_explicit_auths(attrs=None, where=None): ''' Return alf_explicit_auths information from osquery CLI Example: .. code-block:: bash salt '*' osquery.alf_explicit_auths ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='alf_explicit_auths', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def alf_services(attrs=None, where=None): ''' Return alf_services information from osquery CLI Example: .. code-block:: bash salt '*' osquery.alf_services ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='alf_services', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def apps(attrs=None, where=None): ''' Return apps information from osquery CLI Example: .. code-block:: bash salt '*' osquery.apps ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='apps', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def certificates(attrs=None, where=None): ''' Return certificates information from osquery CLI Example: .. code-block:: bash salt '*' osquery.certificates ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='certificates', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def chrome_extensions(attrs=None, where=None): ''' Return chrome_extensions information from osquery CLI Example: .. code-block:: bash salt '*' osquery.chrome_extensions ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='chrome_extensions', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def firefox_addons(attrs=None, where=None): ''' Return firefox_addons information from osquery CLI Example: .. code-block:: bash salt '*' osquery.firefox_addons ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='firefox_addons', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def homebrew_packages(attrs=None, where=None): ''' Return homebrew_packages information from osquery CLI Example: .. code-block:: bash salt '*' osquery.homebrew_packages ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='homebrew_packages', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def iokit_devicetree(attrs=None, where=None): ''' Return iokit_devicetree information from osquery CLI Example: .. code-block:: bash salt '*' osquery.iokit_devicetree ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='iokit_devicetree', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def iokit_registry(attrs=None, where=None): ''' Return iokit_registry information from osquery CLI Example: .. code-block:: bash salt '*' osquery.iokit_registry ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='iokit_registry', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def kernel_extensions(attrs=None, where=None): ''' Return kernel_extensions information from osquery CLI Example: .. code-block:: bash salt '*' osquery.kernel_extensions ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='kernel_extensions', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def keychain_items(attrs=None, where=None): ''' Return keychain_items information from osquery CLI Example: .. code-block:: bash salt '*' osquery.keychain_items ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='keychain_items', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def launchd(attrs=None, where=None): ''' Return launchd information from osquery CLI Example: .. code-block:: bash salt '*' osquery.launchd ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='launchd', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def nfs_shares(attrs=None, where=None): ''' Return nfs_shares information from osquery CLI Example: .. code-block:: bash salt '*' osquery.nfs_shares ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='nfs_shares', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def nvram(attrs=None, where=None): ''' Return nvram information from osquery CLI Example: .. code-block:: bash salt '*' osquery.nvram ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='nvram', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def preferences(attrs=None, where=None): ''' Return preferences information from osquery CLI Example: .. code-block:: bash salt '*' osquery.preferences ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='preferences', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def quarantine(attrs=None, where=None): ''' Return quarantine information from osquery CLI Example: .. code-block:: bash salt '*' osquery.quarantine ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='quarantine', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def safari_extensions(attrs=None, where=None): ''' Return safari_extensions information from osquery CLI Example: .. code-block:: bash salt '*' osquery.safari_extensions ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='safari_extensions', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def startup_items(attrs=None, where=None): ''' Return startup_items information from osquery CLI Example: .. code-block:: bash salt '*' osquery.startup_items ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='startup_items', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def xattr_where_from(attrs=None, where=None): ''' Return xattr_where_from information from osquery CLI Example: .. code-block:: bash salt '*' osquery.xattr_where_from ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='xattr_where_from', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def xprotect_entries(attrs=None, where=None): ''' Return xprotect_entries information from osquery CLI Example: .. code-block:: bash salt '*' osquery.xprotect_entries ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='xprotect_entries', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def xprotect_reports(attrs=None, where=None): ''' Return xprotect_reports information from osquery CLI Example: .. code-block:: bash salt '*' osquery.xprotect_reports ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='xprotect_reports', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def file_(attrs=None, where=None): ''' Return file information from osquery CLI Example: .. code-block:: bash salt '*' osquery.file ''' return _osquery_cmd(table='file', attrs=attrs, where=where) def hash_(attrs=None, where=None): ''' Return hash information from osquery CLI Example: .. code-block:: bash salt '*' osquery.hash ''' return _osquery_cmd(table='hash', attrs=attrs, where=where) def osquery_extensions(attrs=None, where=None): ''' Return osquery_extensions information from osquery CLI Example: .. code-block:: bash salt '*' osquery.osquery_extensions ''' return _osquery_cmd(table='osquery_extensions', attrs=attrs, where=where) def osquery_flags(attrs=None, where=None): ''' Return osquery_flags information from osquery CLI Example: .. code-block:: bash salt '*' osquery.osquery_flags ''' return _osquery_cmd(table='osquery_flags', attrs=attrs, where=where) def osquery_info(attrs=None, where=None): ''' Return osquery_info information from osquery CLI Example: .. code-block:: bash salt '*' osquery.osquery_info ''' return _osquery_cmd(table='osquery_info', attrs=attrs, where=where) def osquery_registry(attrs=None, where=None): ''' Return osquery_registry information from osquery CLI Example: .. code-block:: bash salt '*' osquery.osquery_registry ''' return _osquery_cmd(table='osquery_registry', attrs=attrs, where=where) def time_(attrs=None): ''' Return time information from osquery CLI Example: .. code-block:: bash salt '*' osquery.time ''' return _osquery_cmd(table='time', attrs=attrs) def query(sql=None): ''' Return time information from osquery CLI Example: .. code-block:: bash salt '*' osquery.query "select * from users;" ''' return _osquery(sql)
saltstack/salt
salt/modules/osquery.py
kernel_modules
python
def kernel_modules(attrs=None, where=None): ''' Return kernel_modules information from osquery CLI Example: .. code-block:: bash salt '*' osquery.kernel_modules ''' if __grains__['os_family'] in ['RedHat', 'Debian']: return _osquery_cmd(table='kernel_modules', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat or Debian based systems.'}
Return kernel_modules information from osquery CLI Example: .. code-block:: bash salt '*' osquery.kernel_modules
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/osquery.py#L164-L176
[ "def _osquery_cmd(table, attrs=None, where=None, format='json'):\n '''\n Helper function to run osquery queries\n '''\n ret = {\n 'result': True,\n }\n\n if attrs:\n if isinstance(attrs, list):\n valid_attrs = _table_attrs(table)\n if valid_attrs:\n for a in attrs:\n if a not in valid_attrs:\n ret['result'] = False\n ret['comment'] = '{0} is not a valid attribute for table {1}'.format(a, table)\n return ret\n _attrs = ','.join(attrs)\n else:\n ret['result'] = False\n ret['comment'] = 'Invalid table {0}.'.format(table)\n return ret\n else:\n ret['comment'] = 'attrs must be specified as a list.'\n ret['result'] = False\n return ret\n else:\n _attrs = '*'\n\n sql = 'select {0} from {1}'.format(_attrs, table)\n\n if where:\n sql = '{0} where {1}'.format(sql, where)\n\n sql = '{0};'.format(sql)\n\n res = _osquery(sql)\n if res['result']:\n ret['data'] = res['data']\n else:\n ret['comment'] = res['error']\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Support for OSQuery - https://osquery.io. .. versionadded:: 2015.8.0 ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import logging # Import Salt libs import salt.utils.json import salt.utils.path import salt.utils.platform log = logging.getLogger(__name__) __func_alias__ = { 'file_': 'file', 'hash_': 'hash', 'time_': 'time', } __virtualname__ = 'osquery' def __virtual__(): if salt.utils.path.which('osqueryi'): return __virtualname__ return (False, 'The osquery execution module cannot be loaded: ' 'osqueryi binary is not in the path.') def _table_attrs(table): ''' Helper function to find valid table attributes ''' cmd = ['osqueryi'] + ['--json'] + ['pragma table_info({0})'.format(table)] res = __salt__['cmd.run_all'](cmd) if res['retcode'] == 0: attrs = [] text = salt.utils.json.loads(res['stdout']) for item in text: attrs.append(item['name']) return attrs return False def _osquery(sql, format='json'): ''' Helper function to run raw osquery queries ''' ret = { 'result': True, } cmd = ['osqueryi'] + ['--json'] + [sql] res = __salt__['cmd.run_all'](cmd) if res['stderr']: ret['result'] = False ret['error'] = res['stderr'] else: ret['data'] = salt.utils.json.loads(res['stdout']) log.debug('== %s ==', ret) return ret def _osquery_cmd(table, attrs=None, where=None, format='json'): ''' Helper function to run osquery queries ''' ret = { 'result': True, } if attrs: if isinstance(attrs, list): valid_attrs = _table_attrs(table) if valid_attrs: for a in attrs: if a not in valid_attrs: ret['result'] = False ret['comment'] = '{0} is not a valid attribute for table {1}'.format(a, table) return ret _attrs = ','.join(attrs) else: ret['result'] = False ret['comment'] = 'Invalid table {0}.'.format(table) return ret else: ret['comment'] = 'attrs must be specified as a list.' ret['result'] = False return ret else: _attrs = '*' sql = 'select {0} from {1}'.format(_attrs, table) if where: sql = '{0} where {1}'.format(sql, where) sql = '{0};'.format(sql) res = _osquery(sql) if res['result']: ret['data'] = res['data'] else: ret['comment'] = res['error'] return ret def version(): ''' Return version of osquery CLI Example: .. code-block:: bash salt '*' osquery.version ''' _false_return = {'result': False, 'comment': 'OSQuery version unavailable.'} res = _osquery_cmd(table='osquery_info', attrs=['version']) if 'result' in res and res['result']: if 'data' in res and isinstance(res['data'], list): return res['data'][0].get('version', '') or _false_return return _false_return def rpm_packages(attrs=None, where=None): ''' Return cpuid information from osquery CLI Example: .. code-block:: bash salt '*' osquery.rpm_packages ''' if __grains__['os_family'] == 'RedHat': return _osquery_cmd(table='rpm_packages', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat based systems.'} def kernel_integrity(attrs=None, where=None): ''' Return kernel_integrity information from osquery CLI Example: .. code-block:: bash salt '*' osquery.kernel_integrity ''' if __grains__['os_family'] in ['RedHat', 'Debian']: return _osquery_cmd(table='kernel_integrity', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat or Debian based systems.'} def memory_map(attrs=None, where=None): ''' Return memory_map information from osquery CLI Example: .. code-block:: bash salt '*' osquery.memory_map ''' if __grains__['os_family'] in ['RedHat', 'Debian']: return _osquery_cmd(table='memory_map', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat or Debian based systems.'} def process_memory_map(attrs=None, where=None): ''' Return process_memory_map information from osquery CLI Example: .. code-block:: bash salt '*' osquery.process_memory_map ''' if __grains__['os_family'] in ['RedHat', 'Debian']: return _osquery_cmd(table='process_memory_map', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat or Debian based systems.'} def shared_memory(attrs=None, where=None): ''' Return shared_memory information from osquery CLI Example: .. code-block:: bash salt '*' osquery.shared_memory ''' if __grains__['os_family'] in ['RedHat', 'Debian']: return _osquery_cmd(table='shared_memory', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat or Debian based systems.'} def apt_sources(attrs=None, where=None): ''' Return apt_sources information from osquery CLI Example: .. code-block:: bash salt '*' osquery.apt_sources ''' if __grains__['os_family'] == 'Debian': return _osquery_cmd(table='apt_sources', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Debian based systems.'} def deb_packages(attrs=None, where=None): ''' Return deb_packages information from osquery CLI Example: .. code-block:: bash salt '*' osquery.deb_packages ''' if __grains__['os_family'] == 'Debian': return _osquery_cmd(table='deb_packages', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Debian based systems.'} def acpi_tables(attrs=None, where=None): ''' Return acpi_tables information from osquery CLI Example: .. code-block:: bash salt '*' osquery.acpi_tables ''' return _osquery_cmd(table='acpi_tables', attrs=attrs, where=where) def arp_cache(attrs=None, where=None): ''' Return arp_cache information from osquery CLI Example: .. code-block:: bash salt '*' osquery.arp_cache ''' return _osquery_cmd(table='arp_cache', attrs=attrs, where=where) def block_devices(attrs=None, where=None): ''' Return block_devices information from osquery CLI Example: .. code-block:: bash salt '*' osquery.block_devices ''' return _osquery_cmd(table='block_devices', attrs=attrs, where=where) def cpuid(attrs=None, where=None): ''' Return cpuid information from osquery CLI Example: .. code-block:: bash salt '*' osquery.cpuid ''' return _osquery_cmd(table='cpuid', attrs=attrs, where=where) def crontab(attrs=None, where=None): ''' Return crontab information from osquery CLI Example: .. code-block:: bash salt '*' osquery.crontab ''' return _osquery_cmd(table='crontab', attrs=attrs, where=where) def etc_hosts(attrs=None, where=None): ''' Return etc_hosts information from osquery CLI Example: .. code-block:: bash salt '*' osquery.etc_hosts ''' return _osquery_cmd(table='etc_hosts', attrs=attrs, where=where) def etc_services(attrs=None, where=None): ''' Return etc_services information from osquery CLI Example: .. code-block:: bash salt '*' osquery.etc_services ''' return _osquery_cmd(table='etc_services', attrs=attrs, where=where) def file_changes(attrs=None, where=None): ''' Return file_changes information from osquery CLI Example: .. code-block:: bash salt '*' osquery.file_changes ''' return _osquery_cmd(table='file_changes', attrs=attrs, where=where) def groups(attrs=None, where=None): ''' Return groups information from osquery CLI Example: .. code-block:: bash salt '*' osquery.groups ''' return _osquery_cmd(table='groups', attrs=attrs, where=where) def hardware_events(attrs=None, where=None): ''' Return hardware_events information from osquery CLI Example: .. code-block:: bash salt '*' osquery.hardware_events ''' return _osquery_cmd(table='hardware_events', attrs=attrs, where=where) def interface_addresses(attrs=None, where=None): ''' Return interface_addresses information from osquery CLI Example: .. code-block:: bash salt '*' osquery.interface_addresses ''' return _osquery_cmd(table='interface_addresses', attrs=attrs, where=where) def interface_details(attrs=None, where=None): ''' Return interface_details information from osquery CLI Example: .. code-block:: bash salt '*' osquery.interface_details ''' return _osquery_cmd(table='interface_details', attrs=attrs, where=where) def kernel_info(attrs=None, where=None): ''' Return kernel_info information from osquery CLI Example: .. code-block:: bash salt '*' osquery.kernel_info ''' return _osquery_cmd(table='kernel_info', attrs=attrs, where=where) def last(attrs=None, where=None): ''' Return last information from osquery CLI Example: .. code-block:: bash salt '*' osquery.last ''' return _osquery_cmd(table='last', attrs=attrs, where=where) def listening_ports(attrs=None, where=None): r''' Return listening_ports information from osquery CLI Example: .. code-block:: bash salt '*' osquery.listening_ports ''' return _osquery_cmd(table='listening_ports', attrs=attrs, where=where) def logged_in_users(attrs=None, where=None): r''' Return logged_in_users information from osquery CLI Example: .. code-block:: bash salt '*' osquery.logged_in_users ''' return _osquery_cmd(table='logged_in_users', attrs=attrs, where=where) def mounts(attrs=None, where=None): r''' Return mounts information from osquery CLI Example: .. code-block:: bash salt '*' osquery.mounts ''' return _osquery_cmd(table='mounts', attrs=attrs, where=where) def os_version(attrs=None, where=None): ''' Return os_version information from osquery CLI Example: .. code-block:: bash salt '*' osquery.os_version ''' return _osquery_cmd(table='os_version', attrs=attrs, where=where) def passwd_changes(attrs=None, where=None): ''' Return passwd_changes information from osquery CLI Example: .. code-block:: bash salt '*' osquery.passwd_changes ''' return _osquery_cmd(table='passwd_changes', attrs=attrs, where=where) def pci_devices(attrs=None, where=None): ''' Return pci_devices information from osquery CLI Example: .. code-block:: bash salt '*' osquery.pci_devices ''' return _osquery_cmd(table='pci_devices', attrs=attrs, where=where) def process_envs(attrs=None, where=None): ''' Return process_envs information from osquery CLI Example: .. code-block:: bash salt '*' osquery.process_envs ''' return _osquery_cmd(table='process_envs', attrs=attrs, where=where) def process_open_files(attrs=None, where=None): ''' Return process_open_files information from osquery CLI Example: .. code-block:: bash salt '*' osquery.process_open_files ''' return _osquery_cmd(table='process_open_files', attrs=attrs, where=where) def process_open_sockets(attrs=None, where=None): ''' Return process_open_sockets information from osquery CLI Example: .. code-block:: bash salt '*' osquery.process_open_sockets ''' return _osquery_cmd(table='process_open_sockets', attrs=attrs, where=where) def processes(attrs=None, where=None): ''' Return processes information from osquery CLI Example: .. code-block:: bash salt '*' osquery.processes ''' return _osquery_cmd(table='processes', attrs=attrs, where=where) def routes(attrs=None, where=None): ''' Return routes information from osquery CLI Example: .. code-block:: bash salt '*' osquery.routes ''' return _osquery_cmd(table='routes', attrs=attrs, where=where) def shell_history(attrs=None, where=None): ''' Return shell_history information from osquery CLI Example: .. code-block:: bash salt '*' osquery.shell_history ''' return _osquery_cmd(table='shell_history', attrs=attrs, where=where) def smbios_tables(attrs=None, where=None): ''' Return smbios_tables information from osquery CLI Example: .. code-block:: bash salt '*' osquery.smbios_tables ''' return _osquery_cmd(table='smbios_tables', attrs=attrs, where=where) def suid_bin(attrs=None, where=None): ''' Return suid_bin information from osquery CLI Example: .. code-block:: bash salt '*' osquery.suid_bin ''' return _osquery_cmd(table='suid_bin', attrs=attrs, where=where) def system_controls(attrs=None, where=None): ''' Return system_controls information from osquery CLI Example: .. code-block:: bash salt '*' osquery.system_controls ''' return _osquery_cmd(table='system_controls', attrs=attrs, where=where) def usb_devices(attrs=None, where=None): ''' Return usb_devices information from osquery CLI Example: .. code-block:: bash salt '*' osquery.usb_devices ''' return _osquery_cmd(table='usb_devices', attrs=attrs, where=where) def users(attrs=None, where=None): ''' Return users information from osquery CLI Example: .. code-block:: bash salt '*' osquery.users ''' return _osquery_cmd(table='users', attrs=attrs, where=where) def alf(attrs=None, where=None): ''' Return alf information from osquery CLI Example: .. code-block:: bash salt '*' osquery.alf ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='alf', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def alf_exceptions(attrs=None, where=None): ''' Return alf_exceptions information from osquery CLI Example: .. code-block:: bash salt '*' osquery.alf_exceptions ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='alf_exceptions', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def alf_explicit_auths(attrs=None, where=None): ''' Return alf_explicit_auths information from osquery CLI Example: .. code-block:: bash salt '*' osquery.alf_explicit_auths ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='alf_explicit_auths', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def alf_services(attrs=None, where=None): ''' Return alf_services information from osquery CLI Example: .. code-block:: bash salt '*' osquery.alf_services ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='alf_services', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def apps(attrs=None, where=None): ''' Return apps information from osquery CLI Example: .. code-block:: bash salt '*' osquery.apps ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='apps', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def certificates(attrs=None, where=None): ''' Return certificates information from osquery CLI Example: .. code-block:: bash salt '*' osquery.certificates ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='certificates', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def chrome_extensions(attrs=None, where=None): ''' Return chrome_extensions information from osquery CLI Example: .. code-block:: bash salt '*' osquery.chrome_extensions ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='chrome_extensions', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def firefox_addons(attrs=None, where=None): ''' Return firefox_addons information from osquery CLI Example: .. code-block:: bash salt '*' osquery.firefox_addons ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='firefox_addons', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def homebrew_packages(attrs=None, where=None): ''' Return homebrew_packages information from osquery CLI Example: .. code-block:: bash salt '*' osquery.homebrew_packages ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='homebrew_packages', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def iokit_devicetree(attrs=None, where=None): ''' Return iokit_devicetree information from osquery CLI Example: .. code-block:: bash salt '*' osquery.iokit_devicetree ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='iokit_devicetree', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def iokit_registry(attrs=None, where=None): ''' Return iokit_registry information from osquery CLI Example: .. code-block:: bash salt '*' osquery.iokit_registry ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='iokit_registry', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def kernel_extensions(attrs=None, where=None): ''' Return kernel_extensions information from osquery CLI Example: .. code-block:: bash salt '*' osquery.kernel_extensions ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='kernel_extensions', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def keychain_items(attrs=None, where=None): ''' Return keychain_items information from osquery CLI Example: .. code-block:: bash salt '*' osquery.keychain_items ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='keychain_items', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def launchd(attrs=None, where=None): ''' Return launchd information from osquery CLI Example: .. code-block:: bash salt '*' osquery.launchd ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='launchd', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def nfs_shares(attrs=None, where=None): ''' Return nfs_shares information from osquery CLI Example: .. code-block:: bash salt '*' osquery.nfs_shares ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='nfs_shares', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def nvram(attrs=None, where=None): ''' Return nvram information from osquery CLI Example: .. code-block:: bash salt '*' osquery.nvram ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='nvram', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def preferences(attrs=None, where=None): ''' Return preferences information from osquery CLI Example: .. code-block:: bash salt '*' osquery.preferences ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='preferences', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def quarantine(attrs=None, where=None): ''' Return quarantine information from osquery CLI Example: .. code-block:: bash salt '*' osquery.quarantine ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='quarantine', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def safari_extensions(attrs=None, where=None): ''' Return safari_extensions information from osquery CLI Example: .. code-block:: bash salt '*' osquery.safari_extensions ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='safari_extensions', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def startup_items(attrs=None, where=None): ''' Return startup_items information from osquery CLI Example: .. code-block:: bash salt '*' osquery.startup_items ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='startup_items', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def xattr_where_from(attrs=None, where=None): ''' Return xattr_where_from information from osquery CLI Example: .. code-block:: bash salt '*' osquery.xattr_where_from ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='xattr_where_from', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def xprotect_entries(attrs=None, where=None): ''' Return xprotect_entries information from osquery CLI Example: .. code-block:: bash salt '*' osquery.xprotect_entries ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='xprotect_entries', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def xprotect_reports(attrs=None, where=None): ''' Return xprotect_reports information from osquery CLI Example: .. code-block:: bash salt '*' osquery.xprotect_reports ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='xprotect_reports', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def file_(attrs=None, where=None): ''' Return file information from osquery CLI Example: .. code-block:: bash salt '*' osquery.file ''' return _osquery_cmd(table='file', attrs=attrs, where=where) def hash_(attrs=None, where=None): ''' Return hash information from osquery CLI Example: .. code-block:: bash salt '*' osquery.hash ''' return _osquery_cmd(table='hash', attrs=attrs, where=where) def osquery_extensions(attrs=None, where=None): ''' Return osquery_extensions information from osquery CLI Example: .. code-block:: bash salt '*' osquery.osquery_extensions ''' return _osquery_cmd(table='osquery_extensions', attrs=attrs, where=where) def osquery_flags(attrs=None, where=None): ''' Return osquery_flags information from osquery CLI Example: .. code-block:: bash salt '*' osquery.osquery_flags ''' return _osquery_cmd(table='osquery_flags', attrs=attrs, where=where) def osquery_info(attrs=None, where=None): ''' Return osquery_info information from osquery CLI Example: .. code-block:: bash salt '*' osquery.osquery_info ''' return _osquery_cmd(table='osquery_info', attrs=attrs, where=where) def osquery_registry(attrs=None, where=None): ''' Return osquery_registry information from osquery CLI Example: .. code-block:: bash salt '*' osquery.osquery_registry ''' return _osquery_cmd(table='osquery_registry', attrs=attrs, where=where) def time_(attrs=None): ''' Return time information from osquery CLI Example: .. code-block:: bash salt '*' osquery.time ''' return _osquery_cmd(table='time', attrs=attrs) def query(sql=None): ''' Return time information from osquery CLI Example: .. code-block:: bash salt '*' osquery.query "select * from users;" ''' return _osquery(sql)
saltstack/salt
salt/modules/osquery.py
memory_map
python
def memory_map(attrs=None, where=None): ''' Return memory_map information from osquery CLI Example: .. code-block:: bash salt '*' osquery.memory_map ''' if __grains__['os_family'] in ['RedHat', 'Debian']: return _osquery_cmd(table='memory_map', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat or Debian based systems.'}
Return memory_map information from osquery CLI Example: .. code-block:: bash salt '*' osquery.memory_map
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/osquery.py#L179-L191
[ "def _osquery_cmd(table, attrs=None, where=None, format='json'):\n '''\n Helper function to run osquery queries\n '''\n ret = {\n 'result': True,\n }\n\n if attrs:\n if isinstance(attrs, list):\n valid_attrs = _table_attrs(table)\n if valid_attrs:\n for a in attrs:\n if a not in valid_attrs:\n ret['result'] = False\n ret['comment'] = '{0} is not a valid attribute for table {1}'.format(a, table)\n return ret\n _attrs = ','.join(attrs)\n else:\n ret['result'] = False\n ret['comment'] = 'Invalid table {0}.'.format(table)\n return ret\n else:\n ret['comment'] = 'attrs must be specified as a list.'\n ret['result'] = False\n return ret\n else:\n _attrs = '*'\n\n sql = 'select {0} from {1}'.format(_attrs, table)\n\n if where:\n sql = '{0} where {1}'.format(sql, where)\n\n sql = '{0};'.format(sql)\n\n res = _osquery(sql)\n if res['result']:\n ret['data'] = res['data']\n else:\n ret['comment'] = res['error']\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Support for OSQuery - https://osquery.io. .. versionadded:: 2015.8.0 ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import logging # Import Salt libs import salt.utils.json import salt.utils.path import salt.utils.platform log = logging.getLogger(__name__) __func_alias__ = { 'file_': 'file', 'hash_': 'hash', 'time_': 'time', } __virtualname__ = 'osquery' def __virtual__(): if salt.utils.path.which('osqueryi'): return __virtualname__ return (False, 'The osquery execution module cannot be loaded: ' 'osqueryi binary is not in the path.') def _table_attrs(table): ''' Helper function to find valid table attributes ''' cmd = ['osqueryi'] + ['--json'] + ['pragma table_info({0})'.format(table)] res = __salt__['cmd.run_all'](cmd) if res['retcode'] == 0: attrs = [] text = salt.utils.json.loads(res['stdout']) for item in text: attrs.append(item['name']) return attrs return False def _osquery(sql, format='json'): ''' Helper function to run raw osquery queries ''' ret = { 'result': True, } cmd = ['osqueryi'] + ['--json'] + [sql] res = __salt__['cmd.run_all'](cmd) if res['stderr']: ret['result'] = False ret['error'] = res['stderr'] else: ret['data'] = salt.utils.json.loads(res['stdout']) log.debug('== %s ==', ret) return ret def _osquery_cmd(table, attrs=None, where=None, format='json'): ''' Helper function to run osquery queries ''' ret = { 'result': True, } if attrs: if isinstance(attrs, list): valid_attrs = _table_attrs(table) if valid_attrs: for a in attrs: if a not in valid_attrs: ret['result'] = False ret['comment'] = '{0} is not a valid attribute for table {1}'.format(a, table) return ret _attrs = ','.join(attrs) else: ret['result'] = False ret['comment'] = 'Invalid table {0}.'.format(table) return ret else: ret['comment'] = 'attrs must be specified as a list.' ret['result'] = False return ret else: _attrs = '*' sql = 'select {0} from {1}'.format(_attrs, table) if where: sql = '{0} where {1}'.format(sql, where) sql = '{0};'.format(sql) res = _osquery(sql) if res['result']: ret['data'] = res['data'] else: ret['comment'] = res['error'] return ret def version(): ''' Return version of osquery CLI Example: .. code-block:: bash salt '*' osquery.version ''' _false_return = {'result': False, 'comment': 'OSQuery version unavailable.'} res = _osquery_cmd(table='osquery_info', attrs=['version']) if 'result' in res and res['result']: if 'data' in res and isinstance(res['data'], list): return res['data'][0].get('version', '') or _false_return return _false_return def rpm_packages(attrs=None, where=None): ''' Return cpuid information from osquery CLI Example: .. code-block:: bash salt '*' osquery.rpm_packages ''' if __grains__['os_family'] == 'RedHat': return _osquery_cmd(table='rpm_packages', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat based systems.'} def kernel_integrity(attrs=None, where=None): ''' Return kernel_integrity information from osquery CLI Example: .. code-block:: bash salt '*' osquery.kernel_integrity ''' if __grains__['os_family'] in ['RedHat', 'Debian']: return _osquery_cmd(table='kernel_integrity', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat or Debian based systems.'} def kernel_modules(attrs=None, where=None): ''' Return kernel_modules information from osquery CLI Example: .. code-block:: bash salt '*' osquery.kernel_modules ''' if __grains__['os_family'] in ['RedHat', 'Debian']: return _osquery_cmd(table='kernel_modules', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat or Debian based systems.'} def process_memory_map(attrs=None, where=None): ''' Return process_memory_map information from osquery CLI Example: .. code-block:: bash salt '*' osquery.process_memory_map ''' if __grains__['os_family'] in ['RedHat', 'Debian']: return _osquery_cmd(table='process_memory_map', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat or Debian based systems.'} def shared_memory(attrs=None, where=None): ''' Return shared_memory information from osquery CLI Example: .. code-block:: bash salt '*' osquery.shared_memory ''' if __grains__['os_family'] in ['RedHat', 'Debian']: return _osquery_cmd(table='shared_memory', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat or Debian based systems.'} def apt_sources(attrs=None, where=None): ''' Return apt_sources information from osquery CLI Example: .. code-block:: bash salt '*' osquery.apt_sources ''' if __grains__['os_family'] == 'Debian': return _osquery_cmd(table='apt_sources', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Debian based systems.'} def deb_packages(attrs=None, where=None): ''' Return deb_packages information from osquery CLI Example: .. code-block:: bash salt '*' osquery.deb_packages ''' if __grains__['os_family'] == 'Debian': return _osquery_cmd(table='deb_packages', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Debian based systems.'} def acpi_tables(attrs=None, where=None): ''' Return acpi_tables information from osquery CLI Example: .. code-block:: bash salt '*' osquery.acpi_tables ''' return _osquery_cmd(table='acpi_tables', attrs=attrs, where=where) def arp_cache(attrs=None, where=None): ''' Return arp_cache information from osquery CLI Example: .. code-block:: bash salt '*' osquery.arp_cache ''' return _osquery_cmd(table='arp_cache', attrs=attrs, where=where) def block_devices(attrs=None, where=None): ''' Return block_devices information from osquery CLI Example: .. code-block:: bash salt '*' osquery.block_devices ''' return _osquery_cmd(table='block_devices', attrs=attrs, where=where) def cpuid(attrs=None, where=None): ''' Return cpuid information from osquery CLI Example: .. code-block:: bash salt '*' osquery.cpuid ''' return _osquery_cmd(table='cpuid', attrs=attrs, where=where) def crontab(attrs=None, where=None): ''' Return crontab information from osquery CLI Example: .. code-block:: bash salt '*' osquery.crontab ''' return _osquery_cmd(table='crontab', attrs=attrs, where=where) def etc_hosts(attrs=None, where=None): ''' Return etc_hosts information from osquery CLI Example: .. code-block:: bash salt '*' osquery.etc_hosts ''' return _osquery_cmd(table='etc_hosts', attrs=attrs, where=where) def etc_services(attrs=None, where=None): ''' Return etc_services information from osquery CLI Example: .. code-block:: bash salt '*' osquery.etc_services ''' return _osquery_cmd(table='etc_services', attrs=attrs, where=where) def file_changes(attrs=None, where=None): ''' Return file_changes information from osquery CLI Example: .. code-block:: bash salt '*' osquery.file_changes ''' return _osquery_cmd(table='file_changes', attrs=attrs, where=where) def groups(attrs=None, where=None): ''' Return groups information from osquery CLI Example: .. code-block:: bash salt '*' osquery.groups ''' return _osquery_cmd(table='groups', attrs=attrs, where=where) def hardware_events(attrs=None, where=None): ''' Return hardware_events information from osquery CLI Example: .. code-block:: bash salt '*' osquery.hardware_events ''' return _osquery_cmd(table='hardware_events', attrs=attrs, where=where) def interface_addresses(attrs=None, where=None): ''' Return interface_addresses information from osquery CLI Example: .. code-block:: bash salt '*' osquery.interface_addresses ''' return _osquery_cmd(table='interface_addresses', attrs=attrs, where=where) def interface_details(attrs=None, where=None): ''' Return interface_details information from osquery CLI Example: .. code-block:: bash salt '*' osquery.interface_details ''' return _osquery_cmd(table='interface_details', attrs=attrs, where=where) def kernel_info(attrs=None, where=None): ''' Return kernel_info information from osquery CLI Example: .. code-block:: bash salt '*' osquery.kernel_info ''' return _osquery_cmd(table='kernel_info', attrs=attrs, where=where) def last(attrs=None, where=None): ''' Return last information from osquery CLI Example: .. code-block:: bash salt '*' osquery.last ''' return _osquery_cmd(table='last', attrs=attrs, where=where) def listening_ports(attrs=None, where=None): r''' Return listening_ports information from osquery CLI Example: .. code-block:: bash salt '*' osquery.listening_ports ''' return _osquery_cmd(table='listening_ports', attrs=attrs, where=where) def logged_in_users(attrs=None, where=None): r''' Return logged_in_users information from osquery CLI Example: .. code-block:: bash salt '*' osquery.logged_in_users ''' return _osquery_cmd(table='logged_in_users', attrs=attrs, where=where) def mounts(attrs=None, where=None): r''' Return mounts information from osquery CLI Example: .. code-block:: bash salt '*' osquery.mounts ''' return _osquery_cmd(table='mounts', attrs=attrs, where=where) def os_version(attrs=None, where=None): ''' Return os_version information from osquery CLI Example: .. code-block:: bash salt '*' osquery.os_version ''' return _osquery_cmd(table='os_version', attrs=attrs, where=where) def passwd_changes(attrs=None, where=None): ''' Return passwd_changes information from osquery CLI Example: .. code-block:: bash salt '*' osquery.passwd_changes ''' return _osquery_cmd(table='passwd_changes', attrs=attrs, where=where) def pci_devices(attrs=None, where=None): ''' Return pci_devices information from osquery CLI Example: .. code-block:: bash salt '*' osquery.pci_devices ''' return _osquery_cmd(table='pci_devices', attrs=attrs, where=where) def process_envs(attrs=None, where=None): ''' Return process_envs information from osquery CLI Example: .. code-block:: bash salt '*' osquery.process_envs ''' return _osquery_cmd(table='process_envs', attrs=attrs, where=where) def process_open_files(attrs=None, where=None): ''' Return process_open_files information from osquery CLI Example: .. code-block:: bash salt '*' osquery.process_open_files ''' return _osquery_cmd(table='process_open_files', attrs=attrs, where=where) def process_open_sockets(attrs=None, where=None): ''' Return process_open_sockets information from osquery CLI Example: .. code-block:: bash salt '*' osquery.process_open_sockets ''' return _osquery_cmd(table='process_open_sockets', attrs=attrs, where=where) def processes(attrs=None, where=None): ''' Return processes information from osquery CLI Example: .. code-block:: bash salt '*' osquery.processes ''' return _osquery_cmd(table='processes', attrs=attrs, where=where) def routes(attrs=None, where=None): ''' Return routes information from osquery CLI Example: .. code-block:: bash salt '*' osquery.routes ''' return _osquery_cmd(table='routes', attrs=attrs, where=where) def shell_history(attrs=None, where=None): ''' Return shell_history information from osquery CLI Example: .. code-block:: bash salt '*' osquery.shell_history ''' return _osquery_cmd(table='shell_history', attrs=attrs, where=where) def smbios_tables(attrs=None, where=None): ''' Return smbios_tables information from osquery CLI Example: .. code-block:: bash salt '*' osquery.smbios_tables ''' return _osquery_cmd(table='smbios_tables', attrs=attrs, where=where) def suid_bin(attrs=None, where=None): ''' Return suid_bin information from osquery CLI Example: .. code-block:: bash salt '*' osquery.suid_bin ''' return _osquery_cmd(table='suid_bin', attrs=attrs, where=where) def system_controls(attrs=None, where=None): ''' Return system_controls information from osquery CLI Example: .. code-block:: bash salt '*' osquery.system_controls ''' return _osquery_cmd(table='system_controls', attrs=attrs, where=where) def usb_devices(attrs=None, where=None): ''' Return usb_devices information from osquery CLI Example: .. code-block:: bash salt '*' osquery.usb_devices ''' return _osquery_cmd(table='usb_devices', attrs=attrs, where=where) def users(attrs=None, where=None): ''' Return users information from osquery CLI Example: .. code-block:: bash salt '*' osquery.users ''' return _osquery_cmd(table='users', attrs=attrs, where=where) def alf(attrs=None, where=None): ''' Return alf information from osquery CLI Example: .. code-block:: bash salt '*' osquery.alf ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='alf', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def alf_exceptions(attrs=None, where=None): ''' Return alf_exceptions information from osquery CLI Example: .. code-block:: bash salt '*' osquery.alf_exceptions ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='alf_exceptions', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def alf_explicit_auths(attrs=None, where=None): ''' Return alf_explicit_auths information from osquery CLI Example: .. code-block:: bash salt '*' osquery.alf_explicit_auths ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='alf_explicit_auths', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def alf_services(attrs=None, where=None): ''' Return alf_services information from osquery CLI Example: .. code-block:: bash salt '*' osquery.alf_services ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='alf_services', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def apps(attrs=None, where=None): ''' Return apps information from osquery CLI Example: .. code-block:: bash salt '*' osquery.apps ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='apps', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def certificates(attrs=None, where=None): ''' Return certificates information from osquery CLI Example: .. code-block:: bash salt '*' osquery.certificates ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='certificates', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def chrome_extensions(attrs=None, where=None): ''' Return chrome_extensions information from osquery CLI Example: .. code-block:: bash salt '*' osquery.chrome_extensions ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='chrome_extensions', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def firefox_addons(attrs=None, where=None): ''' Return firefox_addons information from osquery CLI Example: .. code-block:: bash salt '*' osquery.firefox_addons ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='firefox_addons', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def homebrew_packages(attrs=None, where=None): ''' Return homebrew_packages information from osquery CLI Example: .. code-block:: bash salt '*' osquery.homebrew_packages ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='homebrew_packages', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def iokit_devicetree(attrs=None, where=None): ''' Return iokit_devicetree information from osquery CLI Example: .. code-block:: bash salt '*' osquery.iokit_devicetree ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='iokit_devicetree', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def iokit_registry(attrs=None, where=None): ''' Return iokit_registry information from osquery CLI Example: .. code-block:: bash salt '*' osquery.iokit_registry ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='iokit_registry', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def kernel_extensions(attrs=None, where=None): ''' Return kernel_extensions information from osquery CLI Example: .. code-block:: bash salt '*' osquery.kernel_extensions ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='kernel_extensions', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def keychain_items(attrs=None, where=None): ''' Return keychain_items information from osquery CLI Example: .. code-block:: bash salt '*' osquery.keychain_items ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='keychain_items', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def launchd(attrs=None, where=None): ''' Return launchd information from osquery CLI Example: .. code-block:: bash salt '*' osquery.launchd ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='launchd', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def nfs_shares(attrs=None, where=None): ''' Return nfs_shares information from osquery CLI Example: .. code-block:: bash salt '*' osquery.nfs_shares ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='nfs_shares', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def nvram(attrs=None, where=None): ''' Return nvram information from osquery CLI Example: .. code-block:: bash salt '*' osquery.nvram ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='nvram', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def preferences(attrs=None, where=None): ''' Return preferences information from osquery CLI Example: .. code-block:: bash salt '*' osquery.preferences ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='preferences', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def quarantine(attrs=None, where=None): ''' Return quarantine information from osquery CLI Example: .. code-block:: bash salt '*' osquery.quarantine ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='quarantine', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def safari_extensions(attrs=None, where=None): ''' Return safari_extensions information from osquery CLI Example: .. code-block:: bash salt '*' osquery.safari_extensions ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='safari_extensions', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def startup_items(attrs=None, where=None): ''' Return startup_items information from osquery CLI Example: .. code-block:: bash salt '*' osquery.startup_items ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='startup_items', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def xattr_where_from(attrs=None, where=None): ''' Return xattr_where_from information from osquery CLI Example: .. code-block:: bash salt '*' osquery.xattr_where_from ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='xattr_where_from', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def xprotect_entries(attrs=None, where=None): ''' Return xprotect_entries information from osquery CLI Example: .. code-block:: bash salt '*' osquery.xprotect_entries ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='xprotect_entries', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def xprotect_reports(attrs=None, where=None): ''' Return xprotect_reports information from osquery CLI Example: .. code-block:: bash salt '*' osquery.xprotect_reports ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='xprotect_reports', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def file_(attrs=None, where=None): ''' Return file information from osquery CLI Example: .. code-block:: bash salt '*' osquery.file ''' return _osquery_cmd(table='file', attrs=attrs, where=where) def hash_(attrs=None, where=None): ''' Return hash information from osquery CLI Example: .. code-block:: bash salt '*' osquery.hash ''' return _osquery_cmd(table='hash', attrs=attrs, where=where) def osquery_extensions(attrs=None, where=None): ''' Return osquery_extensions information from osquery CLI Example: .. code-block:: bash salt '*' osquery.osquery_extensions ''' return _osquery_cmd(table='osquery_extensions', attrs=attrs, where=where) def osquery_flags(attrs=None, where=None): ''' Return osquery_flags information from osquery CLI Example: .. code-block:: bash salt '*' osquery.osquery_flags ''' return _osquery_cmd(table='osquery_flags', attrs=attrs, where=where) def osquery_info(attrs=None, where=None): ''' Return osquery_info information from osquery CLI Example: .. code-block:: bash salt '*' osquery.osquery_info ''' return _osquery_cmd(table='osquery_info', attrs=attrs, where=where) def osquery_registry(attrs=None, where=None): ''' Return osquery_registry information from osquery CLI Example: .. code-block:: bash salt '*' osquery.osquery_registry ''' return _osquery_cmd(table='osquery_registry', attrs=attrs, where=where) def time_(attrs=None): ''' Return time information from osquery CLI Example: .. code-block:: bash salt '*' osquery.time ''' return _osquery_cmd(table='time', attrs=attrs) def query(sql=None): ''' Return time information from osquery CLI Example: .. code-block:: bash salt '*' osquery.query "select * from users;" ''' return _osquery(sql)
saltstack/salt
salt/modules/osquery.py
process_memory_map
python
def process_memory_map(attrs=None, where=None): ''' Return process_memory_map information from osquery CLI Example: .. code-block:: bash salt '*' osquery.process_memory_map ''' if __grains__['os_family'] in ['RedHat', 'Debian']: return _osquery_cmd(table='process_memory_map', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat or Debian based systems.'}
Return process_memory_map information from osquery CLI Example: .. code-block:: bash salt '*' osquery.process_memory_map
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/osquery.py#L194-L206
[ "def _osquery_cmd(table, attrs=None, where=None, format='json'):\n '''\n Helper function to run osquery queries\n '''\n ret = {\n 'result': True,\n }\n\n if attrs:\n if isinstance(attrs, list):\n valid_attrs = _table_attrs(table)\n if valid_attrs:\n for a in attrs:\n if a not in valid_attrs:\n ret['result'] = False\n ret['comment'] = '{0} is not a valid attribute for table {1}'.format(a, table)\n return ret\n _attrs = ','.join(attrs)\n else:\n ret['result'] = False\n ret['comment'] = 'Invalid table {0}.'.format(table)\n return ret\n else:\n ret['comment'] = 'attrs must be specified as a list.'\n ret['result'] = False\n return ret\n else:\n _attrs = '*'\n\n sql = 'select {0} from {1}'.format(_attrs, table)\n\n if where:\n sql = '{0} where {1}'.format(sql, where)\n\n sql = '{0};'.format(sql)\n\n res = _osquery(sql)\n if res['result']:\n ret['data'] = res['data']\n else:\n ret['comment'] = res['error']\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Support for OSQuery - https://osquery.io. .. versionadded:: 2015.8.0 ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import logging # Import Salt libs import salt.utils.json import salt.utils.path import salt.utils.platform log = logging.getLogger(__name__) __func_alias__ = { 'file_': 'file', 'hash_': 'hash', 'time_': 'time', } __virtualname__ = 'osquery' def __virtual__(): if salt.utils.path.which('osqueryi'): return __virtualname__ return (False, 'The osquery execution module cannot be loaded: ' 'osqueryi binary is not in the path.') def _table_attrs(table): ''' Helper function to find valid table attributes ''' cmd = ['osqueryi'] + ['--json'] + ['pragma table_info({0})'.format(table)] res = __salt__['cmd.run_all'](cmd) if res['retcode'] == 0: attrs = [] text = salt.utils.json.loads(res['stdout']) for item in text: attrs.append(item['name']) return attrs return False def _osquery(sql, format='json'): ''' Helper function to run raw osquery queries ''' ret = { 'result': True, } cmd = ['osqueryi'] + ['--json'] + [sql] res = __salt__['cmd.run_all'](cmd) if res['stderr']: ret['result'] = False ret['error'] = res['stderr'] else: ret['data'] = salt.utils.json.loads(res['stdout']) log.debug('== %s ==', ret) return ret def _osquery_cmd(table, attrs=None, where=None, format='json'): ''' Helper function to run osquery queries ''' ret = { 'result': True, } if attrs: if isinstance(attrs, list): valid_attrs = _table_attrs(table) if valid_attrs: for a in attrs: if a not in valid_attrs: ret['result'] = False ret['comment'] = '{0} is not a valid attribute for table {1}'.format(a, table) return ret _attrs = ','.join(attrs) else: ret['result'] = False ret['comment'] = 'Invalid table {0}.'.format(table) return ret else: ret['comment'] = 'attrs must be specified as a list.' ret['result'] = False return ret else: _attrs = '*' sql = 'select {0} from {1}'.format(_attrs, table) if where: sql = '{0} where {1}'.format(sql, where) sql = '{0};'.format(sql) res = _osquery(sql) if res['result']: ret['data'] = res['data'] else: ret['comment'] = res['error'] return ret def version(): ''' Return version of osquery CLI Example: .. code-block:: bash salt '*' osquery.version ''' _false_return = {'result': False, 'comment': 'OSQuery version unavailable.'} res = _osquery_cmd(table='osquery_info', attrs=['version']) if 'result' in res and res['result']: if 'data' in res and isinstance(res['data'], list): return res['data'][0].get('version', '') or _false_return return _false_return def rpm_packages(attrs=None, where=None): ''' Return cpuid information from osquery CLI Example: .. code-block:: bash salt '*' osquery.rpm_packages ''' if __grains__['os_family'] == 'RedHat': return _osquery_cmd(table='rpm_packages', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat based systems.'} def kernel_integrity(attrs=None, where=None): ''' Return kernel_integrity information from osquery CLI Example: .. code-block:: bash salt '*' osquery.kernel_integrity ''' if __grains__['os_family'] in ['RedHat', 'Debian']: return _osquery_cmd(table='kernel_integrity', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat or Debian based systems.'} def kernel_modules(attrs=None, where=None): ''' Return kernel_modules information from osquery CLI Example: .. code-block:: bash salt '*' osquery.kernel_modules ''' if __grains__['os_family'] in ['RedHat', 'Debian']: return _osquery_cmd(table='kernel_modules', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat or Debian based systems.'} def memory_map(attrs=None, where=None): ''' Return memory_map information from osquery CLI Example: .. code-block:: bash salt '*' osquery.memory_map ''' if __grains__['os_family'] in ['RedHat', 'Debian']: return _osquery_cmd(table='memory_map', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat or Debian based systems.'} def shared_memory(attrs=None, where=None): ''' Return shared_memory information from osquery CLI Example: .. code-block:: bash salt '*' osquery.shared_memory ''' if __grains__['os_family'] in ['RedHat', 'Debian']: return _osquery_cmd(table='shared_memory', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat or Debian based systems.'} def apt_sources(attrs=None, where=None): ''' Return apt_sources information from osquery CLI Example: .. code-block:: bash salt '*' osquery.apt_sources ''' if __grains__['os_family'] == 'Debian': return _osquery_cmd(table='apt_sources', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Debian based systems.'} def deb_packages(attrs=None, where=None): ''' Return deb_packages information from osquery CLI Example: .. code-block:: bash salt '*' osquery.deb_packages ''' if __grains__['os_family'] == 'Debian': return _osquery_cmd(table='deb_packages', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Debian based systems.'} def acpi_tables(attrs=None, where=None): ''' Return acpi_tables information from osquery CLI Example: .. code-block:: bash salt '*' osquery.acpi_tables ''' return _osquery_cmd(table='acpi_tables', attrs=attrs, where=where) def arp_cache(attrs=None, where=None): ''' Return arp_cache information from osquery CLI Example: .. code-block:: bash salt '*' osquery.arp_cache ''' return _osquery_cmd(table='arp_cache', attrs=attrs, where=where) def block_devices(attrs=None, where=None): ''' Return block_devices information from osquery CLI Example: .. code-block:: bash salt '*' osquery.block_devices ''' return _osquery_cmd(table='block_devices', attrs=attrs, where=where) def cpuid(attrs=None, where=None): ''' Return cpuid information from osquery CLI Example: .. code-block:: bash salt '*' osquery.cpuid ''' return _osquery_cmd(table='cpuid', attrs=attrs, where=where) def crontab(attrs=None, where=None): ''' Return crontab information from osquery CLI Example: .. code-block:: bash salt '*' osquery.crontab ''' return _osquery_cmd(table='crontab', attrs=attrs, where=where) def etc_hosts(attrs=None, where=None): ''' Return etc_hosts information from osquery CLI Example: .. code-block:: bash salt '*' osquery.etc_hosts ''' return _osquery_cmd(table='etc_hosts', attrs=attrs, where=where) def etc_services(attrs=None, where=None): ''' Return etc_services information from osquery CLI Example: .. code-block:: bash salt '*' osquery.etc_services ''' return _osquery_cmd(table='etc_services', attrs=attrs, where=where) def file_changes(attrs=None, where=None): ''' Return file_changes information from osquery CLI Example: .. code-block:: bash salt '*' osquery.file_changes ''' return _osquery_cmd(table='file_changes', attrs=attrs, where=where) def groups(attrs=None, where=None): ''' Return groups information from osquery CLI Example: .. code-block:: bash salt '*' osquery.groups ''' return _osquery_cmd(table='groups', attrs=attrs, where=where) def hardware_events(attrs=None, where=None): ''' Return hardware_events information from osquery CLI Example: .. code-block:: bash salt '*' osquery.hardware_events ''' return _osquery_cmd(table='hardware_events', attrs=attrs, where=where) def interface_addresses(attrs=None, where=None): ''' Return interface_addresses information from osquery CLI Example: .. code-block:: bash salt '*' osquery.interface_addresses ''' return _osquery_cmd(table='interface_addresses', attrs=attrs, where=where) def interface_details(attrs=None, where=None): ''' Return interface_details information from osquery CLI Example: .. code-block:: bash salt '*' osquery.interface_details ''' return _osquery_cmd(table='interface_details', attrs=attrs, where=where) def kernel_info(attrs=None, where=None): ''' Return kernel_info information from osquery CLI Example: .. code-block:: bash salt '*' osquery.kernel_info ''' return _osquery_cmd(table='kernel_info', attrs=attrs, where=where) def last(attrs=None, where=None): ''' Return last information from osquery CLI Example: .. code-block:: bash salt '*' osquery.last ''' return _osquery_cmd(table='last', attrs=attrs, where=where) def listening_ports(attrs=None, where=None): r''' Return listening_ports information from osquery CLI Example: .. code-block:: bash salt '*' osquery.listening_ports ''' return _osquery_cmd(table='listening_ports', attrs=attrs, where=where) def logged_in_users(attrs=None, where=None): r''' Return logged_in_users information from osquery CLI Example: .. code-block:: bash salt '*' osquery.logged_in_users ''' return _osquery_cmd(table='logged_in_users', attrs=attrs, where=where) def mounts(attrs=None, where=None): r''' Return mounts information from osquery CLI Example: .. code-block:: bash salt '*' osquery.mounts ''' return _osquery_cmd(table='mounts', attrs=attrs, where=where) def os_version(attrs=None, where=None): ''' Return os_version information from osquery CLI Example: .. code-block:: bash salt '*' osquery.os_version ''' return _osquery_cmd(table='os_version', attrs=attrs, where=where) def passwd_changes(attrs=None, where=None): ''' Return passwd_changes information from osquery CLI Example: .. code-block:: bash salt '*' osquery.passwd_changes ''' return _osquery_cmd(table='passwd_changes', attrs=attrs, where=where) def pci_devices(attrs=None, where=None): ''' Return pci_devices information from osquery CLI Example: .. code-block:: bash salt '*' osquery.pci_devices ''' return _osquery_cmd(table='pci_devices', attrs=attrs, where=where) def process_envs(attrs=None, where=None): ''' Return process_envs information from osquery CLI Example: .. code-block:: bash salt '*' osquery.process_envs ''' return _osquery_cmd(table='process_envs', attrs=attrs, where=where) def process_open_files(attrs=None, where=None): ''' Return process_open_files information from osquery CLI Example: .. code-block:: bash salt '*' osquery.process_open_files ''' return _osquery_cmd(table='process_open_files', attrs=attrs, where=where) def process_open_sockets(attrs=None, where=None): ''' Return process_open_sockets information from osquery CLI Example: .. code-block:: bash salt '*' osquery.process_open_sockets ''' return _osquery_cmd(table='process_open_sockets', attrs=attrs, where=where) def processes(attrs=None, where=None): ''' Return processes information from osquery CLI Example: .. code-block:: bash salt '*' osquery.processes ''' return _osquery_cmd(table='processes', attrs=attrs, where=where) def routes(attrs=None, where=None): ''' Return routes information from osquery CLI Example: .. code-block:: bash salt '*' osquery.routes ''' return _osquery_cmd(table='routes', attrs=attrs, where=where) def shell_history(attrs=None, where=None): ''' Return shell_history information from osquery CLI Example: .. code-block:: bash salt '*' osquery.shell_history ''' return _osquery_cmd(table='shell_history', attrs=attrs, where=where) def smbios_tables(attrs=None, where=None): ''' Return smbios_tables information from osquery CLI Example: .. code-block:: bash salt '*' osquery.smbios_tables ''' return _osquery_cmd(table='smbios_tables', attrs=attrs, where=where) def suid_bin(attrs=None, where=None): ''' Return suid_bin information from osquery CLI Example: .. code-block:: bash salt '*' osquery.suid_bin ''' return _osquery_cmd(table='suid_bin', attrs=attrs, where=where) def system_controls(attrs=None, where=None): ''' Return system_controls information from osquery CLI Example: .. code-block:: bash salt '*' osquery.system_controls ''' return _osquery_cmd(table='system_controls', attrs=attrs, where=where) def usb_devices(attrs=None, where=None): ''' Return usb_devices information from osquery CLI Example: .. code-block:: bash salt '*' osquery.usb_devices ''' return _osquery_cmd(table='usb_devices', attrs=attrs, where=where) def users(attrs=None, where=None): ''' Return users information from osquery CLI Example: .. code-block:: bash salt '*' osquery.users ''' return _osquery_cmd(table='users', attrs=attrs, where=where) def alf(attrs=None, where=None): ''' Return alf information from osquery CLI Example: .. code-block:: bash salt '*' osquery.alf ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='alf', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def alf_exceptions(attrs=None, where=None): ''' Return alf_exceptions information from osquery CLI Example: .. code-block:: bash salt '*' osquery.alf_exceptions ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='alf_exceptions', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def alf_explicit_auths(attrs=None, where=None): ''' Return alf_explicit_auths information from osquery CLI Example: .. code-block:: bash salt '*' osquery.alf_explicit_auths ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='alf_explicit_auths', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def alf_services(attrs=None, where=None): ''' Return alf_services information from osquery CLI Example: .. code-block:: bash salt '*' osquery.alf_services ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='alf_services', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def apps(attrs=None, where=None): ''' Return apps information from osquery CLI Example: .. code-block:: bash salt '*' osquery.apps ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='apps', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def certificates(attrs=None, where=None): ''' Return certificates information from osquery CLI Example: .. code-block:: bash salt '*' osquery.certificates ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='certificates', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def chrome_extensions(attrs=None, where=None): ''' Return chrome_extensions information from osquery CLI Example: .. code-block:: bash salt '*' osquery.chrome_extensions ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='chrome_extensions', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def firefox_addons(attrs=None, where=None): ''' Return firefox_addons information from osquery CLI Example: .. code-block:: bash salt '*' osquery.firefox_addons ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='firefox_addons', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def homebrew_packages(attrs=None, where=None): ''' Return homebrew_packages information from osquery CLI Example: .. code-block:: bash salt '*' osquery.homebrew_packages ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='homebrew_packages', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def iokit_devicetree(attrs=None, where=None): ''' Return iokit_devicetree information from osquery CLI Example: .. code-block:: bash salt '*' osquery.iokit_devicetree ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='iokit_devicetree', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def iokit_registry(attrs=None, where=None): ''' Return iokit_registry information from osquery CLI Example: .. code-block:: bash salt '*' osquery.iokit_registry ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='iokit_registry', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def kernel_extensions(attrs=None, where=None): ''' Return kernel_extensions information from osquery CLI Example: .. code-block:: bash salt '*' osquery.kernel_extensions ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='kernel_extensions', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def keychain_items(attrs=None, where=None): ''' Return keychain_items information from osquery CLI Example: .. code-block:: bash salt '*' osquery.keychain_items ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='keychain_items', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def launchd(attrs=None, where=None): ''' Return launchd information from osquery CLI Example: .. code-block:: bash salt '*' osquery.launchd ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='launchd', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def nfs_shares(attrs=None, where=None): ''' Return nfs_shares information from osquery CLI Example: .. code-block:: bash salt '*' osquery.nfs_shares ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='nfs_shares', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def nvram(attrs=None, where=None): ''' Return nvram information from osquery CLI Example: .. code-block:: bash salt '*' osquery.nvram ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='nvram', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def preferences(attrs=None, where=None): ''' Return preferences information from osquery CLI Example: .. code-block:: bash salt '*' osquery.preferences ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='preferences', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def quarantine(attrs=None, where=None): ''' Return quarantine information from osquery CLI Example: .. code-block:: bash salt '*' osquery.quarantine ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='quarantine', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def safari_extensions(attrs=None, where=None): ''' Return safari_extensions information from osquery CLI Example: .. code-block:: bash salt '*' osquery.safari_extensions ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='safari_extensions', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def startup_items(attrs=None, where=None): ''' Return startup_items information from osquery CLI Example: .. code-block:: bash salt '*' osquery.startup_items ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='startup_items', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def xattr_where_from(attrs=None, where=None): ''' Return xattr_where_from information from osquery CLI Example: .. code-block:: bash salt '*' osquery.xattr_where_from ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='xattr_where_from', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def xprotect_entries(attrs=None, where=None): ''' Return xprotect_entries information from osquery CLI Example: .. code-block:: bash salt '*' osquery.xprotect_entries ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='xprotect_entries', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def xprotect_reports(attrs=None, where=None): ''' Return xprotect_reports information from osquery CLI Example: .. code-block:: bash salt '*' osquery.xprotect_reports ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='xprotect_reports', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def file_(attrs=None, where=None): ''' Return file information from osquery CLI Example: .. code-block:: bash salt '*' osquery.file ''' return _osquery_cmd(table='file', attrs=attrs, where=where) def hash_(attrs=None, where=None): ''' Return hash information from osquery CLI Example: .. code-block:: bash salt '*' osquery.hash ''' return _osquery_cmd(table='hash', attrs=attrs, where=where) def osquery_extensions(attrs=None, where=None): ''' Return osquery_extensions information from osquery CLI Example: .. code-block:: bash salt '*' osquery.osquery_extensions ''' return _osquery_cmd(table='osquery_extensions', attrs=attrs, where=where) def osquery_flags(attrs=None, where=None): ''' Return osquery_flags information from osquery CLI Example: .. code-block:: bash salt '*' osquery.osquery_flags ''' return _osquery_cmd(table='osquery_flags', attrs=attrs, where=where) def osquery_info(attrs=None, where=None): ''' Return osquery_info information from osquery CLI Example: .. code-block:: bash salt '*' osquery.osquery_info ''' return _osquery_cmd(table='osquery_info', attrs=attrs, where=where) def osquery_registry(attrs=None, where=None): ''' Return osquery_registry information from osquery CLI Example: .. code-block:: bash salt '*' osquery.osquery_registry ''' return _osquery_cmd(table='osquery_registry', attrs=attrs, where=where) def time_(attrs=None): ''' Return time information from osquery CLI Example: .. code-block:: bash salt '*' osquery.time ''' return _osquery_cmd(table='time', attrs=attrs) def query(sql=None): ''' Return time information from osquery CLI Example: .. code-block:: bash salt '*' osquery.query "select * from users;" ''' return _osquery(sql)
saltstack/salt
salt/modules/osquery.py
shared_memory
python
def shared_memory(attrs=None, where=None): ''' Return shared_memory information from osquery CLI Example: .. code-block:: bash salt '*' osquery.shared_memory ''' if __grains__['os_family'] in ['RedHat', 'Debian']: return _osquery_cmd(table='shared_memory', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat or Debian based systems.'}
Return shared_memory information from osquery CLI Example: .. code-block:: bash salt '*' osquery.shared_memory
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/osquery.py#L209-L221
[ "def _osquery_cmd(table, attrs=None, where=None, format='json'):\n '''\n Helper function to run osquery queries\n '''\n ret = {\n 'result': True,\n }\n\n if attrs:\n if isinstance(attrs, list):\n valid_attrs = _table_attrs(table)\n if valid_attrs:\n for a in attrs:\n if a not in valid_attrs:\n ret['result'] = False\n ret['comment'] = '{0} is not a valid attribute for table {1}'.format(a, table)\n return ret\n _attrs = ','.join(attrs)\n else:\n ret['result'] = False\n ret['comment'] = 'Invalid table {0}.'.format(table)\n return ret\n else:\n ret['comment'] = 'attrs must be specified as a list.'\n ret['result'] = False\n return ret\n else:\n _attrs = '*'\n\n sql = 'select {0} from {1}'.format(_attrs, table)\n\n if where:\n sql = '{0} where {1}'.format(sql, where)\n\n sql = '{0};'.format(sql)\n\n res = _osquery(sql)\n if res['result']:\n ret['data'] = res['data']\n else:\n ret['comment'] = res['error']\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Support for OSQuery - https://osquery.io. .. versionadded:: 2015.8.0 ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import logging # Import Salt libs import salt.utils.json import salt.utils.path import salt.utils.platform log = logging.getLogger(__name__) __func_alias__ = { 'file_': 'file', 'hash_': 'hash', 'time_': 'time', } __virtualname__ = 'osquery' def __virtual__(): if salt.utils.path.which('osqueryi'): return __virtualname__ return (False, 'The osquery execution module cannot be loaded: ' 'osqueryi binary is not in the path.') def _table_attrs(table): ''' Helper function to find valid table attributes ''' cmd = ['osqueryi'] + ['--json'] + ['pragma table_info({0})'.format(table)] res = __salt__['cmd.run_all'](cmd) if res['retcode'] == 0: attrs = [] text = salt.utils.json.loads(res['stdout']) for item in text: attrs.append(item['name']) return attrs return False def _osquery(sql, format='json'): ''' Helper function to run raw osquery queries ''' ret = { 'result': True, } cmd = ['osqueryi'] + ['--json'] + [sql] res = __salt__['cmd.run_all'](cmd) if res['stderr']: ret['result'] = False ret['error'] = res['stderr'] else: ret['data'] = salt.utils.json.loads(res['stdout']) log.debug('== %s ==', ret) return ret def _osquery_cmd(table, attrs=None, where=None, format='json'): ''' Helper function to run osquery queries ''' ret = { 'result': True, } if attrs: if isinstance(attrs, list): valid_attrs = _table_attrs(table) if valid_attrs: for a in attrs: if a not in valid_attrs: ret['result'] = False ret['comment'] = '{0} is not a valid attribute for table {1}'.format(a, table) return ret _attrs = ','.join(attrs) else: ret['result'] = False ret['comment'] = 'Invalid table {0}.'.format(table) return ret else: ret['comment'] = 'attrs must be specified as a list.' ret['result'] = False return ret else: _attrs = '*' sql = 'select {0} from {1}'.format(_attrs, table) if where: sql = '{0} where {1}'.format(sql, where) sql = '{0};'.format(sql) res = _osquery(sql) if res['result']: ret['data'] = res['data'] else: ret['comment'] = res['error'] return ret def version(): ''' Return version of osquery CLI Example: .. code-block:: bash salt '*' osquery.version ''' _false_return = {'result': False, 'comment': 'OSQuery version unavailable.'} res = _osquery_cmd(table='osquery_info', attrs=['version']) if 'result' in res and res['result']: if 'data' in res and isinstance(res['data'], list): return res['data'][0].get('version', '') or _false_return return _false_return def rpm_packages(attrs=None, where=None): ''' Return cpuid information from osquery CLI Example: .. code-block:: bash salt '*' osquery.rpm_packages ''' if __grains__['os_family'] == 'RedHat': return _osquery_cmd(table='rpm_packages', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat based systems.'} def kernel_integrity(attrs=None, where=None): ''' Return kernel_integrity information from osquery CLI Example: .. code-block:: bash salt '*' osquery.kernel_integrity ''' if __grains__['os_family'] in ['RedHat', 'Debian']: return _osquery_cmd(table='kernel_integrity', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat or Debian based systems.'} def kernel_modules(attrs=None, where=None): ''' Return kernel_modules information from osquery CLI Example: .. code-block:: bash salt '*' osquery.kernel_modules ''' if __grains__['os_family'] in ['RedHat', 'Debian']: return _osquery_cmd(table='kernel_modules', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat or Debian based systems.'} def memory_map(attrs=None, where=None): ''' Return memory_map information from osquery CLI Example: .. code-block:: bash salt '*' osquery.memory_map ''' if __grains__['os_family'] in ['RedHat', 'Debian']: return _osquery_cmd(table='memory_map', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat or Debian based systems.'} def process_memory_map(attrs=None, where=None): ''' Return process_memory_map information from osquery CLI Example: .. code-block:: bash salt '*' osquery.process_memory_map ''' if __grains__['os_family'] in ['RedHat', 'Debian']: return _osquery_cmd(table='process_memory_map', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat or Debian based systems.'} def apt_sources(attrs=None, where=None): ''' Return apt_sources information from osquery CLI Example: .. code-block:: bash salt '*' osquery.apt_sources ''' if __grains__['os_family'] == 'Debian': return _osquery_cmd(table='apt_sources', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Debian based systems.'} def deb_packages(attrs=None, where=None): ''' Return deb_packages information from osquery CLI Example: .. code-block:: bash salt '*' osquery.deb_packages ''' if __grains__['os_family'] == 'Debian': return _osquery_cmd(table='deb_packages', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Debian based systems.'} def acpi_tables(attrs=None, where=None): ''' Return acpi_tables information from osquery CLI Example: .. code-block:: bash salt '*' osquery.acpi_tables ''' return _osquery_cmd(table='acpi_tables', attrs=attrs, where=where) def arp_cache(attrs=None, where=None): ''' Return arp_cache information from osquery CLI Example: .. code-block:: bash salt '*' osquery.arp_cache ''' return _osquery_cmd(table='arp_cache', attrs=attrs, where=where) def block_devices(attrs=None, where=None): ''' Return block_devices information from osquery CLI Example: .. code-block:: bash salt '*' osquery.block_devices ''' return _osquery_cmd(table='block_devices', attrs=attrs, where=where) def cpuid(attrs=None, where=None): ''' Return cpuid information from osquery CLI Example: .. code-block:: bash salt '*' osquery.cpuid ''' return _osquery_cmd(table='cpuid', attrs=attrs, where=where) def crontab(attrs=None, where=None): ''' Return crontab information from osquery CLI Example: .. code-block:: bash salt '*' osquery.crontab ''' return _osquery_cmd(table='crontab', attrs=attrs, where=where) def etc_hosts(attrs=None, where=None): ''' Return etc_hosts information from osquery CLI Example: .. code-block:: bash salt '*' osquery.etc_hosts ''' return _osquery_cmd(table='etc_hosts', attrs=attrs, where=where) def etc_services(attrs=None, where=None): ''' Return etc_services information from osquery CLI Example: .. code-block:: bash salt '*' osquery.etc_services ''' return _osquery_cmd(table='etc_services', attrs=attrs, where=where) def file_changes(attrs=None, where=None): ''' Return file_changes information from osquery CLI Example: .. code-block:: bash salt '*' osquery.file_changes ''' return _osquery_cmd(table='file_changes', attrs=attrs, where=where) def groups(attrs=None, where=None): ''' Return groups information from osquery CLI Example: .. code-block:: bash salt '*' osquery.groups ''' return _osquery_cmd(table='groups', attrs=attrs, where=where) def hardware_events(attrs=None, where=None): ''' Return hardware_events information from osquery CLI Example: .. code-block:: bash salt '*' osquery.hardware_events ''' return _osquery_cmd(table='hardware_events', attrs=attrs, where=where) def interface_addresses(attrs=None, where=None): ''' Return interface_addresses information from osquery CLI Example: .. code-block:: bash salt '*' osquery.interface_addresses ''' return _osquery_cmd(table='interface_addresses', attrs=attrs, where=where) def interface_details(attrs=None, where=None): ''' Return interface_details information from osquery CLI Example: .. code-block:: bash salt '*' osquery.interface_details ''' return _osquery_cmd(table='interface_details', attrs=attrs, where=where) def kernel_info(attrs=None, where=None): ''' Return kernel_info information from osquery CLI Example: .. code-block:: bash salt '*' osquery.kernel_info ''' return _osquery_cmd(table='kernel_info', attrs=attrs, where=where) def last(attrs=None, where=None): ''' Return last information from osquery CLI Example: .. code-block:: bash salt '*' osquery.last ''' return _osquery_cmd(table='last', attrs=attrs, where=where) def listening_ports(attrs=None, where=None): r''' Return listening_ports information from osquery CLI Example: .. code-block:: bash salt '*' osquery.listening_ports ''' return _osquery_cmd(table='listening_ports', attrs=attrs, where=where) def logged_in_users(attrs=None, where=None): r''' Return logged_in_users information from osquery CLI Example: .. code-block:: bash salt '*' osquery.logged_in_users ''' return _osquery_cmd(table='logged_in_users', attrs=attrs, where=where) def mounts(attrs=None, where=None): r''' Return mounts information from osquery CLI Example: .. code-block:: bash salt '*' osquery.mounts ''' return _osquery_cmd(table='mounts', attrs=attrs, where=where) def os_version(attrs=None, where=None): ''' Return os_version information from osquery CLI Example: .. code-block:: bash salt '*' osquery.os_version ''' return _osquery_cmd(table='os_version', attrs=attrs, where=where) def passwd_changes(attrs=None, where=None): ''' Return passwd_changes information from osquery CLI Example: .. code-block:: bash salt '*' osquery.passwd_changes ''' return _osquery_cmd(table='passwd_changes', attrs=attrs, where=where) def pci_devices(attrs=None, where=None): ''' Return pci_devices information from osquery CLI Example: .. code-block:: bash salt '*' osquery.pci_devices ''' return _osquery_cmd(table='pci_devices', attrs=attrs, where=where) def process_envs(attrs=None, where=None): ''' Return process_envs information from osquery CLI Example: .. code-block:: bash salt '*' osquery.process_envs ''' return _osquery_cmd(table='process_envs', attrs=attrs, where=where) def process_open_files(attrs=None, where=None): ''' Return process_open_files information from osquery CLI Example: .. code-block:: bash salt '*' osquery.process_open_files ''' return _osquery_cmd(table='process_open_files', attrs=attrs, where=where) def process_open_sockets(attrs=None, where=None): ''' Return process_open_sockets information from osquery CLI Example: .. code-block:: bash salt '*' osquery.process_open_sockets ''' return _osquery_cmd(table='process_open_sockets', attrs=attrs, where=where) def processes(attrs=None, where=None): ''' Return processes information from osquery CLI Example: .. code-block:: bash salt '*' osquery.processes ''' return _osquery_cmd(table='processes', attrs=attrs, where=where) def routes(attrs=None, where=None): ''' Return routes information from osquery CLI Example: .. code-block:: bash salt '*' osquery.routes ''' return _osquery_cmd(table='routes', attrs=attrs, where=where) def shell_history(attrs=None, where=None): ''' Return shell_history information from osquery CLI Example: .. code-block:: bash salt '*' osquery.shell_history ''' return _osquery_cmd(table='shell_history', attrs=attrs, where=where) def smbios_tables(attrs=None, where=None): ''' Return smbios_tables information from osquery CLI Example: .. code-block:: bash salt '*' osquery.smbios_tables ''' return _osquery_cmd(table='smbios_tables', attrs=attrs, where=where) def suid_bin(attrs=None, where=None): ''' Return suid_bin information from osquery CLI Example: .. code-block:: bash salt '*' osquery.suid_bin ''' return _osquery_cmd(table='suid_bin', attrs=attrs, where=where) def system_controls(attrs=None, where=None): ''' Return system_controls information from osquery CLI Example: .. code-block:: bash salt '*' osquery.system_controls ''' return _osquery_cmd(table='system_controls', attrs=attrs, where=where) def usb_devices(attrs=None, where=None): ''' Return usb_devices information from osquery CLI Example: .. code-block:: bash salt '*' osquery.usb_devices ''' return _osquery_cmd(table='usb_devices', attrs=attrs, where=where) def users(attrs=None, where=None): ''' Return users information from osquery CLI Example: .. code-block:: bash salt '*' osquery.users ''' return _osquery_cmd(table='users', attrs=attrs, where=where) def alf(attrs=None, where=None): ''' Return alf information from osquery CLI Example: .. code-block:: bash salt '*' osquery.alf ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='alf', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def alf_exceptions(attrs=None, where=None): ''' Return alf_exceptions information from osquery CLI Example: .. code-block:: bash salt '*' osquery.alf_exceptions ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='alf_exceptions', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def alf_explicit_auths(attrs=None, where=None): ''' Return alf_explicit_auths information from osquery CLI Example: .. code-block:: bash salt '*' osquery.alf_explicit_auths ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='alf_explicit_auths', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def alf_services(attrs=None, where=None): ''' Return alf_services information from osquery CLI Example: .. code-block:: bash salt '*' osquery.alf_services ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='alf_services', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def apps(attrs=None, where=None): ''' Return apps information from osquery CLI Example: .. code-block:: bash salt '*' osquery.apps ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='apps', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def certificates(attrs=None, where=None): ''' Return certificates information from osquery CLI Example: .. code-block:: bash salt '*' osquery.certificates ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='certificates', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def chrome_extensions(attrs=None, where=None): ''' Return chrome_extensions information from osquery CLI Example: .. code-block:: bash salt '*' osquery.chrome_extensions ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='chrome_extensions', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def firefox_addons(attrs=None, where=None): ''' Return firefox_addons information from osquery CLI Example: .. code-block:: bash salt '*' osquery.firefox_addons ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='firefox_addons', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def homebrew_packages(attrs=None, where=None): ''' Return homebrew_packages information from osquery CLI Example: .. code-block:: bash salt '*' osquery.homebrew_packages ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='homebrew_packages', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def iokit_devicetree(attrs=None, where=None): ''' Return iokit_devicetree information from osquery CLI Example: .. code-block:: bash salt '*' osquery.iokit_devicetree ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='iokit_devicetree', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def iokit_registry(attrs=None, where=None): ''' Return iokit_registry information from osquery CLI Example: .. code-block:: bash salt '*' osquery.iokit_registry ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='iokit_registry', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def kernel_extensions(attrs=None, where=None): ''' Return kernel_extensions information from osquery CLI Example: .. code-block:: bash salt '*' osquery.kernel_extensions ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='kernel_extensions', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def keychain_items(attrs=None, where=None): ''' Return keychain_items information from osquery CLI Example: .. code-block:: bash salt '*' osquery.keychain_items ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='keychain_items', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def launchd(attrs=None, where=None): ''' Return launchd information from osquery CLI Example: .. code-block:: bash salt '*' osquery.launchd ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='launchd', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def nfs_shares(attrs=None, where=None): ''' Return nfs_shares information from osquery CLI Example: .. code-block:: bash salt '*' osquery.nfs_shares ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='nfs_shares', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def nvram(attrs=None, where=None): ''' Return nvram information from osquery CLI Example: .. code-block:: bash salt '*' osquery.nvram ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='nvram', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def preferences(attrs=None, where=None): ''' Return preferences information from osquery CLI Example: .. code-block:: bash salt '*' osquery.preferences ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='preferences', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def quarantine(attrs=None, where=None): ''' Return quarantine information from osquery CLI Example: .. code-block:: bash salt '*' osquery.quarantine ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='quarantine', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def safari_extensions(attrs=None, where=None): ''' Return safari_extensions information from osquery CLI Example: .. code-block:: bash salt '*' osquery.safari_extensions ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='safari_extensions', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def startup_items(attrs=None, where=None): ''' Return startup_items information from osquery CLI Example: .. code-block:: bash salt '*' osquery.startup_items ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='startup_items', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def xattr_where_from(attrs=None, where=None): ''' Return xattr_where_from information from osquery CLI Example: .. code-block:: bash salt '*' osquery.xattr_where_from ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='xattr_where_from', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def xprotect_entries(attrs=None, where=None): ''' Return xprotect_entries information from osquery CLI Example: .. code-block:: bash salt '*' osquery.xprotect_entries ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='xprotect_entries', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def xprotect_reports(attrs=None, where=None): ''' Return xprotect_reports information from osquery CLI Example: .. code-block:: bash salt '*' osquery.xprotect_reports ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='xprotect_reports', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def file_(attrs=None, where=None): ''' Return file information from osquery CLI Example: .. code-block:: bash salt '*' osquery.file ''' return _osquery_cmd(table='file', attrs=attrs, where=where) def hash_(attrs=None, where=None): ''' Return hash information from osquery CLI Example: .. code-block:: bash salt '*' osquery.hash ''' return _osquery_cmd(table='hash', attrs=attrs, where=where) def osquery_extensions(attrs=None, where=None): ''' Return osquery_extensions information from osquery CLI Example: .. code-block:: bash salt '*' osquery.osquery_extensions ''' return _osquery_cmd(table='osquery_extensions', attrs=attrs, where=where) def osquery_flags(attrs=None, where=None): ''' Return osquery_flags information from osquery CLI Example: .. code-block:: bash salt '*' osquery.osquery_flags ''' return _osquery_cmd(table='osquery_flags', attrs=attrs, where=where) def osquery_info(attrs=None, where=None): ''' Return osquery_info information from osquery CLI Example: .. code-block:: bash salt '*' osquery.osquery_info ''' return _osquery_cmd(table='osquery_info', attrs=attrs, where=where) def osquery_registry(attrs=None, where=None): ''' Return osquery_registry information from osquery CLI Example: .. code-block:: bash salt '*' osquery.osquery_registry ''' return _osquery_cmd(table='osquery_registry', attrs=attrs, where=where) def time_(attrs=None): ''' Return time information from osquery CLI Example: .. code-block:: bash salt '*' osquery.time ''' return _osquery_cmd(table='time', attrs=attrs) def query(sql=None): ''' Return time information from osquery CLI Example: .. code-block:: bash salt '*' osquery.query "select * from users;" ''' return _osquery(sql)
saltstack/salt
salt/modules/osquery.py
apt_sources
python
def apt_sources(attrs=None, where=None): ''' Return apt_sources information from osquery CLI Example: .. code-block:: bash salt '*' osquery.apt_sources ''' if __grains__['os_family'] == 'Debian': return _osquery_cmd(table='apt_sources', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Debian based systems.'}
Return apt_sources information from osquery CLI Example: .. code-block:: bash salt '*' osquery.apt_sources
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/osquery.py#L224-L236
[ "def _osquery_cmd(table, attrs=None, where=None, format='json'):\n '''\n Helper function to run osquery queries\n '''\n ret = {\n 'result': True,\n }\n\n if attrs:\n if isinstance(attrs, list):\n valid_attrs = _table_attrs(table)\n if valid_attrs:\n for a in attrs:\n if a not in valid_attrs:\n ret['result'] = False\n ret['comment'] = '{0} is not a valid attribute for table {1}'.format(a, table)\n return ret\n _attrs = ','.join(attrs)\n else:\n ret['result'] = False\n ret['comment'] = 'Invalid table {0}.'.format(table)\n return ret\n else:\n ret['comment'] = 'attrs must be specified as a list.'\n ret['result'] = False\n return ret\n else:\n _attrs = '*'\n\n sql = 'select {0} from {1}'.format(_attrs, table)\n\n if where:\n sql = '{0} where {1}'.format(sql, where)\n\n sql = '{0};'.format(sql)\n\n res = _osquery(sql)\n if res['result']:\n ret['data'] = res['data']\n else:\n ret['comment'] = res['error']\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Support for OSQuery - https://osquery.io. .. versionadded:: 2015.8.0 ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import logging # Import Salt libs import salt.utils.json import salt.utils.path import salt.utils.platform log = logging.getLogger(__name__) __func_alias__ = { 'file_': 'file', 'hash_': 'hash', 'time_': 'time', } __virtualname__ = 'osquery' def __virtual__(): if salt.utils.path.which('osqueryi'): return __virtualname__ return (False, 'The osquery execution module cannot be loaded: ' 'osqueryi binary is not in the path.') def _table_attrs(table): ''' Helper function to find valid table attributes ''' cmd = ['osqueryi'] + ['--json'] + ['pragma table_info({0})'.format(table)] res = __salt__['cmd.run_all'](cmd) if res['retcode'] == 0: attrs = [] text = salt.utils.json.loads(res['stdout']) for item in text: attrs.append(item['name']) return attrs return False def _osquery(sql, format='json'): ''' Helper function to run raw osquery queries ''' ret = { 'result': True, } cmd = ['osqueryi'] + ['--json'] + [sql] res = __salt__['cmd.run_all'](cmd) if res['stderr']: ret['result'] = False ret['error'] = res['stderr'] else: ret['data'] = salt.utils.json.loads(res['stdout']) log.debug('== %s ==', ret) return ret def _osquery_cmd(table, attrs=None, where=None, format='json'): ''' Helper function to run osquery queries ''' ret = { 'result': True, } if attrs: if isinstance(attrs, list): valid_attrs = _table_attrs(table) if valid_attrs: for a in attrs: if a not in valid_attrs: ret['result'] = False ret['comment'] = '{0} is not a valid attribute for table {1}'.format(a, table) return ret _attrs = ','.join(attrs) else: ret['result'] = False ret['comment'] = 'Invalid table {0}.'.format(table) return ret else: ret['comment'] = 'attrs must be specified as a list.' ret['result'] = False return ret else: _attrs = '*' sql = 'select {0} from {1}'.format(_attrs, table) if where: sql = '{0} where {1}'.format(sql, where) sql = '{0};'.format(sql) res = _osquery(sql) if res['result']: ret['data'] = res['data'] else: ret['comment'] = res['error'] return ret def version(): ''' Return version of osquery CLI Example: .. code-block:: bash salt '*' osquery.version ''' _false_return = {'result': False, 'comment': 'OSQuery version unavailable.'} res = _osquery_cmd(table='osquery_info', attrs=['version']) if 'result' in res and res['result']: if 'data' in res and isinstance(res['data'], list): return res['data'][0].get('version', '') or _false_return return _false_return def rpm_packages(attrs=None, where=None): ''' Return cpuid information from osquery CLI Example: .. code-block:: bash salt '*' osquery.rpm_packages ''' if __grains__['os_family'] == 'RedHat': return _osquery_cmd(table='rpm_packages', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat based systems.'} def kernel_integrity(attrs=None, where=None): ''' Return kernel_integrity information from osquery CLI Example: .. code-block:: bash salt '*' osquery.kernel_integrity ''' if __grains__['os_family'] in ['RedHat', 'Debian']: return _osquery_cmd(table='kernel_integrity', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat or Debian based systems.'} def kernel_modules(attrs=None, where=None): ''' Return kernel_modules information from osquery CLI Example: .. code-block:: bash salt '*' osquery.kernel_modules ''' if __grains__['os_family'] in ['RedHat', 'Debian']: return _osquery_cmd(table='kernel_modules', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat or Debian based systems.'} def memory_map(attrs=None, where=None): ''' Return memory_map information from osquery CLI Example: .. code-block:: bash salt '*' osquery.memory_map ''' if __grains__['os_family'] in ['RedHat', 'Debian']: return _osquery_cmd(table='memory_map', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat or Debian based systems.'} def process_memory_map(attrs=None, where=None): ''' Return process_memory_map information from osquery CLI Example: .. code-block:: bash salt '*' osquery.process_memory_map ''' if __grains__['os_family'] in ['RedHat', 'Debian']: return _osquery_cmd(table='process_memory_map', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat or Debian based systems.'} def shared_memory(attrs=None, where=None): ''' Return shared_memory information from osquery CLI Example: .. code-block:: bash salt '*' osquery.shared_memory ''' if __grains__['os_family'] in ['RedHat', 'Debian']: return _osquery_cmd(table='shared_memory', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat or Debian based systems.'} def deb_packages(attrs=None, where=None): ''' Return deb_packages information from osquery CLI Example: .. code-block:: bash salt '*' osquery.deb_packages ''' if __grains__['os_family'] == 'Debian': return _osquery_cmd(table='deb_packages', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Debian based systems.'} def acpi_tables(attrs=None, where=None): ''' Return acpi_tables information from osquery CLI Example: .. code-block:: bash salt '*' osquery.acpi_tables ''' return _osquery_cmd(table='acpi_tables', attrs=attrs, where=where) def arp_cache(attrs=None, where=None): ''' Return arp_cache information from osquery CLI Example: .. code-block:: bash salt '*' osquery.arp_cache ''' return _osquery_cmd(table='arp_cache', attrs=attrs, where=where) def block_devices(attrs=None, where=None): ''' Return block_devices information from osquery CLI Example: .. code-block:: bash salt '*' osquery.block_devices ''' return _osquery_cmd(table='block_devices', attrs=attrs, where=where) def cpuid(attrs=None, where=None): ''' Return cpuid information from osquery CLI Example: .. code-block:: bash salt '*' osquery.cpuid ''' return _osquery_cmd(table='cpuid', attrs=attrs, where=where) def crontab(attrs=None, where=None): ''' Return crontab information from osquery CLI Example: .. code-block:: bash salt '*' osquery.crontab ''' return _osquery_cmd(table='crontab', attrs=attrs, where=where) def etc_hosts(attrs=None, where=None): ''' Return etc_hosts information from osquery CLI Example: .. code-block:: bash salt '*' osquery.etc_hosts ''' return _osquery_cmd(table='etc_hosts', attrs=attrs, where=where) def etc_services(attrs=None, where=None): ''' Return etc_services information from osquery CLI Example: .. code-block:: bash salt '*' osquery.etc_services ''' return _osquery_cmd(table='etc_services', attrs=attrs, where=where) def file_changes(attrs=None, where=None): ''' Return file_changes information from osquery CLI Example: .. code-block:: bash salt '*' osquery.file_changes ''' return _osquery_cmd(table='file_changes', attrs=attrs, where=where) def groups(attrs=None, where=None): ''' Return groups information from osquery CLI Example: .. code-block:: bash salt '*' osquery.groups ''' return _osquery_cmd(table='groups', attrs=attrs, where=where) def hardware_events(attrs=None, where=None): ''' Return hardware_events information from osquery CLI Example: .. code-block:: bash salt '*' osquery.hardware_events ''' return _osquery_cmd(table='hardware_events', attrs=attrs, where=where) def interface_addresses(attrs=None, where=None): ''' Return interface_addresses information from osquery CLI Example: .. code-block:: bash salt '*' osquery.interface_addresses ''' return _osquery_cmd(table='interface_addresses', attrs=attrs, where=where) def interface_details(attrs=None, where=None): ''' Return interface_details information from osquery CLI Example: .. code-block:: bash salt '*' osquery.interface_details ''' return _osquery_cmd(table='interface_details', attrs=attrs, where=where) def kernel_info(attrs=None, where=None): ''' Return kernel_info information from osquery CLI Example: .. code-block:: bash salt '*' osquery.kernel_info ''' return _osquery_cmd(table='kernel_info', attrs=attrs, where=where) def last(attrs=None, where=None): ''' Return last information from osquery CLI Example: .. code-block:: bash salt '*' osquery.last ''' return _osquery_cmd(table='last', attrs=attrs, where=where) def listening_ports(attrs=None, where=None): r''' Return listening_ports information from osquery CLI Example: .. code-block:: bash salt '*' osquery.listening_ports ''' return _osquery_cmd(table='listening_ports', attrs=attrs, where=where) def logged_in_users(attrs=None, where=None): r''' Return logged_in_users information from osquery CLI Example: .. code-block:: bash salt '*' osquery.logged_in_users ''' return _osquery_cmd(table='logged_in_users', attrs=attrs, where=where) def mounts(attrs=None, where=None): r''' Return mounts information from osquery CLI Example: .. code-block:: bash salt '*' osquery.mounts ''' return _osquery_cmd(table='mounts', attrs=attrs, where=where) def os_version(attrs=None, where=None): ''' Return os_version information from osquery CLI Example: .. code-block:: bash salt '*' osquery.os_version ''' return _osquery_cmd(table='os_version', attrs=attrs, where=where) def passwd_changes(attrs=None, where=None): ''' Return passwd_changes information from osquery CLI Example: .. code-block:: bash salt '*' osquery.passwd_changes ''' return _osquery_cmd(table='passwd_changes', attrs=attrs, where=where) def pci_devices(attrs=None, where=None): ''' Return pci_devices information from osquery CLI Example: .. code-block:: bash salt '*' osquery.pci_devices ''' return _osquery_cmd(table='pci_devices', attrs=attrs, where=where) def process_envs(attrs=None, where=None): ''' Return process_envs information from osquery CLI Example: .. code-block:: bash salt '*' osquery.process_envs ''' return _osquery_cmd(table='process_envs', attrs=attrs, where=where) def process_open_files(attrs=None, where=None): ''' Return process_open_files information from osquery CLI Example: .. code-block:: bash salt '*' osquery.process_open_files ''' return _osquery_cmd(table='process_open_files', attrs=attrs, where=where) def process_open_sockets(attrs=None, where=None): ''' Return process_open_sockets information from osquery CLI Example: .. code-block:: bash salt '*' osquery.process_open_sockets ''' return _osquery_cmd(table='process_open_sockets', attrs=attrs, where=where) def processes(attrs=None, where=None): ''' Return processes information from osquery CLI Example: .. code-block:: bash salt '*' osquery.processes ''' return _osquery_cmd(table='processes', attrs=attrs, where=where) def routes(attrs=None, where=None): ''' Return routes information from osquery CLI Example: .. code-block:: bash salt '*' osquery.routes ''' return _osquery_cmd(table='routes', attrs=attrs, where=where) def shell_history(attrs=None, where=None): ''' Return shell_history information from osquery CLI Example: .. code-block:: bash salt '*' osquery.shell_history ''' return _osquery_cmd(table='shell_history', attrs=attrs, where=where) def smbios_tables(attrs=None, where=None): ''' Return smbios_tables information from osquery CLI Example: .. code-block:: bash salt '*' osquery.smbios_tables ''' return _osquery_cmd(table='smbios_tables', attrs=attrs, where=where) def suid_bin(attrs=None, where=None): ''' Return suid_bin information from osquery CLI Example: .. code-block:: bash salt '*' osquery.suid_bin ''' return _osquery_cmd(table='suid_bin', attrs=attrs, where=where) def system_controls(attrs=None, where=None): ''' Return system_controls information from osquery CLI Example: .. code-block:: bash salt '*' osquery.system_controls ''' return _osquery_cmd(table='system_controls', attrs=attrs, where=where) def usb_devices(attrs=None, where=None): ''' Return usb_devices information from osquery CLI Example: .. code-block:: bash salt '*' osquery.usb_devices ''' return _osquery_cmd(table='usb_devices', attrs=attrs, where=where) def users(attrs=None, where=None): ''' Return users information from osquery CLI Example: .. code-block:: bash salt '*' osquery.users ''' return _osquery_cmd(table='users', attrs=attrs, where=where) def alf(attrs=None, where=None): ''' Return alf information from osquery CLI Example: .. code-block:: bash salt '*' osquery.alf ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='alf', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def alf_exceptions(attrs=None, where=None): ''' Return alf_exceptions information from osquery CLI Example: .. code-block:: bash salt '*' osquery.alf_exceptions ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='alf_exceptions', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def alf_explicit_auths(attrs=None, where=None): ''' Return alf_explicit_auths information from osquery CLI Example: .. code-block:: bash salt '*' osquery.alf_explicit_auths ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='alf_explicit_auths', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def alf_services(attrs=None, where=None): ''' Return alf_services information from osquery CLI Example: .. code-block:: bash salt '*' osquery.alf_services ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='alf_services', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def apps(attrs=None, where=None): ''' Return apps information from osquery CLI Example: .. code-block:: bash salt '*' osquery.apps ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='apps', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def certificates(attrs=None, where=None): ''' Return certificates information from osquery CLI Example: .. code-block:: bash salt '*' osquery.certificates ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='certificates', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def chrome_extensions(attrs=None, where=None): ''' Return chrome_extensions information from osquery CLI Example: .. code-block:: bash salt '*' osquery.chrome_extensions ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='chrome_extensions', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def firefox_addons(attrs=None, where=None): ''' Return firefox_addons information from osquery CLI Example: .. code-block:: bash salt '*' osquery.firefox_addons ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='firefox_addons', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def homebrew_packages(attrs=None, where=None): ''' Return homebrew_packages information from osquery CLI Example: .. code-block:: bash salt '*' osquery.homebrew_packages ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='homebrew_packages', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def iokit_devicetree(attrs=None, where=None): ''' Return iokit_devicetree information from osquery CLI Example: .. code-block:: bash salt '*' osquery.iokit_devicetree ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='iokit_devicetree', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def iokit_registry(attrs=None, where=None): ''' Return iokit_registry information from osquery CLI Example: .. code-block:: bash salt '*' osquery.iokit_registry ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='iokit_registry', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def kernel_extensions(attrs=None, where=None): ''' Return kernel_extensions information from osquery CLI Example: .. code-block:: bash salt '*' osquery.kernel_extensions ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='kernel_extensions', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def keychain_items(attrs=None, where=None): ''' Return keychain_items information from osquery CLI Example: .. code-block:: bash salt '*' osquery.keychain_items ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='keychain_items', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def launchd(attrs=None, where=None): ''' Return launchd information from osquery CLI Example: .. code-block:: bash salt '*' osquery.launchd ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='launchd', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def nfs_shares(attrs=None, where=None): ''' Return nfs_shares information from osquery CLI Example: .. code-block:: bash salt '*' osquery.nfs_shares ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='nfs_shares', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def nvram(attrs=None, where=None): ''' Return nvram information from osquery CLI Example: .. code-block:: bash salt '*' osquery.nvram ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='nvram', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def preferences(attrs=None, where=None): ''' Return preferences information from osquery CLI Example: .. code-block:: bash salt '*' osquery.preferences ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='preferences', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def quarantine(attrs=None, where=None): ''' Return quarantine information from osquery CLI Example: .. code-block:: bash salt '*' osquery.quarantine ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='quarantine', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def safari_extensions(attrs=None, where=None): ''' Return safari_extensions information from osquery CLI Example: .. code-block:: bash salt '*' osquery.safari_extensions ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='safari_extensions', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def startup_items(attrs=None, where=None): ''' Return startup_items information from osquery CLI Example: .. code-block:: bash salt '*' osquery.startup_items ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='startup_items', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def xattr_where_from(attrs=None, where=None): ''' Return xattr_where_from information from osquery CLI Example: .. code-block:: bash salt '*' osquery.xattr_where_from ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='xattr_where_from', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def xprotect_entries(attrs=None, where=None): ''' Return xprotect_entries information from osquery CLI Example: .. code-block:: bash salt '*' osquery.xprotect_entries ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='xprotect_entries', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def xprotect_reports(attrs=None, where=None): ''' Return xprotect_reports information from osquery CLI Example: .. code-block:: bash salt '*' osquery.xprotect_reports ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='xprotect_reports', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def file_(attrs=None, where=None): ''' Return file information from osquery CLI Example: .. code-block:: bash salt '*' osquery.file ''' return _osquery_cmd(table='file', attrs=attrs, where=where) def hash_(attrs=None, where=None): ''' Return hash information from osquery CLI Example: .. code-block:: bash salt '*' osquery.hash ''' return _osquery_cmd(table='hash', attrs=attrs, where=where) def osquery_extensions(attrs=None, where=None): ''' Return osquery_extensions information from osquery CLI Example: .. code-block:: bash salt '*' osquery.osquery_extensions ''' return _osquery_cmd(table='osquery_extensions', attrs=attrs, where=where) def osquery_flags(attrs=None, where=None): ''' Return osquery_flags information from osquery CLI Example: .. code-block:: bash salt '*' osquery.osquery_flags ''' return _osquery_cmd(table='osquery_flags', attrs=attrs, where=where) def osquery_info(attrs=None, where=None): ''' Return osquery_info information from osquery CLI Example: .. code-block:: bash salt '*' osquery.osquery_info ''' return _osquery_cmd(table='osquery_info', attrs=attrs, where=where) def osquery_registry(attrs=None, where=None): ''' Return osquery_registry information from osquery CLI Example: .. code-block:: bash salt '*' osquery.osquery_registry ''' return _osquery_cmd(table='osquery_registry', attrs=attrs, where=where) def time_(attrs=None): ''' Return time information from osquery CLI Example: .. code-block:: bash salt '*' osquery.time ''' return _osquery_cmd(table='time', attrs=attrs) def query(sql=None): ''' Return time information from osquery CLI Example: .. code-block:: bash salt '*' osquery.query "select * from users;" ''' return _osquery(sql)
saltstack/salt
salt/modules/osquery.py
deb_packages
python
def deb_packages(attrs=None, where=None): ''' Return deb_packages information from osquery CLI Example: .. code-block:: bash salt '*' osquery.deb_packages ''' if __grains__['os_family'] == 'Debian': return _osquery_cmd(table='deb_packages', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Debian based systems.'}
Return deb_packages information from osquery CLI Example: .. code-block:: bash salt '*' osquery.deb_packages
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/osquery.py#L239-L251
[ "def _osquery_cmd(table, attrs=None, where=None, format='json'):\n '''\n Helper function to run osquery queries\n '''\n ret = {\n 'result': True,\n }\n\n if attrs:\n if isinstance(attrs, list):\n valid_attrs = _table_attrs(table)\n if valid_attrs:\n for a in attrs:\n if a not in valid_attrs:\n ret['result'] = False\n ret['comment'] = '{0} is not a valid attribute for table {1}'.format(a, table)\n return ret\n _attrs = ','.join(attrs)\n else:\n ret['result'] = False\n ret['comment'] = 'Invalid table {0}.'.format(table)\n return ret\n else:\n ret['comment'] = 'attrs must be specified as a list.'\n ret['result'] = False\n return ret\n else:\n _attrs = '*'\n\n sql = 'select {0} from {1}'.format(_attrs, table)\n\n if where:\n sql = '{0} where {1}'.format(sql, where)\n\n sql = '{0};'.format(sql)\n\n res = _osquery(sql)\n if res['result']:\n ret['data'] = res['data']\n else:\n ret['comment'] = res['error']\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Support for OSQuery - https://osquery.io. .. versionadded:: 2015.8.0 ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import logging # Import Salt libs import salt.utils.json import salt.utils.path import salt.utils.platform log = logging.getLogger(__name__) __func_alias__ = { 'file_': 'file', 'hash_': 'hash', 'time_': 'time', } __virtualname__ = 'osquery' def __virtual__(): if salt.utils.path.which('osqueryi'): return __virtualname__ return (False, 'The osquery execution module cannot be loaded: ' 'osqueryi binary is not in the path.') def _table_attrs(table): ''' Helper function to find valid table attributes ''' cmd = ['osqueryi'] + ['--json'] + ['pragma table_info({0})'.format(table)] res = __salt__['cmd.run_all'](cmd) if res['retcode'] == 0: attrs = [] text = salt.utils.json.loads(res['stdout']) for item in text: attrs.append(item['name']) return attrs return False def _osquery(sql, format='json'): ''' Helper function to run raw osquery queries ''' ret = { 'result': True, } cmd = ['osqueryi'] + ['--json'] + [sql] res = __salt__['cmd.run_all'](cmd) if res['stderr']: ret['result'] = False ret['error'] = res['stderr'] else: ret['data'] = salt.utils.json.loads(res['stdout']) log.debug('== %s ==', ret) return ret def _osquery_cmd(table, attrs=None, where=None, format='json'): ''' Helper function to run osquery queries ''' ret = { 'result': True, } if attrs: if isinstance(attrs, list): valid_attrs = _table_attrs(table) if valid_attrs: for a in attrs: if a not in valid_attrs: ret['result'] = False ret['comment'] = '{0} is not a valid attribute for table {1}'.format(a, table) return ret _attrs = ','.join(attrs) else: ret['result'] = False ret['comment'] = 'Invalid table {0}.'.format(table) return ret else: ret['comment'] = 'attrs must be specified as a list.' ret['result'] = False return ret else: _attrs = '*' sql = 'select {0} from {1}'.format(_attrs, table) if where: sql = '{0} where {1}'.format(sql, where) sql = '{0};'.format(sql) res = _osquery(sql) if res['result']: ret['data'] = res['data'] else: ret['comment'] = res['error'] return ret def version(): ''' Return version of osquery CLI Example: .. code-block:: bash salt '*' osquery.version ''' _false_return = {'result': False, 'comment': 'OSQuery version unavailable.'} res = _osquery_cmd(table='osquery_info', attrs=['version']) if 'result' in res and res['result']: if 'data' in res and isinstance(res['data'], list): return res['data'][0].get('version', '') or _false_return return _false_return def rpm_packages(attrs=None, where=None): ''' Return cpuid information from osquery CLI Example: .. code-block:: bash salt '*' osquery.rpm_packages ''' if __grains__['os_family'] == 'RedHat': return _osquery_cmd(table='rpm_packages', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat based systems.'} def kernel_integrity(attrs=None, where=None): ''' Return kernel_integrity information from osquery CLI Example: .. code-block:: bash salt '*' osquery.kernel_integrity ''' if __grains__['os_family'] in ['RedHat', 'Debian']: return _osquery_cmd(table='kernel_integrity', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat or Debian based systems.'} def kernel_modules(attrs=None, where=None): ''' Return kernel_modules information from osquery CLI Example: .. code-block:: bash salt '*' osquery.kernel_modules ''' if __grains__['os_family'] in ['RedHat', 'Debian']: return _osquery_cmd(table='kernel_modules', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat or Debian based systems.'} def memory_map(attrs=None, where=None): ''' Return memory_map information from osquery CLI Example: .. code-block:: bash salt '*' osquery.memory_map ''' if __grains__['os_family'] in ['RedHat', 'Debian']: return _osquery_cmd(table='memory_map', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat or Debian based systems.'} def process_memory_map(attrs=None, where=None): ''' Return process_memory_map information from osquery CLI Example: .. code-block:: bash salt '*' osquery.process_memory_map ''' if __grains__['os_family'] in ['RedHat', 'Debian']: return _osquery_cmd(table='process_memory_map', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat or Debian based systems.'} def shared_memory(attrs=None, where=None): ''' Return shared_memory information from osquery CLI Example: .. code-block:: bash salt '*' osquery.shared_memory ''' if __grains__['os_family'] in ['RedHat', 'Debian']: return _osquery_cmd(table='shared_memory', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat or Debian based systems.'} def apt_sources(attrs=None, where=None): ''' Return apt_sources information from osquery CLI Example: .. code-block:: bash salt '*' osquery.apt_sources ''' if __grains__['os_family'] == 'Debian': return _osquery_cmd(table='apt_sources', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Debian based systems.'} def acpi_tables(attrs=None, where=None): ''' Return acpi_tables information from osquery CLI Example: .. code-block:: bash salt '*' osquery.acpi_tables ''' return _osquery_cmd(table='acpi_tables', attrs=attrs, where=where) def arp_cache(attrs=None, where=None): ''' Return arp_cache information from osquery CLI Example: .. code-block:: bash salt '*' osquery.arp_cache ''' return _osquery_cmd(table='arp_cache', attrs=attrs, where=where) def block_devices(attrs=None, where=None): ''' Return block_devices information from osquery CLI Example: .. code-block:: bash salt '*' osquery.block_devices ''' return _osquery_cmd(table='block_devices', attrs=attrs, where=where) def cpuid(attrs=None, where=None): ''' Return cpuid information from osquery CLI Example: .. code-block:: bash salt '*' osquery.cpuid ''' return _osquery_cmd(table='cpuid', attrs=attrs, where=where) def crontab(attrs=None, where=None): ''' Return crontab information from osquery CLI Example: .. code-block:: bash salt '*' osquery.crontab ''' return _osquery_cmd(table='crontab', attrs=attrs, where=where) def etc_hosts(attrs=None, where=None): ''' Return etc_hosts information from osquery CLI Example: .. code-block:: bash salt '*' osquery.etc_hosts ''' return _osquery_cmd(table='etc_hosts', attrs=attrs, where=where) def etc_services(attrs=None, where=None): ''' Return etc_services information from osquery CLI Example: .. code-block:: bash salt '*' osquery.etc_services ''' return _osquery_cmd(table='etc_services', attrs=attrs, where=where) def file_changes(attrs=None, where=None): ''' Return file_changes information from osquery CLI Example: .. code-block:: bash salt '*' osquery.file_changes ''' return _osquery_cmd(table='file_changes', attrs=attrs, where=where) def groups(attrs=None, where=None): ''' Return groups information from osquery CLI Example: .. code-block:: bash salt '*' osquery.groups ''' return _osquery_cmd(table='groups', attrs=attrs, where=where) def hardware_events(attrs=None, where=None): ''' Return hardware_events information from osquery CLI Example: .. code-block:: bash salt '*' osquery.hardware_events ''' return _osquery_cmd(table='hardware_events', attrs=attrs, where=where) def interface_addresses(attrs=None, where=None): ''' Return interface_addresses information from osquery CLI Example: .. code-block:: bash salt '*' osquery.interface_addresses ''' return _osquery_cmd(table='interface_addresses', attrs=attrs, where=where) def interface_details(attrs=None, where=None): ''' Return interface_details information from osquery CLI Example: .. code-block:: bash salt '*' osquery.interface_details ''' return _osquery_cmd(table='interface_details', attrs=attrs, where=where) def kernel_info(attrs=None, where=None): ''' Return kernel_info information from osquery CLI Example: .. code-block:: bash salt '*' osquery.kernel_info ''' return _osquery_cmd(table='kernel_info', attrs=attrs, where=where) def last(attrs=None, where=None): ''' Return last information from osquery CLI Example: .. code-block:: bash salt '*' osquery.last ''' return _osquery_cmd(table='last', attrs=attrs, where=where) def listening_ports(attrs=None, where=None): r''' Return listening_ports information from osquery CLI Example: .. code-block:: bash salt '*' osquery.listening_ports ''' return _osquery_cmd(table='listening_ports', attrs=attrs, where=where) def logged_in_users(attrs=None, where=None): r''' Return logged_in_users information from osquery CLI Example: .. code-block:: bash salt '*' osquery.logged_in_users ''' return _osquery_cmd(table='logged_in_users', attrs=attrs, where=where) def mounts(attrs=None, where=None): r''' Return mounts information from osquery CLI Example: .. code-block:: bash salt '*' osquery.mounts ''' return _osquery_cmd(table='mounts', attrs=attrs, where=where) def os_version(attrs=None, where=None): ''' Return os_version information from osquery CLI Example: .. code-block:: bash salt '*' osquery.os_version ''' return _osquery_cmd(table='os_version', attrs=attrs, where=where) def passwd_changes(attrs=None, where=None): ''' Return passwd_changes information from osquery CLI Example: .. code-block:: bash salt '*' osquery.passwd_changes ''' return _osquery_cmd(table='passwd_changes', attrs=attrs, where=where) def pci_devices(attrs=None, where=None): ''' Return pci_devices information from osquery CLI Example: .. code-block:: bash salt '*' osquery.pci_devices ''' return _osquery_cmd(table='pci_devices', attrs=attrs, where=where) def process_envs(attrs=None, where=None): ''' Return process_envs information from osquery CLI Example: .. code-block:: bash salt '*' osquery.process_envs ''' return _osquery_cmd(table='process_envs', attrs=attrs, where=where) def process_open_files(attrs=None, where=None): ''' Return process_open_files information from osquery CLI Example: .. code-block:: bash salt '*' osquery.process_open_files ''' return _osquery_cmd(table='process_open_files', attrs=attrs, where=where) def process_open_sockets(attrs=None, where=None): ''' Return process_open_sockets information from osquery CLI Example: .. code-block:: bash salt '*' osquery.process_open_sockets ''' return _osquery_cmd(table='process_open_sockets', attrs=attrs, where=where) def processes(attrs=None, where=None): ''' Return processes information from osquery CLI Example: .. code-block:: bash salt '*' osquery.processes ''' return _osquery_cmd(table='processes', attrs=attrs, where=where) def routes(attrs=None, where=None): ''' Return routes information from osquery CLI Example: .. code-block:: bash salt '*' osquery.routes ''' return _osquery_cmd(table='routes', attrs=attrs, where=where) def shell_history(attrs=None, where=None): ''' Return shell_history information from osquery CLI Example: .. code-block:: bash salt '*' osquery.shell_history ''' return _osquery_cmd(table='shell_history', attrs=attrs, where=where) def smbios_tables(attrs=None, where=None): ''' Return smbios_tables information from osquery CLI Example: .. code-block:: bash salt '*' osquery.smbios_tables ''' return _osquery_cmd(table='smbios_tables', attrs=attrs, where=where) def suid_bin(attrs=None, where=None): ''' Return suid_bin information from osquery CLI Example: .. code-block:: bash salt '*' osquery.suid_bin ''' return _osquery_cmd(table='suid_bin', attrs=attrs, where=where) def system_controls(attrs=None, where=None): ''' Return system_controls information from osquery CLI Example: .. code-block:: bash salt '*' osquery.system_controls ''' return _osquery_cmd(table='system_controls', attrs=attrs, where=where) def usb_devices(attrs=None, where=None): ''' Return usb_devices information from osquery CLI Example: .. code-block:: bash salt '*' osquery.usb_devices ''' return _osquery_cmd(table='usb_devices', attrs=attrs, where=where) def users(attrs=None, where=None): ''' Return users information from osquery CLI Example: .. code-block:: bash salt '*' osquery.users ''' return _osquery_cmd(table='users', attrs=attrs, where=where) def alf(attrs=None, where=None): ''' Return alf information from osquery CLI Example: .. code-block:: bash salt '*' osquery.alf ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='alf', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def alf_exceptions(attrs=None, where=None): ''' Return alf_exceptions information from osquery CLI Example: .. code-block:: bash salt '*' osquery.alf_exceptions ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='alf_exceptions', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def alf_explicit_auths(attrs=None, where=None): ''' Return alf_explicit_auths information from osquery CLI Example: .. code-block:: bash salt '*' osquery.alf_explicit_auths ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='alf_explicit_auths', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def alf_services(attrs=None, where=None): ''' Return alf_services information from osquery CLI Example: .. code-block:: bash salt '*' osquery.alf_services ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='alf_services', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def apps(attrs=None, where=None): ''' Return apps information from osquery CLI Example: .. code-block:: bash salt '*' osquery.apps ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='apps', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def certificates(attrs=None, where=None): ''' Return certificates information from osquery CLI Example: .. code-block:: bash salt '*' osquery.certificates ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='certificates', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def chrome_extensions(attrs=None, where=None): ''' Return chrome_extensions information from osquery CLI Example: .. code-block:: bash salt '*' osquery.chrome_extensions ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='chrome_extensions', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def firefox_addons(attrs=None, where=None): ''' Return firefox_addons information from osquery CLI Example: .. code-block:: bash salt '*' osquery.firefox_addons ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='firefox_addons', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def homebrew_packages(attrs=None, where=None): ''' Return homebrew_packages information from osquery CLI Example: .. code-block:: bash salt '*' osquery.homebrew_packages ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='homebrew_packages', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def iokit_devicetree(attrs=None, where=None): ''' Return iokit_devicetree information from osquery CLI Example: .. code-block:: bash salt '*' osquery.iokit_devicetree ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='iokit_devicetree', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def iokit_registry(attrs=None, where=None): ''' Return iokit_registry information from osquery CLI Example: .. code-block:: bash salt '*' osquery.iokit_registry ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='iokit_registry', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def kernel_extensions(attrs=None, where=None): ''' Return kernel_extensions information from osquery CLI Example: .. code-block:: bash salt '*' osquery.kernel_extensions ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='kernel_extensions', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def keychain_items(attrs=None, where=None): ''' Return keychain_items information from osquery CLI Example: .. code-block:: bash salt '*' osquery.keychain_items ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='keychain_items', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def launchd(attrs=None, where=None): ''' Return launchd information from osquery CLI Example: .. code-block:: bash salt '*' osquery.launchd ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='launchd', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def nfs_shares(attrs=None, where=None): ''' Return nfs_shares information from osquery CLI Example: .. code-block:: bash salt '*' osquery.nfs_shares ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='nfs_shares', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def nvram(attrs=None, where=None): ''' Return nvram information from osquery CLI Example: .. code-block:: bash salt '*' osquery.nvram ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='nvram', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def preferences(attrs=None, where=None): ''' Return preferences information from osquery CLI Example: .. code-block:: bash salt '*' osquery.preferences ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='preferences', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def quarantine(attrs=None, where=None): ''' Return quarantine information from osquery CLI Example: .. code-block:: bash salt '*' osquery.quarantine ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='quarantine', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def safari_extensions(attrs=None, where=None): ''' Return safari_extensions information from osquery CLI Example: .. code-block:: bash salt '*' osquery.safari_extensions ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='safari_extensions', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def startup_items(attrs=None, where=None): ''' Return startup_items information from osquery CLI Example: .. code-block:: bash salt '*' osquery.startup_items ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='startup_items', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def xattr_where_from(attrs=None, where=None): ''' Return xattr_where_from information from osquery CLI Example: .. code-block:: bash salt '*' osquery.xattr_where_from ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='xattr_where_from', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def xprotect_entries(attrs=None, where=None): ''' Return xprotect_entries information from osquery CLI Example: .. code-block:: bash salt '*' osquery.xprotect_entries ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='xprotect_entries', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def xprotect_reports(attrs=None, where=None): ''' Return xprotect_reports information from osquery CLI Example: .. code-block:: bash salt '*' osquery.xprotect_reports ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='xprotect_reports', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def file_(attrs=None, where=None): ''' Return file information from osquery CLI Example: .. code-block:: bash salt '*' osquery.file ''' return _osquery_cmd(table='file', attrs=attrs, where=where) def hash_(attrs=None, where=None): ''' Return hash information from osquery CLI Example: .. code-block:: bash salt '*' osquery.hash ''' return _osquery_cmd(table='hash', attrs=attrs, where=where) def osquery_extensions(attrs=None, where=None): ''' Return osquery_extensions information from osquery CLI Example: .. code-block:: bash salt '*' osquery.osquery_extensions ''' return _osquery_cmd(table='osquery_extensions', attrs=attrs, where=where) def osquery_flags(attrs=None, where=None): ''' Return osquery_flags information from osquery CLI Example: .. code-block:: bash salt '*' osquery.osquery_flags ''' return _osquery_cmd(table='osquery_flags', attrs=attrs, where=where) def osquery_info(attrs=None, where=None): ''' Return osquery_info information from osquery CLI Example: .. code-block:: bash salt '*' osquery.osquery_info ''' return _osquery_cmd(table='osquery_info', attrs=attrs, where=where) def osquery_registry(attrs=None, where=None): ''' Return osquery_registry information from osquery CLI Example: .. code-block:: bash salt '*' osquery.osquery_registry ''' return _osquery_cmd(table='osquery_registry', attrs=attrs, where=where) def time_(attrs=None): ''' Return time information from osquery CLI Example: .. code-block:: bash salt '*' osquery.time ''' return _osquery_cmd(table='time', attrs=attrs) def query(sql=None): ''' Return time information from osquery CLI Example: .. code-block:: bash salt '*' osquery.query "select * from users;" ''' return _osquery(sql)
saltstack/salt
salt/modules/osquery.py
alf
python
def alf(attrs=None, where=None): ''' Return alf information from osquery CLI Example: .. code-block:: bash salt '*' osquery.alf ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='alf', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'}
Return alf information from osquery CLI Example: .. code-block:: bash salt '*' osquery.alf
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/osquery.py#L657-L669
[ "def _osquery_cmd(table, attrs=None, where=None, format='json'):\n '''\n Helper function to run osquery queries\n '''\n ret = {\n 'result': True,\n }\n\n if attrs:\n if isinstance(attrs, list):\n valid_attrs = _table_attrs(table)\n if valid_attrs:\n for a in attrs:\n if a not in valid_attrs:\n ret['result'] = False\n ret['comment'] = '{0} is not a valid attribute for table {1}'.format(a, table)\n return ret\n _attrs = ','.join(attrs)\n else:\n ret['result'] = False\n ret['comment'] = 'Invalid table {0}.'.format(table)\n return ret\n else:\n ret['comment'] = 'attrs must be specified as a list.'\n ret['result'] = False\n return ret\n else:\n _attrs = '*'\n\n sql = 'select {0} from {1}'.format(_attrs, table)\n\n if where:\n sql = '{0} where {1}'.format(sql, where)\n\n sql = '{0};'.format(sql)\n\n res = _osquery(sql)\n if res['result']:\n ret['data'] = res['data']\n else:\n ret['comment'] = res['error']\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Support for OSQuery - https://osquery.io. .. versionadded:: 2015.8.0 ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import logging # Import Salt libs import salt.utils.json import salt.utils.path import salt.utils.platform log = logging.getLogger(__name__) __func_alias__ = { 'file_': 'file', 'hash_': 'hash', 'time_': 'time', } __virtualname__ = 'osquery' def __virtual__(): if salt.utils.path.which('osqueryi'): return __virtualname__ return (False, 'The osquery execution module cannot be loaded: ' 'osqueryi binary is not in the path.') def _table_attrs(table): ''' Helper function to find valid table attributes ''' cmd = ['osqueryi'] + ['--json'] + ['pragma table_info({0})'.format(table)] res = __salt__['cmd.run_all'](cmd) if res['retcode'] == 0: attrs = [] text = salt.utils.json.loads(res['stdout']) for item in text: attrs.append(item['name']) return attrs return False def _osquery(sql, format='json'): ''' Helper function to run raw osquery queries ''' ret = { 'result': True, } cmd = ['osqueryi'] + ['--json'] + [sql] res = __salt__['cmd.run_all'](cmd) if res['stderr']: ret['result'] = False ret['error'] = res['stderr'] else: ret['data'] = salt.utils.json.loads(res['stdout']) log.debug('== %s ==', ret) return ret def _osquery_cmd(table, attrs=None, where=None, format='json'): ''' Helper function to run osquery queries ''' ret = { 'result': True, } if attrs: if isinstance(attrs, list): valid_attrs = _table_attrs(table) if valid_attrs: for a in attrs: if a not in valid_attrs: ret['result'] = False ret['comment'] = '{0} is not a valid attribute for table {1}'.format(a, table) return ret _attrs = ','.join(attrs) else: ret['result'] = False ret['comment'] = 'Invalid table {0}.'.format(table) return ret else: ret['comment'] = 'attrs must be specified as a list.' ret['result'] = False return ret else: _attrs = '*' sql = 'select {0} from {1}'.format(_attrs, table) if where: sql = '{0} where {1}'.format(sql, where) sql = '{0};'.format(sql) res = _osquery(sql) if res['result']: ret['data'] = res['data'] else: ret['comment'] = res['error'] return ret def version(): ''' Return version of osquery CLI Example: .. code-block:: bash salt '*' osquery.version ''' _false_return = {'result': False, 'comment': 'OSQuery version unavailable.'} res = _osquery_cmd(table='osquery_info', attrs=['version']) if 'result' in res and res['result']: if 'data' in res and isinstance(res['data'], list): return res['data'][0].get('version', '') or _false_return return _false_return def rpm_packages(attrs=None, where=None): ''' Return cpuid information from osquery CLI Example: .. code-block:: bash salt '*' osquery.rpm_packages ''' if __grains__['os_family'] == 'RedHat': return _osquery_cmd(table='rpm_packages', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat based systems.'} def kernel_integrity(attrs=None, where=None): ''' Return kernel_integrity information from osquery CLI Example: .. code-block:: bash salt '*' osquery.kernel_integrity ''' if __grains__['os_family'] in ['RedHat', 'Debian']: return _osquery_cmd(table='kernel_integrity', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat or Debian based systems.'} def kernel_modules(attrs=None, where=None): ''' Return kernel_modules information from osquery CLI Example: .. code-block:: bash salt '*' osquery.kernel_modules ''' if __grains__['os_family'] in ['RedHat', 'Debian']: return _osquery_cmd(table='kernel_modules', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat or Debian based systems.'} def memory_map(attrs=None, where=None): ''' Return memory_map information from osquery CLI Example: .. code-block:: bash salt '*' osquery.memory_map ''' if __grains__['os_family'] in ['RedHat', 'Debian']: return _osquery_cmd(table='memory_map', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat or Debian based systems.'} def process_memory_map(attrs=None, where=None): ''' Return process_memory_map information from osquery CLI Example: .. code-block:: bash salt '*' osquery.process_memory_map ''' if __grains__['os_family'] in ['RedHat', 'Debian']: return _osquery_cmd(table='process_memory_map', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat or Debian based systems.'} def shared_memory(attrs=None, where=None): ''' Return shared_memory information from osquery CLI Example: .. code-block:: bash salt '*' osquery.shared_memory ''' if __grains__['os_family'] in ['RedHat', 'Debian']: return _osquery_cmd(table='shared_memory', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat or Debian based systems.'} def apt_sources(attrs=None, where=None): ''' Return apt_sources information from osquery CLI Example: .. code-block:: bash salt '*' osquery.apt_sources ''' if __grains__['os_family'] == 'Debian': return _osquery_cmd(table='apt_sources', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Debian based systems.'} def deb_packages(attrs=None, where=None): ''' Return deb_packages information from osquery CLI Example: .. code-block:: bash salt '*' osquery.deb_packages ''' if __grains__['os_family'] == 'Debian': return _osquery_cmd(table='deb_packages', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Debian based systems.'} def acpi_tables(attrs=None, where=None): ''' Return acpi_tables information from osquery CLI Example: .. code-block:: bash salt '*' osquery.acpi_tables ''' return _osquery_cmd(table='acpi_tables', attrs=attrs, where=where) def arp_cache(attrs=None, where=None): ''' Return arp_cache information from osquery CLI Example: .. code-block:: bash salt '*' osquery.arp_cache ''' return _osquery_cmd(table='arp_cache', attrs=attrs, where=where) def block_devices(attrs=None, where=None): ''' Return block_devices information from osquery CLI Example: .. code-block:: bash salt '*' osquery.block_devices ''' return _osquery_cmd(table='block_devices', attrs=attrs, where=where) def cpuid(attrs=None, where=None): ''' Return cpuid information from osquery CLI Example: .. code-block:: bash salt '*' osquery.cpuid ''' return _osquery_cmd(table='cpuid', attrs=attrs, where=where) def crontab(attrs=None, where=None): ''' Return crontab information from osquery CLI Example: .. code-block:: bash salt '*' osquery.crontab ''' return _osquery_cmd(table='crontab', attrs=attrs, where=where) def etc_hosts(attrs=None, where=None): ''' Return etc_hosts information from osquery CLI Example: .. code-block:: bash salt '*' osquery.etc_hosts ''' return _osquery_cmd(table='etc_hosts', attrs=attrs, where=where) def etc_services(attrs=None, where=None): ''' Return etc_services information from osquery CLI Example: .. code-block:: bash salt '*' osquery.etc_services ''' return _osquery_cmd(table='etc_services', attrs=attrs, where=where) def file_changes(attrs=None, where=None): ''' Return file_changes information from osquery CLI Example: .. code-block:: bash salt '*' osquery.file_changes ''' return _osquery_cmd(table='file_changes', attrs=attrs, where=where) def groups(attrs=None, where=None): ''' Return groups information from osquery CLI Example: .. code-block:: bash salt '*' osquery.groups ''' return _osquery_cmd(table='groups', attrs=attrs, where=where) def hardware_events(attrs=None, where=None): ''' Return hardware_events information from osquery CLI Example: .. code-block:: bash salt '*' osquery.hardware_events ''' return _osquery_cmd(table='hardware_events', attrs=attrs, where=where) def interface_addresses(attrs=None, where=None): ''' Return interface_addresses information from osquery CLI Example: .. code-block:: bash salt '*' osquery.interface_addresses ''' return _osquery_cmd(table='interface_addresses', attrs=attrs, where=where) def interface_details(attrs=None, where=None): ''' Return interface_details information from osquery CLI Example: .. code-block:: bash salt '*' osquery.interface_details ''' return _osquery_cmd(table='interface_details', attrs=attrs, where=where) def kernel_info(attrs=None, where=None): ''' Return kernel_info information from osquery CLI Example: .. code-block:: bash salt '*' osquery.kernel_info ''' return _osquery_cmd(table='kernel_info', attrs=attrs, where=where) def last(attrs=None, where=None): ''' Return last information from osquery CLI Example: .. code-block:: bash salt '*' osquery.last ''' return _osquery_cmd(table='last', attrs=attrs, where=where) def listening_ports(attrs=None, where=None): r''' Return listening_ports information from osquery CLI Example: .. code-block:: bash salt '*' osquery.listening_ports ''' return _osquery_cmd(table='listening_ports', attrs=attrs, where=where) def logged_in_users(attrs=None, where=None): r''' Return logged_in_users information from osquery CLI Example: .. code-block:: bash salt '*' osquery.logged_in_users ''' return _osquery_cmd(table='logged_in_users', attrs=attrs, where=where) def mounts(attrs=None, where=None): r''' Return mounts information from osquery CLI Example: .. code-block:: bash salt '*' osquery.mounts ''' return _osquery_cmd(table='mounts', attrs=attrs, where=where) def os_version(attrs=None, where=None): ''' Return os_version information from osquery CLI Example: .. code-block:: bash salt '*' osquery.os_version ''' return _osquery_cmd(table='os_version', attrs=attrs, where=where) def passwd_changes(attrs=None, where=None): ''' Return passwd_changes information from osquery CLI Example: .. code-block:: bash salt '*' osquery.passwd_changes ''' return _osquery_cmd(table='passwd_changes', attrs=attrs, where=where) def pci_devices(attrs=None, where=None): ''' Return pci_devices information from osquery CLI Example: .. code-block:: bash salt '*' osquery.pci_devices ''' return _osquery_cmd(table='pci_devices', attrs=attrs, where=where) def process_envs(attrs=None, where=None): ''' Return process_envs information from osquery CLI Example: .. code-block:: bash salt '*' osquery.process_envs ''' return _osquery_cmd(table='process_envs', attrs=attrs, where=where) def process_open_files(attrs=None, where=None): ''' Return process_open_files information from osquery CLI Example: .. code-block:: bash salt '*' osquery.process_open_files ''' return _osquery_cmd(table='process_open_files', attrs=attrs, where=where) def process_open_sockets(attrs=None, where=None): ''' Return process_open_sockets information from osquery CLI Example: .. code-block:: bash salt '*' osquery.process_open_sockets ''' return _osquery_cmd(table='process_open_sockets', attrs=attrs, where=where) def processes(attrs=None, where=None): ''' Return processes information from osquery CLI Example: .. code-block:: bash salt '*' osquery.processes ''' return _osquery_cmd(table='processes', attrs=attrs, where=where) def routes(attrs=None, where=None): ''' Return routes information from osquery CLI Example: .. code-block:: bash salt '*' osquery.routes ''' return _osquery_cmd(table='routes', attrs=attrs, where=where) def shell_history(attrs=None, where=None): ''' Return shell_history information from osquery CLI Example: .. code-block:: bash salt '*' osquery.shell_history ''' return _osquery_cmd(table='shell_history', attrs=attrs, where=where) def smbios_tables(attrs=None, where=None): ''' Return smbios_tables information from osquery CLI Example: .. code-block:: bash salt '*' osquery.smbios_tables ''' return _osquery_cmd(table='smbios_tables', attrs=attrs, where=where) def suid_bin(attrs=None, where=None): ''' Return suid_bin information from osquery CLI Example: .. code-block:: bash salt '*' osquery.suid_bin ''' return _osquery_cmd(table='suid_bin', attrs=attrs, where=where) def system_controls(attrs=None, where=None): ''' Return system_controls information from osquery CLI Example: .. code-block:: bash salt '*' osquery.system_controls ''' return _osquery_cmd(table='system_controls', attrs=attrs, where=where) def usb_devices(attrs=None, where=None): ''' Return usb_devices information from osquery CLI Example: .. code-block:: bash salt '*' osquery.usb_devices ''' return _osquery_cmd(table='usb_devices', attrs=attrs, where=where) def users(attrs=None, where=None): ''' Return users information from osquery CLI Example: .. code-block:: bash salt '*' osquery.users ''' return _osquery_cmd(table='users', attrs=attrs, where=where) def alf_exceptions(attrs=None, where=None): ''' Return alf_exceptions information from osquery CLI Example: .. code-block:: bash salt '*' osquery.alf_exceptions ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='alf_exceptions', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def alf_explicit_auths(attrs=None, where=None): ''' Return alf_explicit_auths information from osquery CLI Example: .. code-block:: bash salt '*' osquery.alf_explicit_auths ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='alf_explicit_auths', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def alf_services(attrs=None, where=None): ''' Return alf_services information from osquery CLI Example: .. code-block:: bash salt '*' osquery.alf_services ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='alf_services', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def apps(attrs=None, where=None): ''' Return apps information from osquery CLI Example: .. code-block:: bash salt '*' osquery.apps ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='apps', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def certificates(attrs=None, where=None): ''' Return certificates information from osquery CLI Example: .. code-block:: bash salt '*' osquery.certificates ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='certificates', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def chrome_extensions(attrs=None, where=None): ''' Return chrome_extensions information from osquery CLI Example: .. code-block:: bash salt '*' osquery.chrome_extensions ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='chrome_extensions', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def firefox_addons(attrs=None, where=None): ''' Return firefox_addons information from osquery CLI Example: .. code-block:: bash salt '*' osquery.firefox_addons ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='firefox_addons', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def homebrew_packages(attrs=None, where=None): ''' Return homebrew_packages information from osquery CLI Example: .. code-block:: bash salt '*' osquery.homebrew_packages ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='homebrew_packages', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def iokit_devicetree(attrs=None, where=None): ''' Return iokit_devicetree information from osquery CLI Example: .. code-block:: bash salt '*' osquery.iokit_devicetree ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='iokit_devicetree', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def iokit_registry(attrs=None, where=None): ''' Return iokit_registry information from osquery CLI Example: .. code-block:: bash salt '*' osquery.iokit_registry ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='iokit_registry', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def kernel_extensions(attrs=None, where=None): ''' Return kernel_extensions information from osquery CLI Example: .. code-block:: bash salt '*' osquery.kernel_extensions ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='kernel_extensions', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def keychain_items(attrs=None, where=None): ''' Return keychain_items information from osquery CLI Example: .. code-block:: bash salt '*' osquery.keychain_items ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='keychain_items', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def launchd(attrs=None, where=None): ''' Return launchd information from osquery CLI Example: .. code-block:: bash salt '*' osquery.launchd ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='launchd', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def nfs_shares(attrs=None, where=None): ''' Return nfs_shares information from osquery CLI Example: .. code-block:: bash salt '*' osquery.nfs_shares ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='nfs_shares', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def nvram(attrs=None, where=None): ''' Return nvram information from osquery CLI Example: .. code-block:: bash salt '*' osquery.nvram ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='nvram', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def preferences(attrs=None, where=None): ''' Return preferences information from osquery CLI Example: .. code-block:: bash salt '*' osquery.preferences ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='preferences', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def quarantine(attrs=None, where=None): ''' Return quarantine information from osquery CLI Example: .. code-block:: bash salt '*' osquery.quarantine ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='quarantine', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def safari_extensions(attrs=None, where=None): ''' Return safari_extensions information from osquery CLI Example: .. code-block:: bash salt '*' osquery.safari_extensions ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='safari_extensions', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def startup_items(attrs=None, where=None): ''' Return startup_items information from osquery CLI Example: .. code-block:: bash salt '*' osquery.startup_items ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='startup_items', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def xattr_where_from(attrs=None, where=None): ''' Return xattr_where_from information from osquery CLI Example: .. code-block:: bash salt '*' osquery.xattr_where_from ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='xattr_where_from', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def xprotect_entries(attrs=None, where=None): ''' Return xprotect_entries information from osquery CLI Example: .. code-block:: bash salt '*' osquery.xprotect_entries ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='xprotect_entries', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def xprotect_reports(attrs=None, where=None): ''' Return xprotect_reports information from osquery CLI Example: .. code-block:: bash salt '*' osquery.xprotect_reports ''' if salt.utils.platform.is_darwin(): return _osquery_cmd(table='xprotect_reports', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on macOS systems.'} def file_(attrs=None, where=None): ''' Return file information from osquery CLI Example: .. code-block:: bash salt '*' osquery.file ''' return _osquery_cmd(table='file', attrs=attrs, where=where) def hash_(attrs=None, where=None): ''' Return hash information from osquery CLI Example: .. code-block:: bash salt '*' osquery.hash ''' return _osquery_cmd(table='hash', attrs=attrs, where=where) def osquery_extensions(attrs=None, where=None): ''' Return osquery_extensions information from osquery CLI Example: .. code-block:: bash salt '*' osquery.osquery_extensions ''' return _osquery_cmd(table='osquery_extensions', attrs=attrs, where=where) def osquery_flags(attrs=None, where=None): ''' Return osquery_flags information from osquery CLI Example: .. code-block:: bash salt '*' osquery.osquery_flags ''' return _osquery_cmd(table='osquery_flags', attrs=attrs, where=where) def osquery_info(attrs=None, where=None): ''' Return osquery_info information from osquery CLI Example: .. code-block:: bash salt '*' osquery.osquery_info ''' return _osquery_cmd(table='osquery_info', attrs=attrs, where=where) def osquery_registry(attrs=None, where=None): ''' Return osquery_registry information from osquery CLI Example: .. code-block:: bash salt '*' osquery.osquery_registry ''' return _osquery_cmd(table='osquery_registry', attrs=attrs, where=where) def time_(attrs=None): ''' Return time information from osquery CLI Example: .. code-block:: bash salt '*' osquery.time ''' return _osquery_cmd(table='time', attrs=attrs) def query(sql=None): ''' Return time information from osquery CLI Example: .. code-block:: bash salt '*' osquery.query "select * from users;" ''' return _osquery(sql)
saltstack/salt
salt/utils/lazy.py
verify_fun
python
def verify_fun(lazy_obj, fun): ''' Check that the function passed really exists ''' if not fun: raise salt.exceptions.SaltInvocationError( 'Must specify a function to run!\n' 'ex: manage.up' ) if fun not in lazy_obj: # If the requested function isn't available, lets say why raise salt.exceptions.CommandExecutionError(lazy_obj.missing_fun_string(fun))
Check that the function passed really exists
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/lazy.py#L19-L30
null
# -*- coding: utf-8 -*- ''' Lazily-evaluated data structures, primarily used by Salt's loader ''' # Import Python Libs from __future__ import absolute_import, unicode_literals import logging import salt.exceptions try: from collections.abc import MutableMapping except ImportError: from collections import MutableMapping log = logging.getLogger(__name__) class LazyDict(MutableMapping): ''' A base class of dict which will lazily load keys once they are needed TODO: negative caching? If you ask for 'foo' and it doesn't exist it will look EVERY time unless someone calls load_all() As of now this is left to the class which inherits from this base ''' def __init__(self): self.clear() def __nonzero__(self): # we are zero if dict is empty and loaded is true return bool(self._dict or not self.loaded) def __bool__(self): # we are zero if dict is empty and loaded is true return self.__nonzero__() def clear(self): ''' Clear the dict ''' # create a dict to store loaded values in self._dict = getattr(self, 'mod_dict_class', dict)() # have we already loded everything? self.loaded = False def _load(self, key): ''' Load a single item if you have it ''' raise NotImplementedError() def _load_all(self): ''' Load all of them ''' raise NotImplementedError() def _missing(self, key): ''' Whether or not the key is missing (meaning we know it's not there) ''' return False def missing_fun_string(self, function_name): ''' Return the error string for a missing function. Override this to return a more meaningfull error message if possible ''' return '\'{0}\' is not available.'.format(function_name) def __setitem__(self, key, val): self._dict[key] = val def __delitem__(self, key): del self._dict[key] def __getitem__(self, key): ''' Check if the key is ttld out, then do the get ''' if self._missing(key): raise KeyError(key) if key not in self._dict and not self.loaded: # load the item if self._load(key): log.debug('LazyLoaded %s', key) return self._dict[key] else: log.debug('Could not LazyLoad %s: %s', key, self.missing_fun_string(key)) raise KeyError(key) else: return self._dict[key] def __len__(self): # if not loaded, if not self.loaded: self._load_all() return len(self._dict) def __iter__(self): if not self.loaded: self._load_all() return iter(self._dict)
saltstack/salt
salt/utils/lazy.py
LazyDict.clear
python
def clear(self): ''' Clear the dict ''' # create a dict to store loaded values in self._dict = getattr(self, 'mod_dict_class', dict)() # have we already loded everything? self.loaded = False
Clear the dict
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/lazy.py#L52-L60
null
class LazyDict(MutableMapping): ''' A base class of dict which will lazily load keys once they are needed TODO: negative caching? If you ask for 'foo' and it doesn't exist it will look EVERY time unless someone calls load_all() As of now this is left to the class which inherits from this base ''' def __init__(self): self.clear() def __nonzero__(self): # we are zero if dict is empty and loaded is true return bool(self._dict or not self.loaded) def __bool__(self): # we are zero if dict is empty and loaded is true return self.__nonzero__() def _load(self, key): ''' Load a single item if you have it ''' raise NotImplementedError() def _load_all(self): ''' Load all of them ''' raise NotImplementedError() def _missing(self, key): ''' Whether or not the key is missing (meaning we know it's not there) ''' return False def missing_fun_string(self, function_name): ''' Return the error string for a missing function. Override this to return a more meaningfull error message if possible ''' return '\'{0}\' is not available.'.format(function_name) def __setitem__(self, key, val): self._dict[key] = val def __delitem__(self, key): del self._dict[key] def __getitem__(self, key): ''' Check if the key is ttld out, then do the get ''' if self._missing(key): raise KeyError(key) if key not in self._dict and not self.loaded: # load the item if self._load(key): log.debug('LazyLoaded %s', key) return self._dict[key] else: log.debug('Could not LazyLoad %s: %s', key, self.missing_fun_string(key)) raise KeyError(key) else: return self._dict[key] def __len__(self): # if not loaded, if not self.loaded: self._load_all() return len(self._dict) def __iter__(self): if not self.loaded: self._load_all() return iter(self._dict)
saltstack/salt
salt/modules/boto_iam.py
instance_profile_exists
python
def instance_profile_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an instance profile exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: # Boto weirdly returns an exception here if an instance profile doesn't # exist. conn.get_instance_profile(name) return True except boto.exception.BotoServerError: return False
Check to see if an instance profile exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iam.py#L86-L105
null
# -*- coding: utf-8 -*- ''' Connection module for Amazon IAM .. versionadded:: 2014.7.0 :configuration: This module accepts explicit iam 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 iam.keyid: GKTADJGHEIQSXMKKRBJ08H iam.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs iam.region: 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: boto ''' # keep lint from choking on _get_conn and _cache_id #pylint: disable=E0602 # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import salt libs from salt.ext import six import salt.utils.compat import salt.utils.json import salt.utils.odict as odict import salt.utils.versions from salt.exceptions import SaltInvocationError # Import third party libs # pylint: disable=unused-import from salt.ext.six.moves.urllib.parse import unquote as _unquote # pylint: disable=no-name-in-module try: import boto import boto.iam import boto3 import botocore logging.getLogger('boto').setLevel(logging.CRITICAL) logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=unused-import log = logging.getLogger(__name__) def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'iam', pack=__salt__) def create_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Create an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.create_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if instance_profile_exists(name, region, key, keyid, profile): return True try: # This call returns an instance profile if successful and an exception # if not. It's annoying. conn.create_instance_profile(name) log.info('Created %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create %s instance profile.', name) return False return True def delete_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Delete an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not instance_profile_exists(name, region, key, keyid, profile): return True try: conn.delete_instance_profile(name) log.info('Deleted %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s instance profile.', name) return False return True def role_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an IAM role exists. CLI Example: .. code-block:: bash salt myminion boto_iam.role_exists myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_role(name) return True except boto.exception.BotoServerError: return False def describe_role(name, region=None, key=None, keyid=None, profile=None): ''' Get information for a role. CLI Example: .. code-block:: bash salt myminion boto_iam.describe_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_role(name) if not info: return False role = info.get_role_response.get_role_result.role role['assume_role_policy_document'] = salt.utils.json.loads(_unquote( role.assume_role_policy_document )) # If Sid wasn't defined by the user, boto will still return a Sid in # each policy. To properly check idempotently, let's remove the Sid # from the return if it's not actually set. for policy_key, policy in role['assume_role_policy_document'].items(): if policy_key == 'Statement': for val in policy: if 'Sid' in val and not val['Sid']: del val['Sid'] return role except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get %s information.', name) return False def create_user(user_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_user myuser ''' if not path: path = '/' if get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_user(user_name, path) log.info('Created IAM user : %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM user %s.', user_name) return False def get_all_access_keys(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all access keys from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_access_keys myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.get_all_access_keys(user_name, marker, max_items) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get access keys for IAM user %s.', user_name) return six.text_type(e) def create_access_key(user_name, region=None, key=None, keyid=None, profile=None): ''' Create access key id for a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.create_access_key(user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create access key.') return six.text_type(e) def delete_access_key(access_key_id, user_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete access key id from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_access_key(access_key_id, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete access key id %s.', access_key_id) return six.text_type(e) def delete_user(user_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user myuser ''' if not get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.delete_user(user_name) log.info('Deleted IAM user : %s .', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM user %s', user_name) return six.text_type(e) def get_user(user_name=None, region=None, key=None, keyid=None, profile=None): ''' Get user information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user(user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM user %s info.', user_name) return False def create_group(group_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_group group ''' if not path: path = '/' if get_group(group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_group(group_name, path) log.info('Created IAM group : %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM group %s.', group_name) return False def get_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group(group_name, max_items=1) if not info: return False return info['get_group_response']['get_group_result']['group'] except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_group_members(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: marker = None truncated = True users = [] while truncated: info = conn.get_group(group_name, marker=marker, max_items=1000) if not info: return False truncated = bool(info['get_group_response']['get_group_result']['is_truncated']) if truncated and 'marker' in info['get_group_response']['get_group_result']: marker = info['get_group_response']['get_group_result']['marker'] else: marker = None truncated = False users += info['get_group_response']['get_group_result']['users'] return users except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get members for IAM group %s.', group_name) return False def add_user_to_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Add user to group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.add_user_to_group myuser mygroup ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('Username : %s does not exist.', user_name) return False if user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.add_user_to_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add IAM user %s to group %s.', user_name, group_name) return False def user_exists_in_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Check if user exists in group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.user_exists_in_group myuser mygroup ''' # TODO this should probably use boto.iam.get_groups_for_user users = get_group_members( group_name=group_name, region=region, key=key, keyid=keyid, profile=profile ) if users: for _user in users: if user_name == _user['user_name']: log.debug('IAM user %s is already in IAM group %s.', user_name, group_name) return True return False def remove_user_from_group(group_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Remove user from group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.remove_user_from_group mygroup myuser ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist.', user_name) return False if not user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.remove_user_from_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove IAM user %s from group %s', user_name, group_name) return False def put_group_policy(group_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_group_policy mygroup policyname policyrules ''' group = get_group(group_name, region=region, key=key, keyid=keyid, profile=profile) if not group: log.error('Group %s does not exist', group_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_group_policy(group_name, policy_name, policy_json) if created: log.info('Created policy for IAM group %s.', group_name) return True log.error('Could not create policy for IAM group %s', group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy for IAM group %s', group_name) return False def delete_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group_policy mygroup mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_group_policy( group_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_group_policy(group_name, policy_name) log.info('Successfully deleted policy %s for IAM group %s.', policy_name, group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM group %s.', policy_name, group_name) return False def get_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group_policy mygroup policyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group_policy(group_name, policy_name) log.debug('info for group policy is : %s', info) if not info: return False info = info.get_group_policy_response.get_group_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_all_groups(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM group details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_groups ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _groups = conn.get_all_groups(path_prefix=path_prefix) groups = _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) while marker: _groups = conn.get_all_groups(path_prefix=path_prefix, marker=marker) groups = groups + _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) return groups def get_all_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.get_all_instance_profiles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) marker = False profiles = [] while marker is not None: marker = marker if marker else None p = conn.list_instance_profiles(path_prefix=path_prefix, marker=marker) res = p.list_instance_profiles_response.list_instance_profiles_result profiles += res.instance_profiles marker = getattr(res, 'marker', None) return profiles def list_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' List all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.list_instance_profiles ''' p = get_all_instance_profiles(path_prefix, region, key, keyid, profile) return [i['instance_profile_name'] for i in p] def get_all_group_policies(group_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a group. CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_group_policies mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False try: response = conn.get_all_group_policies(group_name) _list = response.list_group_policies_response.list_group_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def delete_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _group = get_group( group_name, region, key, keyid, profile ) if not _group: return True try: conn.delete_group(group_name) log.info('Successfully deleted IAM group %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM group %s.', group_name) return False def create_login_profile(user_name, password, region=None, key=None, keyid=None, profile=None): ''' Creates a login profile for the specified user, give the user the ability to access AWS services and the AWS Management Console. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_login_profile user_name password ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.create_login_profile(user_name, password) log.info('Created profile for IAM user %s.', user_name) return info except boto.exception.BotoServerError as e: log.debug(e) if 'Conflict' in e: log.info('Profile already exists for IAM user %s.', user_name) return 'Conflict' log.error('Failed to update profile for IAM user %s.', user_name) return False def delete_login_profile(user_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a login profile for the specified user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_login_profile user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.delete_login_profile(user_name) log.info('Deleted login profile for IAM user %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Login profile already deleted for IAM user %s.', user_name) return True log.error('Failed to delete login profile for IAM user %s.', user_name) return False def get_all_mfa_devices(user_name, region=None, key=None, keyid=None, profile=None): ''' Get all MFA devices associated with an IAM user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_mfa_devices user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: result = conn.get_all_mfa_devices(user_name) devices = result['list_mfa_devices_response']['list_mfa_devices_result']['mfa_devices'] return devices except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Could not find IAM user %s.', user_name) return [] log.error('Failed to get all MFA devices for IAM user %s.', user_name) return False def deactivate_mfa_device(user_name, serial, region=None, key=None, keyid=None, profile=None): ''' Deactivates the specified MFA device and removes it from association with the user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.deactivate_mfa_device user_name serial_num ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.deactivate_mfa_device(user_name, serial) log.info('Deactivated MFA device %s for IAM user %s.', serial, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('MFA device %s not associated with IAM user %s.', serial, user_name) return True log.error('Failed to deactivate MFA device %s for IAM user %s.', serial, user_name) return False def delete_virtual_mfa_device(serial, region=None, key=None, keyid=None, profile=None): ''' Deletes the specified virtual MFA device. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_virtual_mfa_device serial_num ''' conn = __utils__['boto3.get_connection_func']('iam')() try: conn.delete_virtual_mfa_device(SerialNumber=serial) log.info('Deleted virtual MFA device %s.', serial) return True except botocore.exceptions.ClientError as e: log.debug(e) if 'NoSuchEntity' in six.text_type(e): log.info('Virtual MFA device %s not found.', serial) return True log.error('Failed to delete virtual MFA device %s.', serial) return False def update_account_password_policy(allow_users_to_change_password=None, hard_expiry=None, max_password_age=None, minimum_password_length=None, password_reuse_prevention=None, require_lowercase_characters=None, require_numbers=None, require_symbols=None, require_uppercase_characters=None, region=None, key=None, keyid=None, profile=None): ''' Update the password policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_account_password_policy True ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.update_account_password_policy(allow_users_to_change_password, hard_expiry, max_password_age, minimum_password_length, password_reuse_prevention, require_lowercase_characters, require_numbers, require_symbols, require_uppercase_characters) log.info('The password policy has been updated.') return True except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy' log.error(msg) return False def get_account_policy(region=None, key=None, keyid=None, profile=None): ''' Get account policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_account_password_policy() return info.get_account_password_policy_response.get_account_password_policy_result.password_policy except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy.' log.error(msg) return False def create_role(name, policy_document=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Create an instance role. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if role_exists(name, region, key, keyid, profile): return True if not policy_document: policy_document = None try: conn.create_role(name, assume_role_policy_document=policy_document, path=path) log.info('Created IAM role %s.', name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to create IAM role %s.', name) return False def delete_role(name, region=None, key=None, keyid=None, profile=None): ''' Delete an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(name, region, key, keyid, profile): return True try: conn.delete_role(name) log.info('Deleted %s IAM role.', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s IAM role.', name) return False def profile_associated(role_name, profile_name, region, key, keyid, profile): ''' Check to see if an instance profile is associated with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.profile_associated myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # The IAM module of boto doesn't return objects. Instead you need to grab # values through its properties. Sigh. try: profiles = conn.list_instance_profiles_for_role(role_name) except boto.exception.BotoServerError as e: log.debug(e) return False profiles = profiles.list_instance_profiles_for_role_response profiles = profiles.list_instance_profiles_for_role_result profiles = profiles.instance_profiles for profile in profiles: if profile.instance_profile_name == profile_name: return True return False def associate_profile_to_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Associate an instance profile with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.associate_profile_to_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if associated: return True else: try: conn.add_role_to_instance_profile(profile_name, role_name) log.info('Added %s instance profile to IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add %s instance profile to IAM role %s', profile_name, role_name) return False def disassociate_profile_from_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Disassociate an instance profile from an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.disassociate_profile_from_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if not associated: return True else: try: conn.remove_role_from_instance_profile(profile_name, role_name) log.info('Removed %s instance profile from IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove %s instance profile from IAM role %s.', profile_name, role_name) return False def list_role_policies(role_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_role_policies myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_role_policies(role_name) _list = response.list_role_policies_response.list_role_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def get_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.get_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: _policy = conn.get_role_policy(role_name, policy_name) # I _hate_ you for not giving me an object boto. _policy = _policy.get_role_policy_response.policy_document # Policy is url encoded _policy = _unquote(_policy) _policy = salt.utils.json.loads(_policy, object_pairs_hook=odict.OrderedDict) return _policy except boto.exception.BotoServerError: return {} def create_role_policy(role_name, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Create or modify a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role_policy myirole mypolicy '{"MyPolicy": "Statement": [{"Action": ["sqs:*"], "Effect": "Allow", "Resource": ["arn:aws:sqs:*:*:*"], "Sid": "MyPolicySqs1"}]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) mode = 'create' if _policy: if _policy == policy: return True mode = 'modify' if isinstance(policy, six.string_types): policy = salt.utils.json.loads(policy, object_pairs_hook=odict.OrderedDict) try: _policy = salt.utils.json.dumps(policy) conn.put_role_policy(role_name, policy_name, _policy) if mode == 'create': msg = 'Successfully added policy %s to IAM role %s.' else: msg = 'Successfully modified policy %s for IAM role %s.' log.info(msg, policy_name, role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to %s policy %s for IAM role %s.', mode, policy_name, role_name) return False def delete_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) if not _policy: return True try: conn.delete_role_policy(role_name, policy_name) log.info('Successfully deleted policy %s for IAM role %s.', policy_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM role %s.', policy_name, role_name) return False def update_assume_role_policy(role_name, policy_document, region=None, key=None, keyid=None, profile=None): ''' Update an assume role policy for a role. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_assume_role_policy myrole '{"Statement":"..."}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(policy_document, six.string_types): policy_document = salt.utils.json.loads(policy_document, object_pairs_hook=odict.OrderedDict) try: _policy_document = salt.utils.json.dumps(policy_document) conn.update_assume_role_policy(role_name, _policy_document) log.info('Successfully updated assume role policy for IAM role %s.', role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to update assume role policy for IAM role %s.', role_name) return False def build_policy(region=None, key=None, keyid=None, profile=None): ''' Build a default assume role policy. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.build_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if hasattr(conn, 'build_policy'): policy = salt.utils.json.loads(conn.build_policy()) elif hasattr(conn, '_build_policy'): policy = salt.utils.json.loads(conn._build_policy()) else: return {} # The format we get from build_policy isn't going to be what we get back # from AWS for the exact same policy. AWS converts single item list values # into strings, so let's do the same here. for key, policy_val in policy.items(): for statement in policy_val: if (isinstance(statement['Action'], list) and len(statement['Action']) == 1): statement['Action'] = statement['Action'][0] if (isinstance(statement['Principal']['Service'], list) and len(statement['Principal']['Service']) == 1): statement['Principal']['Service'] = statement['Principal']['Service'][0] # build_policy doesn't add a version field, which AWS is going to set to a # default value, when we get it back, so let's set it. policy['Version'] = '2008-10-17' return policy def get_account_id(region=None, key=None, keyid=None, profile=None): ''' Get a the AWS account id associated with the used credentials. CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_id ''' cache_key = 'boto_iam.account_id' if cache_key not in __context__: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_user() # The get_user call returns an user ARN: # arn:aws:iam::027050522557:user/salt-test arn = ret['get_user_response']['get_user_result']['user']['arn'] account_id = arn.split(':')[4] except boto.exception.BotoServerError: # If call failed, then let's try to get the ARN from the metadata timeout = boto.config.getfloat( 'Boto', 'metadata_service_timeout', 1.0 ) attempts = boto.config.getint( 'Boto', 'metadata_service_num_attempts', 1 ) identity = boto.utils.get_instance_identity( timeout=timeout, num_retries=attempts ) try: account_id = identity['document']['accountId'] except KeyError: log.error('Failed to get account id from instance_identity in' ' boto_iam.get_account_id.') __context__[cache_key] = account_id return __context__[cache_key] def get_all_roles(path_prefix=None, region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM role details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_roles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _roles = conn.list_roles(path_prefix=path_prefix) roles = _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) while marker: _roles = conn.list_roles(path_prefix=path_prefix, marker=marker) roles = roles + _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) return roles def get_all_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM user details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_users ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _users = conn.get_all_users(path_prefix=path_prefix) users = _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) while marker: _users = conn.get_all_users(path_prefix=path_prefix, marker=marker) users = users + _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) return users def get_all_user_policies(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all user policies. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_user_policies myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_all_user_policies(user_name, marker, max_items) if not info: return False _list = info.list_user_policies_response.list_user_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policies for user %s.', user_name) return False def get_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user_policy myuser mypolicyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user_policy(user_name, policy_name) log.debug('Info for IAM user %s policy %s: %s.', user_name, policy_name, info) if not info: return False info = info.get_user_policy_response.get_user_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policy %s for IAM user %s.', policy_name, user_name) return False def put_user_policy(user_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_user_policy myuser policyname policyrules ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_user_policy(user_name, policy_name, policy_json) if created: log.info('Created policy %s for IAM user %s.', policy_name, user_name) return True log.error('Could not create policy %s for IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy %s for IAM user %s.', policy_name, user_name) return False def delete_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user_policy myuser mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_user_policy( user_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_user_policy(user_name, policy_name) log.info('Successfully deleted policy %s for IAM user %s.', policy_name, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM user %s.', policy_name, user_name) return False def upload_server_cert(cert_name, cert_body, private_key, cert_chain=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Upload a certificate to Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.upload_server_cert mycert_name crt priv_key :param cert_name: The name for the server certificate. Do not include the path in this value. :param cert_body: The contents of the public key certificate in PEM-encoded format. :param private_key: The contents of the private key in PEM-encoded format. :param cert_chain: The contents of the certificate chain. This is typically a concatenation of the PEM-encoded public key certificates of the chain. :param path: The path for the server certificate. :param region: The name of the region to connect to. :param key: The key to be used in order to connect :param keyid: The keyid to be used in order to connect :param profile: The profile that contains a dict of region, key, keyid :return: True / False ''' exists = get_server_certificate(cert_name, region, key, keyid, profile) if exists: return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.upload_server_cert(cert_name, cert_body, private_key, cert_chain) log.info('Created certificate %s.', cert_name) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to failed to create certificate %s.', cert_name) return False def list_server_certificates(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Lists the server certificates stored in IAM that have the specified path prefix. .. versionadded:: ??? :param path_prefix: The path prefix for filtering the results. For example: /company/servercerts would get all server certificates for which the path starts with /company/servercerts . This parameter is optional. If it is not included, it defaults to a slash (/), listing all server certificates. This parameter allows (per its regex pattern) a string of characters consisting of either a forward slash (/) by itself or a string that must begin and end with forward slashes. In addition, it can contain any ASCII character from the ! (u0021) through the DEL character (u007F), including most punctuation characters, digits, and upper and lowercased letters. CLI Example: .. code-block:: bash salt myminion boto_iam.list_server_certificates path_prefix=/somepath/ ''' retries = 10 sleep = 6 conn = __utils__['boto3.get_connection']('iam', region=region, key=key, keyid=keyid, profile=profile) Items = [] while retries: try: log.debug('Garnering list of IAM Server Certificates') IsTruncated = True while IsTruncated: kwargs = {'PathPrefix': path_prefix} ret = conn.list_server_certificates(**kwargs) Items += ret.get('ServerCertificateMetadataList', []) IsTruncated = ret.get('IsTruncated') kwargs.update({'Marker': ret.get('Marker')}) return Items except botocore.exceptions.ParamValidationError as err: raise SaltInvocationError(str(err)) except botocore.exceptions.ClientError as err: if retries and jmespath.search('Error.Code', err.response) == 'Throttling': retries -= 1 log.debug('Throttled by AWS API, retrying in %s seconds...', sleep) time.sleep(sleep) continue log.error('Failed to list IAM Server Certificates: %s', err.message) return None def get_server_certificate(cert_name, region=None, key=None, keyid=None, profile=None): ''' Returns certificate information from Amazon .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_server_certificate mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_server_certificate(cert_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get certificate %s information.', cert_name) return False def delete_server_cert(cert_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a certificate from Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_server_cert mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_server_cert(cert_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete certificate %s.', cert_name) return False def export_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM user details. Produces results that can be used to create an sls file. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.export_users --out=txt | sed "s/local: //" > iam_users.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() users = get_all_users(path_prefix, region, key, keyid, profile) for user in users: name = user.user_name _policies = conn.get_all_user_policies(name, max_items=100) _policies = _policies.list_user_policies_response.list_user_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_user_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_user_policy_response.get_user_policy_result.policy_document )) policies[policy_name] = _policy user_sls = [] user_sls.append({"name": name}) user_sls.append({"policies": policies}) user_sls.append({"path": user.path}) results["manage user " + name] = {"boto_iam.user_present": user_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def export_roles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM role details. Produces results that can be used to create an sls file. CLI Example: salt-call boto_iam.export_roles --out=txt | sed "s/local: //" > iam_roles.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() roles = get_all_roles(path_prefix, region, key, keyid, profile) for role in roles: name = role.role_name _policies = conn.list_role_policies(name, max_items=100) _policies = _policies.list_role_policies_response.list_role_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_role_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_role_policy_response.get_role_policy_result.policy_document )) policies[policy_name] = _policy role_sls = [] role_sls.append({"name": name}) role_sls.append({"policies": policies}) role_sls.append({'policy_document': salt.utils.json.loads(_unquote(role.assume_role_policy_document))}) role_sls.append({"path": role.path}) results["manage role " + name] = {"boto_iam_role.present": role_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def _get_policy_arn(name, region=None, key=None, keyid=None, profile=None): if name.startswith('arn:aws:iam:'): return name account_id = get_account_id( region=region, key=key, keyid=keyid, profile=profile ) return 'arn:aws:iam::{0}:policy/{1}'.format(account_id, name) def policy_exists(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return True except boto.exception.BotoServerError: return False def get_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return ret.get('get_policy_response', {}).get('get_policy_result', {}) except boto.exception.BotoServerError: return None def create_policy(policy_name, policy_document, path=None, description=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in 'path', 'description': if locals()[arg] is not None: params[arg] = locals()[arg] if policy_exists(policy_name, region, key, keyid, profile): return True try: conn.create_policy(policy_name, policy_document, **params) log.info('Created IAM policy %s.', policy_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s.', policy_name) return False return True def delete_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_exists(policy_arn, region, key, keyid, profile): return True try: conn.delete_policy(policy_arn) log.info('Deleted %s policy.', policy_name) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete %s policy: %s.', policy_name, aws.get('message')) return False return True def list_policies(region=None, key=None, keyid=None, profile=None): ''' List policies. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policies ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: policies = [] for ret in __utils__['boto.paged_call'](conn.list_policies): policies.append(ret.get('list_policies_response', {}).get('list_policies_result', {}).get('policies')) return policies except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to list policy versions.' log.error(msg) return [] def policy_version_exists(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.get_policy_version(policy_arn, version_id) return True except boto.exception.BotoServerError: return False def get_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy_version(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile), version_id) retval = ret.get('get_policy_version_response', {}).get('get_policy_version_result', {}).get('policy_version', {}) retval['document'] = _unquote(retval.get('document')) return {'policy_version': retval} except boto.exception.BotoServerError: return None def create_policy_version(policy_name, policy_document, set_as_default=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy version. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy_version mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in ('set_as_default',): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.create_policy_version(policy_arn, policy_document, **params) vid = ret.get('create_policy_version_response', {}).get('create_policy_version_result', {}).get('policy_version', {}).get('version_id') log.info('Created IAM policy %s version %s.', policy_name, vid) return {'created': True, 'version_id': vid} except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s version %s.', policy_name, vid) return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Delete a policy version. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_version_exists(policy_arn, version_id, region, key, keyid, profile): return True try: conn.delete_policy_version(policy_arn, version_id) log.info('Deleted IAM policy %s version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete IAM policy %s version %s: %s', policy_name, version_id, aws.get('message')) return False return True def list_policy_versions(policy_name, region=None, key=None, keyid=None, profile=None): ''' List versions of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policy_versions mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.list_policy_versions(policy_arn) return ret.get('list_policy_versions_response', {}).get('list_policy_versions_result', {}).get('versions') except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list versions for IAM policy %s.', policy_name) return [] def set_default_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Set the default version of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.set_default_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.set_default_policy_version(policy_arn, version_id) log.info('Set %s policy to version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to set %s policy to version %s: %s', policy_name, version_id, aws.get('message')) return False return True def attach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_user_policy(policy_arn, user_name) log.info('Attached policy %s to IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach %s policy to IAM user %s.', policy_name, user_name) return False return True def detach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_user_policy(policy_arn, user_name) log.info('Detached %s policy from IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach %s policy from IAM user %s.', policy_name, user_name) return False return True def attach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_group_policy(policy_arn, group_name) log.info('Attached policy %s to IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM group %s.', policy_name, group_name) return False return True def detach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_group_policy(policy_arn, group_name) log.info('Detached policy %s from IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM group %s.', policy_name, group_name) return False return True def attach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_role_policy(policy_arn, role_name) log.info('Attached policy %s to IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM role %s.', policy_name, role_name) return False return True def detach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_role_policy(policy_arn, role_name) log.info('Detached policy %s from IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM role %s.', policy_name, role_name) return False return True def list_entities_for_policy(policy_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities that a policy is attached to. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 params = {} for arg in ('path_prefix', 'entity_filter'): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) while retries: try: allret = { 'policy_groups': [], 'policy_users': [], 'policy_roles': [], } for ret in __utils__['boto.paged_call'](conn.list_entities_for_policy, policy_arn=policy_arn, **params): for k, v in six.iteritems(allret): v.extend(ret.get('list_entities_for_policy_response', {}).get('list_entities_for_policy_result', {}).get(k)) return allret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('Failed to list entities for IAM policy %s: %s', policy_name, e.message) return {} return {} def list_attached_user_policies(user_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given user. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'UserName': user_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedUserPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_user_policies_response', {}).get('list_attached_user_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM user %s.', user_name) return [] def list_attached_group_policies(group_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given group. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'GroupName': group_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedGroupPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_group_policies_response', {}).get('list_attached_group_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM group %s.', group_name) return [] def list_attached_role_policies(role_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'RoleName': role_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedRolePolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_role_policies_response', {}).get('list_attached_role_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM role %s.', role_name) return [] def create_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Create SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.create_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_saml_provider(saml_metadata_document, name) log.info('Successfully created %s SAML provider.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to create SAML provider %s.', name) return False def get_saml_provider_arn(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider_arn my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_saml_providers() for saml_provider in response.list_saml_providers_response.list_saml_providers_result.saml_provider_list: if saml_provider['arn'].endswith(':saml-provider/' + name): return saml_provider['arn'] return False except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to get ARN of SAML provider %s.', name) return False def delete_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Delete SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.delete_saml_provider my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return True conn.delete_saml_provider(saml_provider_arn) log.info('Successfully deleted SAML provider %s.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete SAML provider %s.', name) return False def list_saml_providers(region=None, key=None, keyid=None, profile=None): ''' List SAML providers. CLI Example: .. code-block:: bash salt myminion boto_iam.list_saml_providers ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: providers = [] info = conn.list_saml_providers() for arn in info['list_saml_providers_response']['list_saml_providers_result']['saml_provider_list']: providers.append(arn['arn'].rsplit('/', 1)[1]) return providers except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get list of SAML providers.') return False def get_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider document. CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider arn ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: provider = conn.get_saml_provider(name) return provider['get_saml_provider_response']['get_saml_provider_result']['saml_metadata_document'] except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get SAML provider document %s.', name) return False def update_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Update SAML provider. CLI Example: .. code-block:: bash salt myminion boto_iam.update_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return False if conn.update_saml_provider(name, saml_metadata_document): return True return False except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to update SAML provider %s.', name) return False
saltstack/salt
salt/modules/boto_iam.py
role_exists
python
def role_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an IAM role exists. CLI Example: .. code-block:: bash salt myminion boto_iam.role_exists myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_role(name) return True except boto.exception.BotoServerError: return False
Check to see if an IAM role exists. CLI Example: .. code-block:: bash salt myminion boto_iam.role_exists myirole
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iam.py#L160-L175
null
# -*- coding: utf-8 -*- ''' Connection module for Amazon IAM .. versionadded:: 2014.7.0 :configuration: This module accepts explicit iam 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 iam.keyid: GKTADJGHEIQSXMKKRBJ08H iam.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs iam.region: 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: boto ''' # keep lint from choking on _get_conn and _cache_id #pylint: disable=E0602 # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import salt libs from salt.ext import six import salt.utils.compat import salt.utils.json import salt.utils.odict as odict import salt.utils.versions from salt.exceptions import SaltInvocationError # Import third party libs # pylint: disable=unused-import from salt.ext.six.moves.urllib.parse import unquote as _unquote # pylint: disable=no-name-in-module try: import boto import boto.iam import boto3 import botocore logging.getLogger('boto').setLevel(logging.CRITICAL) logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=unused-import log = logging.getLogger(__name__) def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'iam', pack=__salt__) def instance_profile_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an instance profile exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: # Boto weirdly returns an exception here if an instance profile doesn't # exist. conn.get_instance_profile(name) return True except boto.exception.BotoServerError: return False def create_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Create an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.create_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if instance_profile_exists(name, region, key, keyid, profile): return True try: # This call returns an instance profile if successful and an exception # if not. It's annoying. conn.create_instance_profile(name) log.info('Created %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create %s instance profile.', name) return False return True def delete_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Delete an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not instance_profile_exists(name, region, key, keyid, profile): return True try: conn.delete_instance_profile(name) log.info('Deleted %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s instance profile.', name) return False return True def describe_role(name, region=None, key=None, keyid=None, profile=None): ''' Get information for a role. CLI Example: .. code-block:: bash salt myminion boto_iam.describe_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_role(name) if not info: return False role = info.get_role_response.get_role_result.role role['assume_role_policy_document'] = salt.utils.json.loads(_unquote( role.assume_role_policy_document )) # If Sid wasn't defined by the user, boto will still return a Sid in # each policy. To properly check idempotently, let's remove the Sid # from the return if it's not actually set. for policy_key, policy in role['assume_role_policy_document'].items(): if policy_key == 'Statement': for val in policy: if 'Sid' in val and not val['Sid']: del val['Sid'] return role except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get %s information.', name) return False def create_user(user_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_user myuser ''' if not path: path = '/' if get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_user(user_name, path) log.info('Created IAM user : %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM user %s.', user_name) return False def get_all_access_keys(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all access keys from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_access_keys myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.get_all_access_keys(user_name, marker, max_items) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get access keys for IAM user %s.', user_name) return six.text_type(e) def create_access_key(user_name, region=None, key=None, keyid=None, profile=None): ''' Create access key id for a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.create_access_key(user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create access key.') return six.text_type(e) def delete_access_key(access_key_id, user_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete access key id from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_access_key(access_key_id, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete access key id %s.', access_key_id) return six.text_type(e) def delete_user(user_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user myuser ''' if not get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.delete_user(user_name) log.info('Deleted IAM user : %s .', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM user %s', user_name) return six.text_type(e) def get_user(user_name=None, region=None, key=None, keyid=None, profile=None): ''' Get user information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user(user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM user %s info.', user_name) return False def create_group(group_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_group group ''' if not path: path = '/' if get_group(group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_group(group_name, path) log.info('Created IAM group : %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM group %s.', group_name) return False def get_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group(group_name, max_items=1) if not info: return False return info['get_group_response']['get_group_result']['group'] except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_group_members(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: marker = None truncated = True users = [] while truncated: info = conn.get_group(group_name, marker=marker, max_items=1000) if not info: return False truncated = bool(info['get_group_response']['get_group_result']['is_truncated']) if truncated and 'marker' in info['get_group_response']['get_group_result']: marker = info['get_group_response']['get_group_result']['marker'] else: marker = None truncated = False users += info['get_group_response']['get_group_result']['users'] return users except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get members for IAM group %s.', group_name) return False def add_user_to_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Add user to group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.add_user_to_group myuser mygroup ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('Username : %s does not exist.', user_name) return False if user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.add_user_to_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add IAM user %s to group %s.', user_name, group_name) return False def user_exists_in_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Check if user exists in group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.user_exists_in_group myuser mygroup ''' # TODO this should probably use boto.iam.get_groups_for_user users = get_group_members( group_name=group_name, region=region, key=key, keyid=keyid, profile=profile ) if users: for _user in users: if user_name == _user['user_name']: log.debug('IAM user %s is already in IAM group %s.', user_name, group_name) return True return False def remove_user_from_group(group_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Remove user from group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.remove_user_from_group mygroup myuser ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist.', user_name) return False if not user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.remove_user_from_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove IAM user %s from group %s', user_name, group_name) return False def put_group_policy(group_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_group_policy mygroup policyname policyrules ''' group = get_group(group_name, region=region, key=key, keyid=keyid, profile=profile) if not group: log.error('Group %s does not exist', group_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_group_policy(group_name, policy_name, policy_json) if created: log.info('Created policy for IAM group %s.', group_name) return True log.error('Could not create policy for IAM group %s', group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy for IAM group %s', group_name) return False def delete_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group_policy mygroup mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_group_policy( group_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_group_policy(group_name, policy_name) log.info('Successfully deleted policy %s for IAM group %s.', policy_name, group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM group %s.', policy_name, group_name) return False def get_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group_policy mygroup policyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group_policy(group_name, policy_name) log.debug('info for group policy is : %s', info) if not info: return False info = info.get_group_policy_response.get_group_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_all_groups(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM group details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_groups ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _groups = conn.get_all_groups(path_prefix=path_prefix) groups = _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) while marker: _groups = conn.get_all_groups(path_prefix=path_prefix, marker=marker) groups = groups + _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) return groups def get_all_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.get_all_instance_profiles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) marker = False profiles = [] while marker is not None: marker = marker if marker else None p = conn.list_instance_profiles(path_prefix=path_prefix, marker=marker) res = p.list_instance_profiles_response.list_instance_profiles_result profiles += res.instance_profiles marker = getattr(res, 'marker', None) return profiles def list_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' List all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.list_instance_profiles ''' p = get_all_instance_profiles(path_prefix, region, key, keyid, profile) return [i['instance_profile_name'] for i in p] def get_all_group_policies(group_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a group. CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_group_policies mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False try: response = conn.get_all_group_policies(group_name) _list = response.list_group_policies_response.list_group_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def delete_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _group = get_group( group_name, region, key, keyid, profile ) if not _group: return True try: conn.delete_group(group_name) log.info('Successfully deleted IAM group %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM group %s.', group_name) return False def create_login_profile(user_name, password, region=None, key=None, keyid=None, profile=None): ''' Creates a login profile for the specified user, give the user the ability to access AWS services and the AWS Management Console. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_login_profile user_name password ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.create_login_profile(user_name, password) log.info('Created profile for IAM user %s.', user_name) return info except boto.exception.BotoServerError as e: log.debug(e) if 'Conflict' in e: log.info('Profile already exists for IAM user %s.', user_name) return 'Conflict' log.error('Failed to update profile for IAM user %s.', user_name) return False def delete_login_profile(user_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a login profile for the specified user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_login_profile user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.delete_login_profile(user_name) log.info('Deleted login profile for IAM user %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Login profile already deleted for IAM user %s.', user_name) return True log.error('Failed to delete login profile for IAM user %s.', user_name) return False def get_all_mfa_devices(user_name, region=None, key=None, keyid=None, profile=None): ''' Get all MFA devices associated with an IAM user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_mfa_devices user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: result = conn.get_all_mfa_devices(user_name) devices = result['list_mfa_devices_response']['list_mfa_devices_result']['mfa_devices'] return devices except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Could not find IAM user %s.', user_name) return [] log.error('Failed to get all MFA devices for IAM user %s.', user_name) return False def deactivate_mfa_device(user_name, serial, region=None, key=None, keyid=None, profile=None): ''' Deactivates the specified MFA device and removes it from association with the user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.deactivate_mfa_device user_name serial_num ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.deactivate_mfa_device(user_name, serial) log.info('Deactivated MFA device %s for IAM user %s.', serial, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('MFA device %s not associated with IAM user %s.', serial, user_name) return True log.error('Failed to deactivate MFA device %s for IAM user %s.', serial, user_name) return False def delete_virtual_mfa_device(serial, region=None, key=None, keyid=None, profile=None): ''' Deletes the specified virtual MFA device. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_virtual_mfa_device serial_num ''' conn = __utils__['boto3.get_connection_func']('iam')() try: conn.delete_virtual_mfa_device(SerialNumber=serial) log.info('Deleted virtual MFA device %s.', serial) return True except botocore.exceptions.ClientError as e: log.debug(e) if 'NoSuchEntity' in six.text_type(e): log.info('Virtual MFA device %s not found.', serial) return True log.error('Failed to delete virtual MFA device %s.', serial) return False def update_account_password_policy(allow_users_to_change_password=None, hard_expiry=None, max_password_age=None, minimum_password_length=None, password_reuse_prevention=None, require_lowercase_characters=None, require_numbers=None, require_symbols=None, require_uppercase_characters=None, region=None, key=None, keyid=None, profile=None): ''' Update the password policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_account_password_policy True ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.update_account_password_policy(allow_users_to_change_password, hard_expiry, max_password_age, minimum_password_length, password_reuse_prevention, require_lowercase_characters, require_numbers, require_symbols, require_uppercase_characters) log.info('The password policy has been updated.') return True except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy' log.error(msg) return False def get_account_policy(region=None, key=None, keyid=None, profile=None): ''' Get account policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_account_password_policy() return info.get_account_password_policy_response.get_account_password_policy_result.password_policy except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy.' log.error(msg) return False def create_role(name, policy_document=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Create an instance role. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if role_exists(name, region, key, keyid, profile): return True if not policy_document: policy_document = None try: conn.create_role(name, assume_role_policy_document=policy_document, path=path) log.info('Created IAM role %s.', name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to create IAM role %s.', name) return False def delete_role(name, region=None, key=None, keyid=None, profile=None): ''' Delete an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(name, region, key, keyid, profile): return True try: conn.delete_role(name) log.info('Deleted %s IAM role.', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s IAM role.', name) return False def profile_associated(role_name, profile_name, region, key, keyid, profile): ''' Check to see if an instance profile is associated with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.profile_associated myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # The IAM module of boto doesn't return objects. Instead you need to grab # values through its properties. Sigh. try: profiles = conn.list_instance_profiles_for_role(role_name) except boto.exception.BotoServerError as e: log.debug(e) return False profiles = profiles.list_instance_profiles_for_role_response profiles = profiles.list_instance_profiles_for_role_result profiles = profiles.instance_profiles for profile in profiles: if profile.instance_profile_name == profile_name: return True return False def associate_profile_to_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Associate an instance profile with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.associate_profile_to_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if associated: return True else: try: conn.add_role_to_instance_profile(profile_name, role_name) log.info('Added %s instance profile to IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add %s instance profile to IAM role %s', profile_name, role_name) return False def disassociate_profile_from_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Disassociate an instance profile from an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.disassociate_profile_from_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if not associated: return True else: try: conn.remove_role_from_instance_profile(profile_name, role_name) log.info('Removed %s instance profile from IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove %s instance profile from IAM role %s.', profile_name, role_name) return False def list_role_policies(role_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_role_policies myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_role_policies(role_name) _list = response.list_role_policies_response.list_role_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def get_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.get_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: _policy = conn.get_role_policy(role_name, policy_name) # I _hate_ you for not giving me an object boto. _policy = _policy.get_role_policy_response.policy_document # Policy is url encoded _policy = _unquote(_policy) _policy = salt.utils.json.loads(_policy, object_pairs_hook=odict.OrderedDict) return _policy except boto.exception.BotoServerError: return {} def create_role_policy(role_name, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Create or modify a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role_policy myirole mypolicy '{"MyPolicy": "Statement": [{"Action": ["sqs:*"], "Effect": "Allow", "Resource": ["arn:aws:sqs:*:*:*"], "Sid": "MyPolicySqs1"}]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) mode = 'create' if _policy: if _policy == policy: return True mode = 'modify' if isinstance(policy, six.string_types): policy = salt.utils.json.loads(policy, object_pairs_hook=odict.OrderedDict) try: _policy = salt.utils.json.dumps(policy) conn.put_role_policy(role_name, policy_name, _policy) if mode == 'create': msg = 'Successfully added policy %s to IAM role %s.' else: msg = 'Successfully modified policy %s for IAM role %s.' log.info(msg, policy_name, role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to %s policy %s for IAM role %s.', mode, policy_name, role_name) return False def delete_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) if not _policy: return True try: conn.delete_role_policy(role_name, policy_name) log.info('Successfully deleted policy %s for IAM role %s.', policy_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM role %s.', policy_name, role_name) return False def update_assume_role_policy(role_name, policy_document, region=None, key=None, keyid=None, profile=None): ''' Update an assume role policy for a role. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_assume_role_policy myrole '{"Statement":"..."}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(policy_document, six.string_types): policy_document = salt.utils.json.loads(policy_document, object_pairs_hook=odict.OrderedDict) try: _policy_document = salt.utils.json.dumps(policy_document) conn.update_assume_role_policy(role_name, _policy_document) log.info('Successfully updated assume role policy for IAM role %s.', role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to update assume role policy for IAM role %s.', role_name) return False def build_policy(region=None, key=None, keyid=None, profile=None): ''' Build a default assume role policy. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.build_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if hasattr(conn, 'build_policy'): policy = salt.utils.json.loads(conn.build_policy()) elif hasattr(conn, '_build_policy'): policy = salt.utils.json.loads(conn._build_policy()) else: return {} # The format we get from build_policy isn't going to be what we get back # from AWS for the exact same policy. AWS converts single item list values # into strings, so let's do the same here. for key, policy_val in policy.items(): for statement in policy_val: if (isinstance(statement['Action'], list) and len(statement['Action']) == 1): statement['Action'] = statement['Action'][0] if (isinstance(statement['Principal']['Service'], list) and len(statement['Principal']['Service']) == 1): statement['Principal']['Service'] = statement['Principal']['Service'][0] # build_policy doesn't add a version field, which AWS is going to set to a # default value, when we get it back, so let's set it. policy['Version'] = '2008-10-17' return policy def get_account_id(region=None, key=None, keyid=None, profile=None): ''' Get a the AWS account id associated with the used credentials. CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_id ''' cache_key = 'boto_iam.account_id' if cache_key not in __context__: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_user() # The get_user call returns an user ARN: # arn:aws:iam::027050522557:user/salt-test arn = ret['get_user_response']['get_user_result']['user']['arn'] account_id = arn.split(':')[4] except boto.exception.BotoServerError: # If call failed, then let's try to get the ARN from the metadata timeout = boto.config.getfloat( 'Boto', 'metadata_service_timeout', 1.0 ) attempts = boto.config.getint( 'Boto', 'metadata_service_num_attempts', 1 ) identity = boto.utils.get_instance_identity( timeout=timeout, num_retries=attempts ) try: account_id = identity['document']['accountId'] except KeyError: log.error('Failed to get account id from instance_identity in' ' boto_iam.get_account_id.') __context__[cache_key] = account_id return __context__[cache_key] def get_all_roles(path_prefix=None, region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM role details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_roles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _roles = conn.list_roles(path_prefix=path_prefix) roles = _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) while marker: _roles = conn.list_roles(path_prefix=path_prefix, marker=marker) roles = roles + _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) return roles def get_all_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM user details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_users ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _users = conn.get_all_users(path_prefix=path_prefix) users = _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) while marker: _users = conn.get_all_users(path_prefix=path_prefix, marker=marker) users = users + _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) return users def get_all_user_policies(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all user policies. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_user_policies myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_all_user_policies(user_name, marker, max_items) if not info: return False _list = info.list_user_policies_response.list_user_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policies for user %s.', user_name) return False def get_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user_policy myuser mypolicyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user_policy(user_name, policy_name) log.debug('Info for IAM user %s policy %s: %s.', user_name, policy_name, info) if not info: return False info = info.get_user_policy_response.get_user_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policy %s for IAM user %s.', policy_name, user_name) return False def put_user_policy(user_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_user_policy myuser policyname policyrules ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_user_policy(user_name, policy_name, policy_json) if created: log.info('Created policy %s for IAM user %s.', policy_name, user_name) return True log.error('Could not create policy %s for IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy %s for IAM user %s.', policy_name, user_name) return False def delete_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user_policy myuser mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_user_policy( user_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_user_policy(user_name, policy_name) log.info('Successfully deleted policy %s for IAM user %s.', policy_name, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM user %s.', policy_name, user_name) return False def upload_server_cert(cert_name, cert_body, private_key, cert_chain=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Upload a certificate to Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.upload_server_cert mycert_name crt priv_key :param cert_name: The name for the server certificate. Do not include the path in this value. :param cert_body: The contents of the public key certificate in PEM-encoded format. :param private_key: The contents of the private key in PEM-encoded format. :param cert_chain: The contents of the certificate chain. This is typically a concatenation of the PEM-encoded public key certificates of the chain. :param path: The path for the server certificate. :param region: The name of the region to connect to. :param key: The key to be used in order to connect :param keyid: The keyid to be used in order to connect :param profile: The profile that contains a dict of region, key, keyid :return: True / False ''' exists = get_server_certificate(cert_name, region, key, keyid, profile) if exists: return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.upload_server_cert(cert_name, cert_body, private_key, cert_chain) log.info('Created certificate %s.', cert_name) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to failed to create certificate %s.', cert_name) return False def list_server_certificates(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Lists the server certificates stored in IAM that have the specified path prefix. .. versionadded:: ??? :param path_prefix: The path prefix for filtering the results. For example: /company/servercerts would get all server certificates for which the path starts with /company/servercerts . This parameter is optional. If it is not included, it defaults to a slash (/), listing all server certificates. This parameter allows (per its regex pattern) a string of characters consisting of either a forward slash (/) by itself or a string that must begin and end with forward slashes. In addition, it can contain any ASCII character from the ! (u0021) through the DEL character (u007F), including most punctuation characters, digits, and upper and lowercased letters. CLI Example: .. code-block:: bash salt myminion boto_iam.list_server_certificates path_prefix=/somepath/ ''' retries = 10 sleep = 6 conn = __utils__['boto3.get_connection']('iam', region=region, key=key, keyid=keyid, profile=profile) Items = [] while retries: try: log.debug('Garnering list of IAM Server Certificates') IsTruncated = True while IsTruncated: kwargs = {'PathPrefix': path_prefix} ret = conn.list_server_certificates(**kwargs) Items += ret.get('ServerCertificateMetadataList', []) IsTruncated = ret.get('IsTruncated') kwargs.update({'Marker': ret.get('Marker')}) return Items except botocore.exceptions.ParamValidationError as err: raise SaltInvocationError(str(err)) except botocore.exceptions.ClientError as err: if retries and jmespath.search('Error.Code', err.response) == 'Throttling': retries -= 1 log.debug('Throttled by AWS API, retrying in %s seconds...', sleep) time.sleep(sleep) continue log.error('Failed to list IAM Server Certificates: %s', err.message) return None def get_server_certificate(cert_name, region=None, key=None, keyid=None, profile=None): ''' Returns certificate information from Amazon .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_server_certificate mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_server_certificate(cert_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get certificate %s information.', cert_name) return False def delete_server_cert(cert_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a certificate from Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_server_cert mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_server_cert(cert_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete certificate %s.', cert_name) return False def export_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM user details. Produces results that can be used to create an sls file. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.export_users --out=txt | sed "s/local: //" > iam_users.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() users = get_all_users(path_prefix, region, key, keyid, profile) for user in users: name = user.user_name _policies = conn.get_all_user_policies(name, max_items=100) _policies = _policies.list_user_policies_response.list_user_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_user_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_user_policy_response.get_user_policy_result.policy_document )) policies[policy_name] = _policy user_sls = [] user_sls.append({"name": name}) user_sls.append({"policies": policies}) user_sls.append({"path": user.path}) results["manage user " + name] = {"boto_iam.user_present": user_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def export_roles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM role details. Produces results that can be used to create an sls file. CLI Example: salt-call boto_iam.export_roles --out=txt | sed "s/local: //" > iam_roles.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() roles = get_all_roles(path_prefix, region, key, keyid, profile) for role in roles: name = role.role_name _policies = conn.list_role_policies(name, max_items=100) _policies = _policies.list_role_policies_response.list_role_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_role_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_role_policy_response.get_role_policy_result.policy_document )) policies[policy_name] = _policy role_sls = [] role_sls.append({"name": name}) role_sls.append({"policies": policies}) role_sls.append({'policy_document': salt.utils.json.loads(_unquote(role.assume_role_policy_document))}) role_sls.append({"path": role.path}) results["manage role " + name] = {"boto_iam_role.present": role_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def _get_policy_arn(name, region=None, key=None, keyid=None, profile=None): if name.startswith('arn:aws:iam:'): return name account_id = get_account_id( region=region, key=key, keyid=keyid, profile=profile ) return 'arn:aws:iam::{0}:policy/{1}'.format(account_id, name) def policy_exists(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return True except boto.exception.BotoServerError: return False def get_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return ret.get('get_policy_response', {}).get('get_policy_result', {}) except boto.exception.BotoServerError: return None def create_policy(policy_name, policy_document, path=None, description=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in 'path', 'description': if locals()[arg] is not None: params[arg] = locals()[arg] if policy_exists(policy_name, region, key, keyid, profile): return True try: conn.create_policy(policy_name, policy_document, **params) log.info('Created IAM policy %s.', policy_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s.', policy_name) return False return True def delete_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_exists(policy_arn, region, key, keyid, profile): return True try: conn.delete_policy(policy_arn) log.info('Deleted %s policy.', policy_name) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete %s policy: %s.', policy_name, aws.get('message')) return False return True def list_policies(region=None, key=None, keyid=None, profile=None): ''' List policies. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policies ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: policies = [] for ret in __utils__['boto.paged_call'](conn.list_policies): policies.append(ret.get('list_policies_response', {}).get('list_policies_result', {}).get('policies')) return policies except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to list policy versions.' log.error(msg) return [] def policy_version_exists(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.get_policy_version(policy_arn, version_id) return True except boto.exception.BotoServerError: return False def get_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy_version(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile), version_id) retval = ret.get('get_policy_version_response', {}).get('get_policy_version_result', {}).get('policy_version', {}) retval['document'] = _unquote(retval.get('document')) return {'policy_version': retval} except boto.exception.BotoServerError: return None def create_policy_version(policy_name, policy_document, set_as_default=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy version. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy_version mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in ('set_as_default',): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.create_policy_version(policy_arn, policy_document, **params) vid = ret.get('create_policy_version_response', {}).get('create_policy_version_result', {}).get('policy_version', {}).get('version_id') log.info('Created IAM policy %s version %s.', policy_name, vid) return {'created': True, 'version_id': vid} except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s version %s.', policy_name, vid) return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Delete a policy version. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_version_exists(policy_arn, version_id, region, key, keyid, profile): return True try: conn.delete_policy_version(policy_arn, version_id) log.info('Deleted IAM policy %s version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete IAM policy %s version %s: %s', policy_name, version_id, aws.get('message')) return False return True def list_policy_versions(policy_name, region=None, key=None, keyid=None, profile=None): ''' List versions of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policy_versions mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.list_policy_versions(policy_arn) return ret.get('list_policy_versions_response', {}).get('list_policy_versions_result', {}).get('versions') except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list versions for IAM policy %s.', policy_name) return [] def set_default_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Set the default version of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.set_default_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.set_default_policy_version(policy_arn, version_id) log.info('Set %s policy to version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to set %s policy to version %s: %s', policy_name, version_id, aws.get('message')) return False return True def attach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_user_policy(policy_arn, user_name) log.info('Attached policy %s to IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach %s policy to IAM user %s.', policy_name, user_name) return False return True def detach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_user_policy(policy_arn, user_name) log.info('Detached %s policy from IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach %s policy from IAM user %s.', policy_name, user_name) return False return True def attach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_group_policy(policy_arn, group_name) log.info('Attached policy %s to IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM group %s.', policy_name, group_name) return False return True def detach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_group_policy(policy_arn, group_name) log.info('Detached policy %s from IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM group %s.', policy_name, group_name) return False return True def attach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_role_policy(policy_arn, role_name) log.info('Attached policy %s to IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM role %s.', policy_name, role_name) return False return True def detach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_role_policy(policy_arn, role_name) log.info('Detached policy %s from IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM role %s.', policy_name, role_name) return False return True def list_entities_for_policy(policy_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities that a policy is attached to. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 params = {} for arg in ('path_prefix', 'entity_filter'): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) while retries: try: allret = { 'policy_groups': [], 'policy_users': [], 'policy_roles': [], } for ret in __utils__['boto.paged_call'](conn.list_entities_for_policy, policy_arn=policy_arn, **params): for k, v in six.iteritems(allret): v.extend(ret.get('list_entities_for_policy_response', {}).get('list_entities_for_policy_result', {}).get(k)) return allret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('Failed to list entities for IAM policy %s: %s', policy_name, e.message) return {} return {} def list_attached_user_policies(user_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given user. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'UserName': user_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedUserPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_user_policies_response', {}).get('list_attached_user_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM user %s.', user_name) return [] def list_attached_group_policies(group_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given group. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'GroupName': group_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedGroupPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_group_policies_response', {}).get('list_attached_group_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM group %s.', group_name) return [] def list_attached_role_policies(role_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'RoleName': role_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedRolePolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_role_policies_response', {}).get('list_attached_role_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM role %s.', role_name) return [] def create_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Create SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.create_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_saml_provider(saml_metadata_document, name) log.info('Successfully created %s SAML provider.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to create SAML provider %s.', name) return False def get_saml_provider_arn(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider_arn my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_saml_providers() for saml_provider in response.list_saml_providers_response.list_saml_providers_result.saml_provider_list: if saml_provider['arn'].endswith(':saml-provider/' + name): return saml_provider['arn'] return False except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to get ARN of SAML provider %s.', name) return False def delete_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Delete SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.delete_saml_provider my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return True conn.delete_saml_provider(saml_provider_arn) log.info('Successfully deleted SAML provider %s.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete SAML provider %s.', name) return False def list_saml_providers(region=None, key=None, keyid=None, profile=None): ''' List SAML providers. CLI Example: .. code-block:: bash salt myminion boto_iam.list_saml_providers ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: providers = [] info = conn.list_saml_providers() for arn in info['list_saml_providers_response']['list_saml_providers_result']['saml_provider_list']: providers.append(arn['arn'].rsplit('/', 1)[1]) return providers except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get list of SAML providers.') return False def get_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider document. CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider arn ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: provider = conn.get_saml_provider(name) return provider['get_saml_provider_response']['get_saml_provider_result']['saml_metadata_document'] except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get SAML provider document %s.', name) return False def update_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Update SAML provider. CLI Example: .. code-block:: bash salt myminion boto_iam.update_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return False if conn.update_saml_provider(name, saml_metadata_document): return True return False except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to update SAML provider %s.', name) return False
saltstack/salt
salt/modules/boto_iam.py
describe_role
python
def describe_role(name, region=None, key=None, keyid=None, profile=None): ''' Get information for a role. CLI Example: .. code-block:: bash salt myminion boto_iam.describe_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_role(name) if not info: return False role = info.get_role_response.get_role_result.role role['assume_role_policy_document'] = salt.utils.json.loads(_unquote( role.assume_role_policy_document )) # If Sid wasn't defined by the user, boto will still return a Sid in # each policy. To properly check idempotently, let's remove the Sid # from the return if it's not actually set. for policy_key, policy in role['assume_role_policy_document'].items(): if policy_key == 'Statement': for val in policy: if 'Sid' in val and not val['Sid']: del val['Sid'] return role except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get %s information.', name) return False
Get information for a role. CLI Example: .. code-block:: bash salt myminion boto_iam.describe_role myirole
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iam.py#L178-L209
[ "def loads(s, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.loads and prevents a traceback in the event that a bytestring is\n passed to the function. (Python < 3.6 cannot load bytestrings)\n\n You can pass an alternate json module (loaded via import_json() above)\n using the _json_module argument)\n '''\n json_module = kwargs.pop('_json_module', json)\n try:\n return json_module.loads(s, **kwargs)\n except TypeError as exc:\n # json.loads cannot load bytestrings in Python < 3.6\n if six.PY3 and isinstance(s, bytes):\n return json_module.loads(salt.utils.stringutils.to_unicode(s), **kwargs)\n else:\n raise exc\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon IAM .. versionadded:: 2014.7.0 :configuration: This module accepts explicit iam 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 iam.keyid: GKTADJGHEIQSXMKKRBJ08H iam.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs iam.region: 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: boto ''' # keep lint from choking on _get_conn and _cache_id #pylint: disable=E0602 # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import salt libs from salt.ext import six import salt.utils.compat import salt.utils.json import salt.utils.odict as odict import salt.utils.versions from salt.exceptions import SaltInvocationError # Import third party libs # pylint: disable=unused-import from salt.ext.six.moves.urllib.parse import unquote as _unquote # pylint: disable=no-name-in-module try: import boto import boto.iam import boto3 import botocore logging.getLogger('boto').setLevel(logging.CRITICAL) logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=unused-import log = logging.getLogger(__name__) def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'iam', pack=__salt__) def instance_profile_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an instance profile exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: # Boto weirdly returns an exception here if an instance profile doesn't # exist. conn.get_instance_profile(name) return True except boto.exception.BotoServerError: return False def create_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Create an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.create_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if instance_profile_exists(name, region, key, keyid, profile): return True try: # This call returns an instance profile if successful and an exception # if not. It's annoying. conn.create_instance_profile(name) log.info('Created %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create %s instance profile.', name) return False return True def delete_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Delete an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not instance_profile_exists(name, region, key, keyid, profile): return True try: conn.delete_instance_profile(name) log.info('Deleted %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s instance profile.', name) return False return True def role_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an IAM role exists. CLI Example: .. code-block:: bash salt myminion boto_iam.role_exists myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_role(name) return True except boto.exception.BotoServerError: return False def create_user(user_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_user myuser ''' if not path: path = '/' if get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_user(user_name, path) log.info('Created IAM user : %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM user %s.', user_name) return False def get_all_access_keys(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all access keys from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_access_keys myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.get_all_access_keys(user_name, marker, max_items) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get access keys for IAM user %s.', user_name) return six.text_type(e) def create_access_key(user_name, region=None, key=None, keyid=None, profile=None): ''' Create access key id for a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.create_access_key(user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create access key.') return six.text_type(e) def delete_access_key(access_key_id, user_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete access key id from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_access_key(access_key_id, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete access key id %s.', access_key_id) return six.text_type(e) def delete_user(user_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user myuser ''' if not get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.delete_user(user_name) log.info('Deleted IAM user : %s .', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM user %s', user_name) return six.text_type(e) def get_user(user_name=None, region=None, key=None, keyid=None, profile=None): ''' Get user information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user(user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM user %s info.', user_name) return False def create_group(group_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_group group ''' if not path: path = '/' if get_group(group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_group(group_name, path) log.info('Created IAM group : %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM group %s.', group_name) return False def get_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group(group_name, max_items=1) if not info: return False return info['get_group_response']['get_group_result']['group'] except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_group_members(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: marker = None truncated = True users = [] while truncated: info = conn.get_group(group_name, marker=marker, max_items=1000) if not info: return False truncated = bool(info['get_group_response']['get_group_result']['is_truncated']) if truncated and 'marker' in info['get_group_response']['get_group_result']: marker = info['get_group_response']['get_group_result']['marker'] else: marker = None truncated = False users += info['get_group_response']['get_group_result']['users'] return users except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get members for IAM group %s.', group_name) return False def add_user_to_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Add user to group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.add_user_to_group myuser mygroup ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('Username : %s does not exist.', user_name) return False if user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.add_user_to_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add IAM user %s to group %s.', user_name, group_name) return False def user_exists_in_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Check if user exists in group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.user_exists_in_group myuser mygroup ''' # TODO this should probably use boto.iam.get_groups_for_user users = get_group_members( group_name=group_name, region=region, key=key, keyid=keyid, profile=profile ) if users: for _user in users: if user_name == _user['user_name']: log.debug('IAM user %s is already in IAM group %s.', user_name, group_name) return True return False def remove_user_from_group(group_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Remove user from group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.remove_user_from_group mygroup myuser ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist.', user_name) return False if not user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.remove_user_from_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove IAM user %s from group %s', user_name, group_name) return False def put_group_policy(group_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_group_policy mygroup policyname policyrules ''' group = get_group(group_name, region=region, key=key, keyid=keyid, profile=profile) if not group: log.error('Group %s does not exist', group_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_group_policy(group_name, policy_name, policy_json) if created: log.info('Created policy for IAM group %s.', group_name) return True log.error('Could not create policy for IAM group %s', group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy for IAM group %s', group_name) return False def delete_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group_policy mygroup mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_group_policy( group_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_group_policy(group_name, policy_name) log.info('Successfully deleted policy %s for IAM group %s.', policy_name, group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM group %s.', policy_name, group_name) return False def get_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group_policy mygroup policyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group_policy(group_name, policy_name) log.debug('info for group policy is : %s', info) if not info: return False info = info.get_group_policy_response.get_group_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_all_groups(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM group details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_groups ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _groups = conn.get_all_groups(path_prefix=path_prefix) groups = _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) while marker: _groups = conn.get_all_groups(path_prefix=path_prefix, marker=marker) groups = groups + _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) return groups def get_all_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.get_all_instance_profiles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) marker = False profiles = [] while marker is not None: marker = marker if marker else None p = conn.list_instance_profiles(path_prefix=path_prefix, marker=marker) res = p.list_instance_profiles_response.list_instance_profiles_result profiles += res.instance_profiles marker = getattr(res, 'marker', None) return profiles def list_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' List all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.list_instance_profiles ''' p = get_all_instance_profiles(path_prefix, region, key, keyid, profile) return [i['instance_profile_name'] for i in p] def get_all_group_policies(group_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a group. CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_group_policies mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False try: response = conn.get_all_group_policies(group_name) _list = response.list_group_policies_response.list_group_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def delete_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _group = get_group( group_name, region, key, keyid, profile ) if not _group: return True try: conn.delete_group(group_name) log.info('Successfully deleted IAM group %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM group %s.', group_name) return False def create_login_profile(user_name, password, region=None, key=None, keyid=None, profile=None): ''' Creates a login profile for the specified user, give the user the ability to access AWS services and the AWS Management Console. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_login_profile user_name password ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.create_login_profile(user_name, password) log.info('Created profile for IAM user %s.', user_name) return info except boto.exception.BotoServerError as e: log.debug(e) if 'Conflict' in e: log.info('Profile already exists for IAM user %s.', user_name) return 'Conflict' log.error('Failed to update profile for IAM user %s.', user_name) return False def delete_login_profile(user_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a login profile for the specified user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_login_profile user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.delete_login_profile(user_name) log.info('Deleted login profile for IAM user %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Login profile already deleted for IAM user %s.', user_name) return True log.error('Failed to delete login profile for IAM user %s.', user_name) return False def get_all_mfa_devices(user_name, region=None, key=None, keyid=None, profile=None): ''' Get all MFA devices associated with an IAM user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_mfa_devices user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: result = conn.get_all_mfa_devices(user_name) devices = result['list_mfa_devices_response']['list_mfa_devices_result']['mfa_devices'] return devices except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Could not find IAM user %s.', user_name) return [] log.error('Failed to get all MFA devices for IAM user %s.', user_name) return False def deactivate_mfa_device(user_name, serial, region=None, key=None, keyid=None, profile=None): ''' Deactivates the specified MFA device and removes it from association with the user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.deactivate_mfa_device user_name serial_num ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.deactivate_mfa_device(user_name, serial) log.info('Deactivated MFA device %s for IAM user %s.', serial, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('MFA device %s not associated with IAM user %s.', serial, user_name) return True log.error('Failed to deactivate MFA device %s for IAM user %s.', serial, user_name) return False def delete_virtual_mfa_device(serial, region=None, key=None, keyid=None, profile=None): ''' Deletes the specified virtual MFA device. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_virtual_mfa_device serial_num ''' conn = __utils__['boto3.get_connection_func']('iam')() try: conn.delete_virtual_mfa_device(SerialNumber=serial) log.info('Deleted virtual MFA device %s.', serial) return True except botocore.exceptions.ClientError as e: log.debug(e) if 'NoSuchEntity' in six.text_type(e): log.info('Virtual MFA device %s not found.', serial) return True log.error('Failed to delete virtual MFA device %s.', serial) return False def update_account_password_policy(allow_users_to_change_password=None, hard_expiry=None, max_password_age=None, minimum_password_length=None, password_reuse_prevention=None, require_lowercase_characters=None, require_numbers=None, require_symbols=None, require_uppercase_characters=None, region=None, key=None, keyid=None, profile=None): ''' Update the password policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_account_password_policy True ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.update_account_password_policy(allow_users_to_change_password, hard_expiry, max_password_age, minimum_password_length, password_reuse_prevention, require_lowercase_characters, require_numbers, require_symbols, require_uppercase_characters) log.info('The password policy has been updated.') return True except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy' log.error(msg) return False def get_account_policy(region=None, key=None, keyid=None, profile=None): ''' Get account policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_account_password_policy() return info.get_account_password_policy_response.get_account_password_policy_result.password_policy except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy.' log.error(msg) return False def create_role(name, policy_document=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Create an instance role. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if role_exists(name, region, key, keyid, profile): return True if not policy_document: policy_document = None try: conn.create_role(name, assume_role_policy_document=policy_document, path=path) log.info('Created IAM role %s.', name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to create IAM role %s.', name) return False def delete_role(name, region=None, key=None, keyid=None, profile=None): ''' Delete an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(name, region, key, keyid, profile): return True try: conn.delete_role(name) log.info('Deleted %s IAM role.', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s IAM role.', name) return False def profile_associated(role_name, profile_name, region, key, keyid, profile): ''' Check to see if an instance profile is associated with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.profile_associated myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # The IAM module of boto doesn't return objects. Instead you need to grab # values through its properties. Sigh. try: profiles = conn.list_instance_profiles_for_role(role_name) except boto.exception.BotoServerError as e: log.debug(e) return False profiles = profiles.list_instance_profiles_for_role_response profiles = profiles.list_instance_profiles_for_role_result profiles = profiles.instance_profiles for profile in profiles: if profile.instance_profile_name == profile_name: return True return False def associate_profile_to_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Associate an instance profile with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.associate_profile_to_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if associated: return True else: try: conn.add_role_to_instance_profile(profile_name, role_name) log.info('Added %s instance profile to IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add %s instance profile to IAM role %s', profile_name, role_name) return False def disassociate_profile_from_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Disassociate an instance profile from an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.disassociate_profile_from_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if not associated: return True else: try: conn.remove_role_from_instance_profile(profile_name, role_name) log.info('Removed %s instance profile from IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove %s instance profile from IAM role %s.', profile_name, role_name) return False def list_role_policies(role_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_role_policies myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_role_policies(role_name) _list = response.list_role_policies_response.list_role_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def get_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.get_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: _policy = conn.get_role_policy(role_name, policy_name) # I _hate_ you for not giving me an object boto. _policy = _policy.get_role_policy_response.policy_document # Policy is url encoded _policy = _unquote(_policy) _policy = salt.utils.json.loads(_policy, object_pairs_hook=odict.OrderedDict) return _policy except boto.exception.BotoServerError: return {} def create_role_policy(role_name, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Create or modify a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role_policy myirole mypolicy '{"MyPolicy": "Statement": [{"Action": ["sqs:*"], "Effect": "Allow", "Resource": ["arn:aws:sqs:*:*:*"], "Sid": "MyPolicySqs1"}]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) mode = 'create' if _policy: if _policy == policy: return True mode = 'modify' if isinstance(policy, six.string_types): policy = salt.utils.json.loads(policy, object_pairs_hook=odict.OrderedDict) try: _policy = salt.utils.json.dumps(policy) conn.put_role_policy(role_name, policy_name, _policy) if mode == 'create': msg = 'Successfully added policy %s to IAM role %s.' else: msg = 'Successfully modified policy %s for IAM role %s.' log.info(msg, policy_name, role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to %s policy %s for IAM role %s.', mode, policy_name, role_name) return False def delete_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) if not _policy: return True try: conn.delete_role_policy(role_name, policy_name) log.info('Successfully deleted policy %s for IAM role %s.', policy_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM role %s.', policy_name, role_name) return False def update_assume_role_policy(role_name, policy_document, region=None, key=None, keyid=None, profile=None): ''' Update an assume role policy for a role. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_assume_role_policy myrole '{"Statement":"..."}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(policy_document, six.string_types): policy_document = salt.utils.json.loads(policy_document, object_pairs_hook=odict.OrderedDict) try: _policy_document = salt.utils.json.dumps(policy_document) conn.update_assume_role_policy(role_name, _policy_document) log.info('Successfully updated assume role policy for IAM role %s.', role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to update assume role policy for IAM role %s.', role_name) return False def build_policy(region=None, key=None, keyid=None, profile=None): ''' Build a default assume role policy. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.build_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if hasattr(conn, 'build_policy'): policy = salt.utils.json.loads(conn.build_policy()) elif hasattr(conn, '_build_policy'): policy = salt.utils.json.loads(conn._build_policy()) else: return {} # The format we get from build_policy isn't going to be what we get back # from AWS for the exact same policy. AWS converts single item list values # into strings, so let's do the same here. for key, policy_val in policy.items(): for statement in policy_val: if (isinstance(statement['Action'], list) and len(statement['Action']) == 1): statement['Action'] = statement['Action'][0] if (isinstance(statement['Principal']['Service'], list) and len(statement['Principal']['Service']) == 1): statement['Principal']['Service'] = statement['Principal']['Service'][0] # build_policy doesn't add a version field, which AWS is going to set to a # default value, when we get it back, so let's set it. policy['Version'] = '2008-10-17' return policy def get_account_id(region=None, key=None, keyid=None, profile=None): ''' Get a the AWS account id associated with the used credentials. CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_id ''' cache_key = 'boto_iam.account_id' if cache_key not in __context__: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_user() # The get_user call returns an user ARN: # arn:aws:iam::027050522557:user/salt-test arn = ret['get_user_response']['get_user_result']['user']['arn'] account_id = arn.split(':')[4] except boto.exception.BotoServerError: # If call failed, then let's try to get the ARN from the metadata timeout = boto.config.getfloat( 'Boto', 'metadata_service_timeout', 1.0 ) attempts = boto.config.getint( 'Boto', 'metadata_service_num_attempts', 1 ) identity = boto.utils.get_instance_identity( timeout=timeout, num_retries=attempts ) try: account_id = identity['document']['accountId'] except KeyError: log.error('Failed to get account id from instance_identity in' ' boto_iam.get_account_id.') __context__[cache_key] = account_id return __context__[cache_key] def get_all_roles(path_prefix=None, region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM role details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_roles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _roles = conn.list_roles(path_prefix=path_prefix) roles = _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) while marker: _roles = conn.list_roles(path_prefix=path_prefix, marker=marker) roles = roles + _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) return roles def get_all_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM user details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_users ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _users = conn.get_all_users(path_prefix=path_prefix) users = _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) while marker: _users = conn.get_all_users(path_prefix=path_prefix, marker=marker) users = users + _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) return users def get_all_user_policies(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all user policies. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_user_policies myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_all_user_policies(user_name, marker, max_items) if not info: return False _list = info.list_user_policies_response.list_user_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policies for user %s.', user_name) return False def get_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user_policy myuser mypolicyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user_policy(user_name, policy_name) log.debug('Info for IAM user %s policy %s: %s.', user_name, policy_name, info) if not info: return False info = info.get_user_policy_response.get_user_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policy %s for IAM user %s.', policy_name, user_name) return False def put_user_policy(user_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_user_policy myuser policyname policyrules ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_user_policy(user_name, policy_name, policy_json) if created: log.info('Created policy %s for IAM user %s.', policy_name, user_name) return True log.error('Could not create policy %s for IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy %s for IAM user %s.', policy_name, user_name) return False def delete_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user_policy myuser mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_user_policy( user_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_user_policy(user_name, policy_name) log.info('Successfully deleted policy %s for IAM user %s.', policy_name, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM user %s.', policy_name, user_name) return False def upload_server_cert(cert_name, cert_body, private_key, cert_chain=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Upload a certificate to Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.upload_server_cert mycert_name crt priv_key :param cert_name: The name for the server certificate. Do not include the path in this value. :param cert_body: The contents of the public key certificate in PEM-encoded format. :param private_key: The contents of the private key in PEM-encoded format. :param cert_chain: The contents of the certificate chain. This is typically a concatenation of the PEM-encoded public key certificates of the chain. :param path: The path for the server certificate. :param region: The name of the region to connect to. :param key: The key to be used in order to connect :param keyid: The keyid to be used in order to connect :param profile: The profile that contains a dict of region, key, keyid :return: True / False ''' exists = get_server_certificate(cert_name, region, key, keyid, profile) if exists: return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.upload_server_cert(cert_name, cert_body, private_key, cert_chain) log.info('Created certificate %s.', cert_name) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to failed to create certificate %s.', cert_name) return False def list_server_certificates(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Lists the server certificates stored in IAM that have the specified path prefix. .. versionadded:: ??? :param path_prefix: The path prefix for filtering the results. For example: /company/servercerts would get all server certificates for which the path starts with /company/servercerts . This parameter is optional. If it is not included, it defaults to a slash (/), listing all server certificates. This parameter allows (per its regex pattern) a string of characters consisting of either a forward slash (/) by itself or a string that must begin and end with forward slashes. In addition, it can contain any ASCII character from the ! (u0021) through the DEL character (u007F), including most punctuation characters, digits, and upper and lowercased letters. CLI Example: .. code-block:: bash salt myminion boto_iam.list_server_certificates path_prefix=/somepath/ ''' retries = 10 sleep = 6 conn = __utils__['boto3.get_connection']('iam', region=region, key=key, keyid=keyid, profile=profile) Items = [] while retries: try: log.debug('Garnering list of IAM Server Certificates') IsTruncated = True while IsTruncated: kwargs = {'PathPrefix': path_prefix} ret = conn.list_server_certificates(**kwargs) Items += ret.get('ServerCertificateMetadataList', []) IsTruncated = ret.get('IsTruncated') kwargs.update({'Marker': ret.get('Marker')}) return Items except botocore.exceptions.ParamValidationError as err: raise SaltInvocationError(str(err)) except botocore.exceptions.ClientError as err: if retries and jmespath.search('Error.Code', err.response) == 'Throttling': retries -= 1 log.debug('Throttled by AWS API, retrying in %s seconds...', sleep) time.sleep(sleep) continue log.error('Failed to list IAM Server Certificates: %s', err.message) return None def get_server_certificate(cert_name, region=None, key=None, keyid=None, profile=None): ''' Returns certificate information from Amazon .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_server_certificate mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_server_certificate(cert_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get certificate %s information.', cert_name) return False def delete_server_cert(cert_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a certificate from Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_server_cert mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_server_cert(cert_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete certificate %s.', cert_name) return False def export_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM user details. Produces results that can be used to create an sls file. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.export_users --out=txt | sed "s/local: //" > iam_users.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() users = get_all_users(path_prefix, region, key, keyid, profile) for user in users: name = user.user_name _policies = conn.get_all_user_policies(name, max_items=100) _policies = _policies.list_user_policies_response.list_user_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_user_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_user_policy_response.get_user_policy_result.policy_document )) policies[policy_name] = _policy user_sls = [] user_sls.append({"name": name}) user_sls.append({"policies": policies}) user_sls.append({"path": user.path}) results["manage user " + name] = {"boto_iam.user_present": user_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def export_roles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM role details. Produces results that can be used to create an sls file. CLI Example: salt-call boto_iam.export_roles --out=txt | sed "s/local: //" > iam_roles.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() roles = get_all_roles(path_prefix, region, key, keyid, profile) for role in roles: name = role.role_name _policies = conn.list_role_policies(name, max_items=100) _policies = _policies.list_role_policies_response.list_role_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_role_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_role_policy_response.get_role_policy_result.policy_document )) policies[policy_name] = _policy role_sls = [] role_sls.append({"name": name}) role_sls.append({"policies": policies}) role_sls.append({'policy_document': salt.utils.json.loads(_unquote(role.assume_role_policy_document))}) role_sls.append({"path": role.path}) results["manage role " + name] = {"boto_iam_role.present": role_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def _get_policy_arn(name, region=None, key=None, keyid=None, profile=None): if name.startswith('arn:aws:iam:'): return name account_id = get_account_id( region=region, key=key, keyid=keyid, profile=profile ) return 'arn:aws:iam::{0}:policy/{1}'.format(account_id, name) def policy_exists(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return True except boto.exception.BotoServerError: return False def get_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return ret.get('get_policy_response', {}).get('get_policy_result', {}) except boto.exception.BotoServerError: return None def create_policy(policy_name, policy_document, path=None, description=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in 'path', 'description': if locals()[arg] is not None: params[arg] = locals()[arg] if policy_exists(policy_name, region, key, keyid, profile): return True try: conn.create_policy(policy_name, policy_document, **params) log.info('Created IAM policy %s.', policy_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s.', policy_name) return False return True def delete_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_exists(policy_arn, region, key, keyid, profile): return True try: conn.delete_policy(policy_arn) log.info('Deleted %s policy.', policy_name) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete %s policy: %s.', policy_name, aws.get('message')) return False return True def list_policies(region=None, key=None, keyid=None, profile=None): ''' List policies. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policies ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: policies = [] for ret in __utils__['boto.paged_call'](conn.list_policies): policies.append(ret.get('list_policies_response', {}).get('list_policies_result', {}).get('policies')) return policies except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to list policy versions.' log.error(msg) return [] def policy_version_exists(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.get_policy_version(policy_arn, version_id) return True except boto.exception.BotoServerError: return False def get_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy_version(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile), version_id) retval = ret.get('get_policy_version_response', {}).get('get_policy_version_result', {}).get('policy_version', {}) retval['document'] = _unquote(retval.get('document')) return {'policy_version': retval} except boto.exception.BotoServerError: return None def create_policy_version(policy_name, policy_document, set_as_default=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy version. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy_version mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in ('set_as_default',): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.create_policy_version(policy_arn, policy_document, **params) vid = ret.get('create_policy_version_response', {}).get('create_policy_version_result', {}).get('policy_version', {}).get('version_id') log.info('Created IAM policy %s version %s.', policy_name, vid) return {'created': True, 'version_id': vid} except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s version %s.', policy_name, vid) return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Delete a policy version. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_version_exists(policy_arn, version_id, region, key, keyid, profile): return True try: conn.delete_policy_version(policy_arn, version_id) log.info('Deleted IAM policy %s version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete IAM policy %s version %s: %s', policy_name, version_id, aws.get('message')) return False return True def list_policy_versions(policy_name, region=None, key=None, keyid=None, profile=None): ''' List versions of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policy_versions mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.list_policy_versions(policy_arn) return ret.get('list_policy_versions_response', {}).get('list_policy_versions_result', {}).get('versions') except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list versions for IAM policy %s.', policy_name) return [] def set_default_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Set the default version of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.set_default_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.set_default_policy_version(policy_arn, version_id) log.info('Set %s policy to version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to set %s policy to version %s: %s', policy_name, version_id, aws.get('message')) return False return True def attach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_user_policy(policy_arn, user_name) log.info('Attached policy %s to IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach %s policy to IAM user %s.', policy_name, user_name) return False return True def detach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_user_policy(policy_arn, user_name) log.info('Detached %s policy from IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach %s policy from IAM user %s.', policy_name, user_name) return False return True def attach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_group_policy(policy_arn, group_name) log.info('Attached policy %s to IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM group %s.', policy_name, group_name) return False return True def detach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_group_policy(policy_arn, group_name) log.info('Detached policy %s from IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM group %s.', policy_name, group_name) return False return True def attach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_role_policy(policy_arn, role_name) log.info('Attached policy %s to IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM role %s.', policy_name, role_name) return False return True def detach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_role_policy(policy_arn, role_name) log.info('Detached policy %s from IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM role %s.', policy_name, role_name) return False return True def list_entities_for_policy(policy_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities that a policy is attached to. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 params = {} for arg in ('path_prefix', 'entity_filter'): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) while retries: try: allret = { 'policy_groups': [], 'policy_users': [], 'policy_roles': [], } for ret in __utils__['boto.paged_call'](conn.list_entities_for_policy, policy_arn=policy_arn, **params): for k, v in six.iteritems(allret): v.extend(ret.get('list_entities_for_policy_response', {}).get('list_entities_for_policy_result', {}).get(k)) return allret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('Failed to list entities for IAM policy %s: %s', policy_name, e.message) return {} return {} def list_attached_user_policies(user_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given user. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'UserName': user_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedUserPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_user_policies_response', {}).get('list_attached_user_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM user %s.', user_name) return [] def list_attached_group_policies(group_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given group. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'GroupName': group_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedGroupPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_group_policies_response', {}).get('list_attached_group_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM group %s.', group_name) return [] def list_attached_role_policies(role_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'RoleName': role_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedRolePolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_role_policies_response', {}).get('list_attached_role_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM role %s.', role_name) return [] def create_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Create SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.create_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_saml_provider(saml_metadata_document, name) log.info('Successfully created %s SAML provider.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to create SAML provider %s.', name) return False def get_saml_provider_arn(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider_arn my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_saml_providers() for saml_provider in response.list_saml_providers_response.list_saml_providers_result.saml_provider_list: if saml_provider['arn'].endswith(':saml-provider/' + name): return saml_provider['arn'] return False except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to get ARN of SAML provider %s.', name) return False def delete_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Delete SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.delete_saml_provider my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return True conn.delete_saml_provider(saml_provider_arn) log.info('Successfully deleted SAML provider %s.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete SAML provider %s.', name) return False def list_saml_providers(region=None, key=None, keyid=None, profile=None): ''' List SAML providers. CLI Example: .. code-block:: bash salt myminion boto_iam.list_saml_providers ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: providers = [] info = conn.list_saml_providers() for arn in info['list_saml_providers_response']['list_saml_providers_result']['saml_provider_list']: providers.append(arn['arn'].rsplit('/', 1)[1]) return providers except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get list of SAML providers.') return False def get_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider document. CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider arn ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: provider = conn.get_saml_provider(name) return provider['get_saml_provider_response']['get_saml_provider_result']['saml_metadata_document'] except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get SAML provider document %s.', name) return False def update_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Update SAML provider. CLI Example: .. code-block:: bash salt myminion boto_iam.update_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return False if conn.update_saml_provider(name, saml_metadata_document): return True return False except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to update SAML provider %s.', name) return False
saltstack/salt
salt/modules/boto_iam.py
create_user
python
def create_user(user_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_user myuser ''' if not path: path = '/' if get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_user(user_name, path) log.info('Created IAM user : %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM user %s.', user_name) return False
Create a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_user myuser
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iam.py#L212-L237
[ "def get_user(user_name=None, region=None, key=None, keyid=None, profile=None):\n '''\n Get user information.\n\n .. versionadded:: 2015.8.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_iam.get_user myuser\n '''\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n try:\n info = conn.get_user(user_name)\n if not info:\n return False\n return info\n except boto.exception.BotoServerError as e:\n log.debug(e)\n log.error('Failed to get IAM user %s info.', user_name)\n return False\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon IAM .. versionadded:: 2014.7.0 :configuration: This module accepts explicit iam 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 iam.keyid: GKTADJGHEIQSXMKKRBJ08H iam.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs iam.region: 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: boto ''' # keep lint from choking on _get_conn and _cache_id #pylint: disable=E0602 # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import salt libs from salt.ext import six import salt.utils.compat import salt.utils.json import salt.utils.odict as odict import salt.utils.versions from salt.exceptions import SaltInvocationError # Import third party libs # pylint: disable=unused-import from salt.ext.six.moves.urllib.parse import unquote as _unquote # pylint: disable=no-name-in-module try: import boto import boto.iam import boto3 import botocore logging.getLogger('boto').setLevel(logging.CRITICAL) logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=unused-import log = logging.getLogger(__name__) def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'iam', pack=__salt__) def instance_profile_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an instance profile exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: # Boto weirdly returns an exception here if an instance profile doesn't # exist. conn.get_instance_profile(name) return True except boto.exception.BotoServerError: return False def create_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Create an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.create_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if instance_profile_exists(name, region, key, keyid, profile): return True try: # This call returns an instance profile if successful and an exception # if not. It's annoying. conn.create_instance_profile(name) log.info('Created %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create %s instance profile.', name) return False return True def delete_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Delete an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not instance_profile_exists(name, region, key, keyid, profile): return True try: conn.delete_instance_profile(name) log.info('Deleted %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s instance profile.', name) return False return True def role_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an IAM role exists. CLI Example: .. code-block:: bash salt myminion boto_iam.role_exists myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_role(name) return True except boto.exception.BotoServerError: return False def describe_role(name, region=None, key=None, keyid=None, profile=None): ''' Get information for a role. CLI Example: .. code-block:: bash salt myminion boto_iam.describe_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_role(name) if not info: return False role = info.get_role_response.get_role_result.role role['assume_role_policy_document'] = salt.utils.json.loads(_unquote( role.assume_role_policy_document )) # If Sid wasn't defined by the user, boto will still return a Sid in # each policy. To properly check idempotently, let's remove the Sid # from the return if it's not actually set. for policy_key, policy in role['assume_role_policy_document'].items(): if policy_key == 'Statement': for val in policy: if 'Sid' in val and not val['Sid']: del val['Sid'] return role except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get %s information.', name) return False def get_all_access_keys(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all access keys from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_access_keys myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.get_all_access_keys(user_name, marker, max_items) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get access keys for IAM user %s.', user_name) return six.text_type(e) def create_access_key(user_name, region=None, key=None, keyid=None, profile=None): ''' Create access key id for a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.create_access_key(user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create access key.') return six.text_type(e) def delete_access_key(access_key_id, user_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete access key id from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_access_key(access_key_id, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete access key id %s.', access_key_id) return six.text_type(e) def delete_user(user_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user myuser ''' if not get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.delete_user(user_name) log.info('Deleted IAM user : %s .', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM user %s', user_name) return six.text_type(e) def get_user(user_name=None, region=None, key=None, keyid=None, profile=None): ''' Get user information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user(user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM user %s info.', user_name) return False def create_group(group_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_group group ''' if not path: path = '/' if get_group(group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_group(group_name, path) log.info('Created IAM group : %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM group %s.', group_name) return False def get_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group(group_name, max_items=1) if not info: return False return info['get_group_response']['get_group_result']['group'] except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_group_members(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: marker = None truncated = True users = [] while truncated: info = conn.get_group(group_name, marker=marker, max_items=1000) if not info: return False truncated = bool(info['get_group_response']['get_group_result']['is_truncated']) if truncated and 'marker' in info['get_group_response']['get_group_result']: marker = info['get_group_response']['get_group_result']['marker'] else: marker = None truncated = False users += info['get_group_response']['get_group_result']['users'] return users except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get members for IAM group %s.', group_name) return False def add_user_to_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Add user to group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.add_user_to_group myuser mygroup ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('Username : %s does not exist.', user_name) return False if user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.add_user_to_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add IAM user %s to group %s.', user_name, group_name) return False def user_exists_in_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Check if user exists in group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.user_exists_in_group myuser mygroup ''' # TODO this should probably use boto.iam.get_groups_for_user users = get_group_members( group_name=group_name, region=region, key=key, keyid=keyid, profile=profile ) if users: for _user in users: if user_name == _user['user_name']: log.debug('IAM user %s is already in IAM group %s.', user_name, group_name) return True return False def remove_user_from_group(group_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Remove user from group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.remove_user_from_group mygroup myuser ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist.', user_name) return False if not user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.remove_user_from_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove IAM user %s from group %s', user_name, group_name) return False def put_group_policy(group_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_group_policy mygroup policyname policyrules ''' group = get_group(group_name, region=region, key=key, keyid=keyid, profile=profile) if not group: log.error('Group %s does not exist', group_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_group_policy(group_name, policy_name, policy_json) if created: log.info('Created policy for IAM group %s.', group_name) return True log.error('Could not create policy for IAM group %s', group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy for IAM group %s', group_name) return False def delete_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group_policy mygroup mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_group_policy( group_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_group_policy(group_name, policy_name) log.info('Successfully deleted policy %s for IAM group %s.', policy_name, group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM group %s.', policy_name, group_name) return False def get_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group_policy mygroup policyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group_policy(group_name, policy_name) log.debug('info for group policy is : %s', info) if not info: return False info = info.get_group_policy_response.get_group_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_all_groups(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM group details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_groups ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _groups = conn.get_all_groups(path_prefix=path_prefix) groups = _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) while marker: _groups = conn.get_all_groups(path_prefix=path_prefix, marker=marker) groups = groups + _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) return groups def get_all_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.get_all_instance_profiles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) marker = False profiles = [] while marker is not None: marker = marker if marker else None p = conn.list_instance_profiles(path_prefix=path_prefix, marker=marker) res = p.list_instance_profiles_response.list_instance_profiles_result profiles += res.instance_profiles marker = getattr(res, 'marker', None) return profiles def list_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' List all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.list_instance_profiles ''' p = get_all_instance_profiles(path_prefix, region, key, keyid, profile) return [i['instance_profile_name'] for i in p] def get_all_group_policies(group_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a group. CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_group_policies mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False try: response = conn.get_all_group_policies(group_name) _list = response.list_group_policies_response.list_group_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def delete_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _group = get_group( group_name, region, key, keyid, profile ) if not _group: return True try: conn.delete_group(group_name) log.info('Successfully deleted IAM group %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM group %s.', group_name) return False def create_login_profile(user_name, password, region=None, key=None, keyid=None, profile=None): ''' Creates a login profile for the specified user, give the user the ability to access AWS services and the AWS Management Console. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_login_profile user_name password ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.create_login_profile(user_name, password) log.info('Created profile for IAM user %s.', user_name) return info except boto.exception.BotoServerError as e: log.debug(e) if 'Conflict' in e: log.info('Profile already exists for IAM user %s.', user_name) return 'Conflict' log.error('Failed to update profile for IAM user %s.', user_name) return False def delete_login_profile(user_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a login profile for the specified user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_login_profile user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.delete_login_profile(user_name) log.info('Deleted login profile for IAM user %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Login profile already deleted for IAM user %s.', user_name) return True log.error('Failed to delete login profile for IAM user %s.', user_name) return False def get_all_mfa_devices(user_name, region=None, key=None, keyid=None, profile=None): ''' Get all MFA devices associated with an IAM user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_mfa_devices user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: result = conn.get_all_mfa_devices(user_name) devices = result['list_mfa_devices_response']['list_mfa_devices_result']['mfa_devices'] return devices except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Could not find IAM user %s.', user_name) return [] log.error('Failed to get all MFA devices for IAM user %s.', user_name) return False def deactivate_mfa_device(user_name, serial, region=None, key=None, keyid=None, profile=None): ''' Deactivates the specified MFA device and removes it from association with the user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.deactivate_mfa_device user_name serial_num ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.deactivate_mfa_device(user_name, serial) log.info('Deactivated MFA device %s for IAM user %s.', serial, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('MFA device %s not associated with IAM user %s.', serial, user_name) return True log.error('Failed to deactivate MFA device %s for IAM user %s.', serial, user_name) return False def delete_virtual_mfa_device(serial, region=None, key=None, keyid=None, profile=None): ''' Deletes the specified virtual MFA device. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_virtual_mfa_device serial_num ''' conn = __utils__['boto3.get_connection_func']('iam')() try: conn.delete_virtual_mfa_device(SerialNumber=serial) log.info('Deleted virtual MFA device %s.', serial) return True except botocore.exceptions.ClientError as e: log.debug(e) if 'NoSuchEntity' in six.text_type(e): log.info('Virtual MFA device %s not found.', serial) return True log.error('Failed to delete virtual MFA device %s.', serial) return False def update_account_password_policy(allow_users_to_change_password=None, hard_expiry=None, max_password_age=None, minimum_password_length=None, password_reuse_prevention=None, require_lowercase_characters=None, require_numbers=None, require_symbols=None, require_uppercase_characters=None, region=None, key=None, keyid=None, profile=None): ''' Update the password policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_account_password_policy True ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.update_account_password_policy(allow_users_to_change_password, hard_expiry, max_password_age, minimum_password_length, password_reuse_prevention, require_lowercase_characters, require_numbers, require_symbols, require_uppercase_characters) log.info('The password policy has been updated.') return True except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy' log.error(msg) return False def get_account_policy(region=None, key=None, keyid=None, profile=None): ''' Get account policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_account_password_policy() return info.get_account_password_policy_response.get_account_password_policy_result.password_policy except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy.' log.error(msg) return False def create_role(name, policy_document=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Create an instance role. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if role_exists(name, region, key, keyid, profile): return True if not policy_document: policy_document = None try: conn.create_role(name, assume_role_policy_document=policy_document, path=path) log.info('Created IAM role %s.', name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to create IAM role %s.', name) return False def delete_role(name, region=None, key=None, keyid=None, profile=None): ''' Delete an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(name, region, key, keyid, profile): return True try: conn.delete_role(name) log.info('Deleted %s IAM role.', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s IAM role.', name) return False def profile_associated(role_name, profile_name, region, key, keyid, profile): ''' Check to see if an instance profile is associated with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.profile_associated myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # The IAM module of boto doesn't return objects. Instead you need to grab # values through its properties. Sigh. try: profiles = conn.list_instance_profiles_for_role(role_name) except boto.exception.BotoServerError as e: log.debug(e) return False profiles = profiles.list_instance_profiles_for_role_response profiles = profiles.list_instance_profiles_for_role_result profiles = profiles.instance_profiles for profile in profiles: if profile.instance_profile_name == profile_name: return True return False def associate_profile_to_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Associate an instance profile with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.associate_profile_to_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if associated: return True else: try: conn.add_role_to_instance_profile(profile_name, role_name) log.info('Added %s instance profile to IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add %s instance profile to IAM role %s', profile_name, role_name) return False def disassociate_profile_from_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Disassociate an instance profile from an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.disassociate_profile_from_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if not associated: return True else: try: conn.remove_role_from_instance_profile(profile_name, role_name) log.info('Removed %s instance profile from IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove %s instance profile from IAM role %s.', profile_name, role_name) return False def list_role_policies(role_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_role_policies myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_role_policies(role_name) _list = response.list_role_policies_response.list_role_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def get_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.get_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: _policy = conn.get_role_policy(role_name, policy_name) # I _hate_ you for not giving me an object boto. _policy = _policy.get_role_policy_response.policy_document # Policy is url encoded _policy = _unquote(_policy) _policy = salt.utils.json.loads(_policy, object_pairs_hook=odict.OrderedDict) return _policy except boto.exception.BotoServerError: return {} def create_role_policy(role_name, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Create or modify a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role_policy myirole mypolicy '{"MyPolicy": "Statement": [{"Action": ["sqs:*"], "Effect": "Allow", "Resource": ["arn:aws:sqs:*:*:*"], "Sid": "MyPolicySqs1"}]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) mode = 'create' if _policy: if _policy == policy: return True mode = 'modify' if isinstance(policy, six.string_types): policy = salt.utils.json.loads(policy, object_pairs_hook=odict.OrderedDict) try: _policy = salt.utils.json.dumps(policy) conn.put_role_policy(role_name, policy_name, _policy) if mode == 'create': msg = 'Successfully added policy %s to IAM role %s.' else: msg = 'Successfully modified policy %s for IAM role %s.' log.info(msg, policy_name, role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to %s policy %s for IAM role %s.', mode, policy_name, role_name) return False def delete_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) if not _policy: return True try: conn.delete_role_policy(role_name, policy_name) log.info('Successfully deleted policy %s for IAM role %s.', policy_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM role %s.', policy_name, role_name) return False def update_assume_role_policy(role_name, policy_document, region=None, key=None, keyid=None, profile=None): ''' Update an assume role policy for a role. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_assume_role_policy myrole '{"Statement":"..."}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(policy_document, six.string_types): policy_document = salt.utils.json.loads(policy_document, object_pairs_hook=odict.OrderedDict) try: _policy_document = salt.utils.json.dumps(policy_document) conn.update_assume_role_policy(role_name, _policy_document) log.info('Successfully updated assume role policy for IAM role %s.', role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to update assume role policy for IAM role %s.', role_name) return False def build_policy(region=None, key=None, keyid=None, profile=None): ''' Build a default assume role policy. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.build_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if hasattr(conn, 'build_policy'): policy = salt.utils.json.loads(conn.build_policy()) elif hasattr(conn, '_build_policy'): policy = salt.utils.json.loads(conn._build_policy()) else: return {} # The format we get from build_policy isn't going to be what we get back # from AWS for the exact same policy. AWS converts single item list values # into strings, so let's do the same here. for key, policy_val in policy.items(): for statement in policy_val: if (isinstance(statement['Action'], list) and len(statement['Action']) == 1): statement['Action'] = statement['Action'][0] if (isinstance(statement['Principal']['Service'], list) and len(statement['Principal']['Service']) == 1): statement['Principal']['Service'] = statement['Principal']['Service'][0] # build_policy doesn't add a version field, which AWS is going to set to a # default value, when we get it back, so let's set it. policy['Version'] = '2008-10-17' return policy def get_account_id(region=None, key=None, keyid=None, profile=None): ''' Get a the AWS account id associated with the used credentials. CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_id ''' cache_key = 'boto_iam.account_id' if cache_key not in __context__: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_user() # The get_user call returns an user ARN: # arn:aws:iam::027050522557:user/salt-test arn = ret['get_user_response']['get_user_result']['user']['arn'] account_id = arn.split(':')[4] except boto.exception.BotoServerError: # If call failed, then let's try to get the ARN from the metadata timeout = boto.config.getfloat( 'Boto', 'metadata_service_timeout', 1.0 ) attempts = boto.config.getint( 'Boto', 'metadata_service_num_attempts', 1 ) identity = boto.utils.get_instance_identity( timeout=timeout, num_retries=attempts ) try: account_id = identity['document']['accountId'] except KeyError: log.error('Failed to get account id from instance_identity in' ' boto_iam.get_account_id.') __context__[cache_key] = account_id return __context__[cache_key] def get_all_roles(path_prefix=None, region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM role details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_roles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _roles = conn.list_roles(path_prefix=path_prefix) roles = _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) while marker: _roles = conn.list_roles(path_prefix=path_prefix, marker=marker) roles = roles + _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) return roles def get_all_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM user details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_users ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _users = conn.get_all_users(path_prefix=path_prefix) users = _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) while marker: _users = conn.get_all_users(path_prefix=path_prefix, marker=marker) users = users + _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) return users def get_all_user_policies(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all user policies. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_user_policies myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_all_user_policies(user_name, marker, max_items) if not info: return False _list = info.list_user_policies_response.list_user_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policies for user %s.', user_name) return False def get_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user_policy myuser mypolicyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user_policy(user_name, policy_name) log.debug('Info for IAM user %s policy %s: %s.', user_name, policy_name, info) if not info: return False info = info.get_user_policy_response.get_user_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policy %s for IAM user %s.', policy_name, user_name) return False def put_user_policy(user_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_user_policy myuser policyname policyrules ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_user_policy(user_name, policy_name, policy_json) if created: log.info('Created policy %s for IAM user %s.', policy_name, user_name) return True log.error('Could not create policy %s for IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy %s for IAM user %s.', policy_name, user_name) return False def delete_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user_policy myuser mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_user_policy( user_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_user_policy(user_name, policy_name) log.info('Successfully deleted policy %s for IAM user %s.', policy_name, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM user %s.', policy_name, user_name) return False def upload_server_cert(cert_name, cert_body, private_key, cert_chain=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Upload a certificate to Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.upload_server_cert mycert_name crt priv_key :param cert_name: The name for the server certificate. Do not include the path in this value. :param cert_body: The contents of the public key certificate in PEM-encoded format. :param private_key: The contents of the private key in PEM-encoded format. :param cert_chain: The contents of the certificate chain. This is typically a concatenation of the PEM-encoded public key certificates of the chain. :param path: The path for the server certificate. :param region: The name of the region to connect to. :param key: The key to be used in order to connect :param keyid: The keyid to be used in order to connect :param profile: The profile that contains a dict of region, key, keyid :return: True / False ''' exists = get_server_certificate(cert_name, region, key, keyid, profile) if exists: return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.upload_server_cert(cert_name, cert_body, private_key, cert_chain) log.info('Created certificate %s.', cert_name) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to failed to create certificate %s.', cert_name) return False def list_server_certificates(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Lists the server certificates stored in IAM that have the specified path prefix. .. versionadded:: ??? :param path_prefix: The path prefix for filtering the results. For example: /company/servercerts would get all server certificates for which the path starts with /company/servercerts . This parameter is optional. If it is not included, it defaults to a slash (/), listing all server certificates. This parameter allows (per its regex pattern) a string of characters consisting of either a forward slash (/) by itself or a string that must begin and end with forward slashes. In addition, it can contain any ASCII character from the ! (u0021) through the DEL character (u007F), including most punctuation characters, digits, and upper and lowercased letters. CLI Example: .. code-block:: bash salt myminion boto_iam.list_server_certificates path_prefix=/somepath/ ''' retries = 10 sleep = 6 conn = __utils__['boto3.get_connection']('iam', region=region, key=key, keyid=keyid, profile=profile) Items = [] while retries: try: log.debug('Garnering list of IAM Server Certificates') IsTruncated = True while IsTruncated: kwargs = {'PathPrefix': path_prefix} ret = conn.list_server_certificates(**kwargs) Items += ret.get('ServerCertificateMetadataList', []) IsTruncated = ret.get('IsTruncated') kwargs.update({'Marker': ret.get('Marker')}) return Items except botocore.exceptions.ParamValidationError as err: raise SaltInvocationError(str(err)) except botocore.exceptions.ClientError as err: if retries and jmespath.search('Error.Code', err.response) == 'Throttling': retries -= 1 log.debug('Throttled by AWS API, retrying in %s seconds...', sleep) time.sleep(sleep) continue log.error('Failed to list IAM Server Certificates: %s', err.message) return None def get_server_certificate(cert_name, region=None, key=None, keyid=None, profile=None): ''' Returns certificate information from Amazon .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_server_certificate mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_server_certificate(cert_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get certificate %s information.', cert_name) return False def delete_server_cert(cert_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a certificate from Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_server_cert mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_server_cert(cert_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete certificate %s.', cert_name) return False def export_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM user details. Produces results that can be used to create an sls file. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.export_users --out=txt | sed "s/local: //" > iam_users.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() users = get_all_users(path_prefix, region, key, keyid, profile) for user in users: name = user.user_name _policies = conn.get_all_user_policies(name, max_items=100) _policies = _policies.list_user_policies_response.list_user_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_user_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_user_policy_response.get_user_policy_result.policy_document )) policies[policy_name] = _policy user_sls = [] user_sls.append({"name": name}) user_sls.append({"policies": policies}) user_sls.append({"path": user.path}) results["manage user " + name] = {"boto_iam.user_present": user_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def export_roles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM role details. Produces results that can be used to create an sls file. CLI Example: salt-call boto_iam.export_roles --out=txt | sed "s/local: //" > iam_roles.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() roles = get_all_roles(path_prefix, region, key, keyid, profile) for role in roles: name = role.role_name _policies = conn.list_role_policies(name, max_items=100) _policies = _policies.list_role_policies_response.list_role_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_role_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_role_policy_response.get_role_policy_result.policy_document )) policies[policy_name] = _policy role_sls = [] role_sls.append({"name": name}) role_sls.append({"policies": policies}) role_sls.append({'policy_document': salt.utils.json.loads(_unquote(role.assume_role_policy_document))}) role_sls.append({"path": role.path}) results["manage role " + name] = {"boto_iam_role.present": role_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def _get_policy_arn(name, region=None, key=None, keyid=None, profile=None): if name.startswith('arn:aws:iam:'): return name account_id = get_account_id( region=region, key=key, keyid=keyid, profile=profile ) return 'arn:aws:iam::{0}:policy/{1}'.format(account_id, name) def policy_exists(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return True except boto.exception.BotoServerError: return False def get_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return ret.get('get_policy_response', {}).get('get_policy_result', {}) except boto.exception.BotoServerError: return None def create_policy(policy_name, policy_document, path=None, description=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in 'path', 'description': if locals()[arg] is not None: params[arg] = locals()[arg] if policy_exists(policy_name, region, key, keyid, profile): return True try: conn.create_policy(policy_name, policy_document, **params) log.info('Created IAM policy %s.', policy_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s.', policy_name) return False return True def delete_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_exists(policy_arn, region, key, keyid, profile): return True try: conn.delete_policy(policy_arn) log.info('Deleted %s policy.', policy_name) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete %s policy: %s.', policy_name, aws.get('message')) return False return True def list_policies(region=None, key=None, keyid=None, profile=None): ''' List policies. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policies ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: policies = [] for ret in __utils__['boto.paged_call'](conn.list_policies): policies.append(ret.get('list_policies_response', {}).get('list_policies_result', {}).get('policies')) return policies except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to list policy versions.' log.error(msg) return [] def policy_version_exists(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.get_policy_version(policy_arn, version_id) return True except boto.exception.BotoServerError: return False def get_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy_version(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile), version_id) retval = ret.get('get_policy_version_response', {}).get('get_policy_version_result', {}).get('policy_version', {}) retval['document'] = _unquote(retval.get('document')) return {'policy_version': retval} except boto.exception.BotoServerError: return None def create_policy_version(policy_name, policy_document, set_as_default=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy version. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy_version mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in ('set_as_default',): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.create_policy_version(policy_arn, policy_document, **params) vid = ret.get('create_policy_version_response', {}).get('create_policy_version_result', {}).get('policy_version', {}).get('version_id') log.info('Created IAM policy %s version %s.', policy_name, vid) return {'created': True, 'version_id': vid} except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s version %s.', policy_name, vid) return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Delete a policy version. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_version_exists(policy_arn, version_id, region, key, keyid, profile): return True try: conn.delete_policy_version(policy_arn, version_id) log.info('Deleted IAM policy %s version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete IAM policy %s version %s: %s', policy_name, version_id, aws.get('message')) return False return True def list_policy_versions(policy_name, region=None, key=None, keyid=None, profile=None): ''' List versions of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policy_versions mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.list_policy_versions(policy_arn) return ret.get('list_policy_versions_response', {}).get('list_policy_versions_result', {}).get('versions') except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list versions for IAM policy %s.', policy_name) return [] def set_default_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Set the default version of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.set_default_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.set_default_policy_version(policy_arn, version_id) log.info('Set %s policy to version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to set %s policy to version %s: %s', policy_name, version_id, aws.get('message')) return False return True def attach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_user_policy(policy_arn, user_name) log.info('Attached policy %s to IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach %s policy to IAM user %s.', policy_name, user_name) return False return True def detach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_user_policy(policy_arn, user_name) log.info('Detached %s policy from IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach %s policy from IAM user %s.', policy_name, user_name) return False return True def attach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_group_policy(policy_arn, group_name) log.info('Attached policy %s to IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM group %s.', policy_name, group_name) return False return True def detach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_group_policy(policy_arn, group_name) log.info('Detached policy %s from IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM group %s.', policy_name, group_name) return False return True def attach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_role_policy(policy_arn, role_name) log.info('Attached policy %s to IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM role %s.', policy_name, role_name) return False return True def detach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_role_policy(policy_arn, role_name) log.info('Detached policy %s from IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM role %s.', policy_name, role_name) return False return True def list_entities_for_policy(policy_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities that a policy is attached to. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 params = {} for arg in ('path_prefix', 'entity_filter'): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) while retries: try: allret = { 'policy_groups': [], 'policy_users': [], 'policy_roles': [], } for ret in __utils__['boto.paged_call'](conn.list_entities_for_policy, policy_arn=policy_arn, **params): for k, v in six.iteritems(allret): v.extend(ret.get('list_entities_for_policy_response', {}).get('list_entities_for_policy_result', {}).get(k)) return allret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('Failed to list entities for IAM policy %s: %s', policy_name, e.message) return {} return {} def list_attached_user_policies(user_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given user. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'UserName': user_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedUserPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_user_policies_response', {}).get('list_attached_user_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM user %s.', user_name) return [] def list_attached_group_policies(group_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given group. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'GroupName': group_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedGroupPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_group_policies_response', {}).get('list_attached_group_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM group %s.', group_name) return [] def list_attached_role_policies(role_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'RoleName': role_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedRolePolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_role_policies_response', {}).get('list_attached_role_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM role %s.', role_name) return [] def create_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Create SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.create_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_saml_provider(saml_metadata_document, name) log.info('Successfully created %s SAML provider.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to create SAML provider %s.', name) return False def get_saml_provider_arn(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider_arn my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_saml_providers() for saml_provider in response.list_saml_providers_response.list_saml_providers_result.saml_provider_list: if saml_provider['arn'].endswith(':saml-provider/' + name): return saml_provider['arn'] return False except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to get ARN of SAML provider %s.', name) return False def delete_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Delete SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.delete_saml_provider my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return True conn.delete_saml_provider(saml_provider_arn) log.info('Successfully deleted SAML provider %s.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete SAML provider %s.', name) return False def list_saml_providers(region=None, key=None, keyid=None, profile=None): ''' List SAML providers. CLI Example: .. code-block:: bash salt myminion boto_iam.list_saml_providers ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: providers = [] info = conn.list_saml_providers() for arn in info['list_saml_providers_response']['list_saml_providers_result']['saml_provider_list']: providers.append(arn['arn'].rsplit('/', 1)[1]) return providers except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get list of SAML providers.') return False def get_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider document. CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider arn ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: provider = conn.get_saml_provider(name) return provider['get_saml_provider_response']['get_saml_provider_result']['saml_metadata_document'] except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get SAML provider document %s.', name) return False def update_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Update SAML provider. CLI Example: .. code-block:: bash salt myminion boto_iam.update_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return False if conn.update_saml_provider(name, saml_metadata_document): return True return False except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to update SAML provider %s.', name) return False
saltstack/salt
salt/modules/boto_iam.py
get_all_access_keys
python
def get_all_access_keys(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all access keys from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_access_keys myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.get_all_access_keys(user_name, marker, max_items) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get access keys for IAM user %s.', user_name) return six.text_type(e)
Get all access keys from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_access_keys myuser
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iam.py#L240-L259
null
# -*- coding: utf-8 -*- ''' Connection module for Amazon IAM .. versionadded:: 2014.7.0 :configuration: This module accepts explicit iam 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 iam.keyid: GKTADJGHEIQSXMKKRBJ08H iam.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs iam.region: 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: boto ''' # keep lint from choking on _get_conn and _cache_id #pylint: disable=E0602 # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import salt libs from salt.ext import six import salt.utils.compat import salt.utils.json import salt.utils.odict as odict import salt.utils.versions from salt.exceptions import SaltInvocationError # Import third party libs # pylint: disable=unused-import from salt.ext.six.moves.urllib.parse import unquote as _unquote # pylint: disable=no-name-in-module try: import boto import boto.iam import boto3 import botocore logging.getLogger('boto').setLevel(logging.CRITICAL) logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=unused-import log = logging.getLogger(__name__) def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'iam', pack=__salt__) def instance_profile_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an instance profile exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: # Boto weirdly returns an exception here if an instance profile doesn't # exist. conn.get_instance_profile(name) return True except boto.exception.BotoServerError: return False def create_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Create an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.create_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if instance_profile_exists(name, region, key, keyid, profile): return True try: # This call returns an instance profile if successful and an exception # if not. It's annoying. conn.create_instance_profile(name) log.info('Created %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create %s instance profile.', name) return False return True def delete_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Delete an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not instance_profile_exists(name, region, key, keyid, profile): return True try: conn.delete_instance_profile(name) log.info('Deleted %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s instance profile.', name) return False return True def role_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an IAM role exists. CLI Example: .. code-block:: bash salt myminion boto_iam.role_exists myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_role(name) return True except boto.exception.BotoServerError: return False def describe_role(name, region=None, key=None, keyid=None, profile=None): ''' Get information for a role. CLI Example: .. code-block:: bash salt myminion boto_iam.describe_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_role(name) if not info: return False role = info.get_role_response.get_role_result.role role['assume_role_policy_document'] = salt.utils.json.loads(_unquote( role.assume_role_policy_document )) # If Sid wasn't defined by the user, boto will still return a Sid in # each policy. To properly check idempotently, let's remove the Sid # from the return if it's not actually set. for policy_key, policy in role['assume_role_policy_document'].items(): if policy_key == 'Statement': for val in policy: if 'Sid' in val and not val['Sid']: del val['Sid'] return role except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get %s information.', name) return False def create_user(user_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_user myuser ''' if not path: path = '/' if get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_user(user_name, path) log.info('Created IAM user : %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM user %s.', user_name) return False def create_access_key(user_name, region=None, key=None, keyid=None, profile=None): ''' Create access key id for a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.create_access_key(user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create access key.') return six.text_type(e) def delete_access_key(access_key_id, user_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete access key id from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_access_key(access_key_id, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete access key id %s.', access_key_id) return six.text_type(e) def delete_user(user_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user myuser ''' if not get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.delete_user(user_name) log.info('Deleted IAM user : %s .', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM user %s', user_name) return six.text_type(e) def get_user(user_name=None, region=None, key=None, keyid=None, profile=None): ''' Get user information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user(user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM user %s info.', user_name) return False def create_group(group_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_group group ''' if not path: path = '/' if get_group(group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_group(group_name, path) log.info('Created IAM group : %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM group %s.', group_name) return False def get_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group(group_name, max_items=1) if not info: return False return info['get_group_response']['get_group_result']['group'] except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_group_members(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: marker = None truncated = True users = [] while truncated: info = conn.get_group(group_name, marker=marker, max_items=1000) if not info: return False truncated = bool(info['get_group_response']['get_group_result']['is_truncated']) if truncated and 'marker' in info['get_group_response']['get_group_result']: marker = info['get_group_response']['get_group_result']['marker'] else: marker = None truncated = False users += info['get_group_response']['get_group_result']['users'] return users except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get members for IAM group %s.', group_name) return False def add_user_to_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Add user to group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.add_user_to_group myuser mygroup ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('Username : %s does not exist.', user_name) return False if user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.add_user_to_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add IAM user %s to group %s.', user_name, group_name) return False def user_exists_in_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Check if user exists in group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.user_exists_in_group myuser mygroup ''' # TODO this should probably use boto.iam.get_groups_for_user users = get_group_members( group_name=group_name, region=region, key=key, keyid=keyid, profile=profile ) if users: for _user in users: if user_name == _user['user_name']: log.debug('IAM user %s is already in IAM group %s.', user_name, group_name) return True return False def remove_user_from_group(group_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Remove user from group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.remove_user_from_group mygroup myuser ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist.', user_name) return False if not user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.remove_user_from_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove IAM user %s from group %s', user_name, group_name) return False def put_group_policy(group_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_group_policy mygroup policyname policyrules ''' group = get_group(group_name, region=region, key=key, keyid=keyid, profile=profile) if not group: log.error('Group %s does not exist', group_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_group_policy(group_name, policy_name, policy_json) if created: log.info('Created policy for IAM group %s.', group_name) return True log.error('Could not create policy for IAM group %s', group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy for IAM group %s', group_name) return False def delete_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group_policy mygroup mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_group_policy( group_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_group_policy(group_name, policy_name) log.info('Successfully deleted policy %s for IAM group %s.', policy_name, group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM group %s.', policy_name, group_name) return False def get_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group_policy mygroup policyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group_policy(group_name, policy_name) log.debug('info for group policy is : %s', info) if not info: return False info = info.get_group_policy_response.get_group_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_all_groups(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM group details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_groups ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _groups = conn.get_all_groups(path_prefix=path_prefix) groups = _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) while marker: _groups = conn.get_all_groups(path_prefix=path_prefix, marker=marker) groups = groups + _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) return groups def get_all_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.get_all_instance_profiles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) marker = False profiles = [] while marker is not None: marker = marker if marker else None p = conn.list_instance_profiles(path_prefix=path_prefix, marker=marker) res = p.list_instance_profiles_response.list_instance_profiles_result profiles += res.instance_profiles marker = getattr(res, 'marker', None) return profiles def list_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' List all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.list_instance_profiles ''' p = get_all_instance_profiles(path_prefix, region, key, keyid, profile) return [i['instance_profile_name'] for i in p] def get_all_group_policies(group_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a group. CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_group_policies mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False try: response = conn.get_all_group_policies(group_name) _list = response.list_group_policies_response.list_group_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def delete_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _group = get_group( group_name, region, key, keyid, profile ) if not _group: return True try: conn.delete_group(group_name) log.info('Successfully deleted IAM group %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM group %s.', group_name) return False def create_login_profile(user_name, password, region=None, key=None, keyid=None, profile=None): ''' Creates a login profile for the specified user, give the user the ability to access AWS services and the AWS Management Console. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_login_profile user_name password ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.create_login_profile(user_name, password) log.info('Created profile for IAM user %s.', user_name) return info except boto.exception.BotoServerError as e: log.debug(e) if 'Conflict' in e: log.info('Profile already exists for IAM user %s.', user_name) return 'Conflict' log.error('Failed to update profile for IAM user %s.', user_name) return False def delete_login_profile(user_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a login profile for the specified user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_login_profile user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.delete_login_profile(user_name) log.info('Deleted login profile for IAM user %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Login profile already deleted for IAM user %s.', user_name) return True log.error('Failed to delete login profile for IAM user %s.', user_name) return False def get_all_mfa_devices(user_name, region=None, key=None, keyid=None, profile=None): ''' Get all MFA devices associated with an IAM user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_mfa_devices user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: result = conn.get_all_mfa_devices(user_name) devices = result['list_mfa_devices_response']['list_mfa_devices_result']['mfa_devices'] return devices except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Could not find IAM user %s.', user_name) return [] log.error('Failed to get all MFA devices for IAM user %s.', user_name) return False def deactivate_mfa_device(user_name, serial, region=None, key=None, keyid=None, profile=None): ''' Deactivates the specified MFA device and removes it from association with the user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.deactivate_mfa_device user_name serial_num ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.deactivate_mfa_device(user_name, serial) log.info('Deactivated MFA device %s for IAM user %s.', serial, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('MFA device %s not associated with IAM user %s.', serial, user_name) return True log.error('Failed to deactivate MFA device %s for IAM user %s.', serial, user_name) return False def delete_virtual_mfa_device(serial, region=None, key=None, keyid=None, profile=None): ''' Deletes the specified virtual MFA device. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_virtual_mfa_device serial_num ''' conn = __utils__['boto3.get_connection_func']('iam')() try: conn.delete_virtual_mfa_device(SerialNumber=serial) log.info('Deleted virtual MFA device %s.', serial) return True except botocore.exceptions.ClientError as e: log.debug(e) if 'NoSuchEntity' in six.text_type(e): log.info('Virtual MFA device %s not found.', serial) return True log.error('Failed to delete virtual MFA device %s.', serial) return False def update_account_password_policy(allow_users_to_change_password=None, hard_expiry=None, max_password_age=None, minimum_password_length=None, password_reuse_prevention=None, require_lowercase_characters=None, require_numbers=None, require_symbols=None, require_uppercase_characters=None, region=None, key=None, keyid=None, profile=None): ''' Update the password policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_account_password_policy True ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.update_account_password_policy(allow_users_to_change_password, hard_expiry, max_password_age, minimum_password_length, password_reuse_prevention, require_lowercase_characters, require_numbers, require_symbols, require_uppercase_characters) log.info('The password policy has been updated.') return True except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy' log.error(msg) return False def get_account_policy(region=None, key=None, keyid=None, profile=None): ''' Get account policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_account_password_policy() return info.get_account_password_policy_response.get_account_password_policy_result.password_policy except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy.' log.error(msg) return False def create_role(name, policy_document=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Create an instance role. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if role_exists(name, region, key, keyid, profile): return True if not policy_document: policy_document = None try: conn.create_role(name, assume_role_policy_document=policy_document, path=path) log.info('Created IAM role %s.', name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to create IAM role %s.', name) return False def delete_role(name, region=None, key=None, keyid=None, profile=None): ''' Delete an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(name, region, key, keyid, profile): return True try: conn.delete_role(name) log.info('Deleted %s IAM role.', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s IAM role.', name) return False def profile_associated(role_name, profile_name, region, key, keyid, profile): ''' Check to see if an instance profile is associated with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.profile_associated myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # The IAM module of boto doesn't return objects. Instead you need to grab # values through its properties. Sigh. try: profiles = conn.list_instance_profiles_for_role(role_name) except boto.exception.BotoServerError as e: log.debug(e) return False profiles = profiles.list_instance_profiles_for_role_response profiles = profiles.list_instance_profiles_for_role_result profiles = profiles.instance_profiles for profile in profiles: if profile.instance_profile_name == profile_name: return True return False def associate_profile_to_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Associate an instance profile with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.associate_profile_to_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if associated: return True else: try: conn.add_role_to_instance_profile(profile_name, role_name) log.info('Added %s instance profile to IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add %s instance profile to IAM role %s', profile_name, role_name) return False def disassociate_profile_from_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Disassociate an instance profile from an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.disassociate_profile_from_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if not associated: return True else: try: conn.remove_role_from_instance_profile(profile_name, role_name) log.info('Removed %s instance profile from IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove %s instance profile from IAM role %s.', profile_name, role_name) return False def list_role_policies(role_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_role_policies myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_role_policies(role_name) _list = response.list_role_policies_response.list_role_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def get_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.get_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: _policy = conn.get_role_policy(role_name, policy_name) # I _hate_ you for not giving me an object boto. _policy = _policy.get_role_policy_response.policy_document # Policy is url encoded _policy = _unquote(_policy) _policy = salt.utils.json.loads(_policy, object_pairs_hook=odict.OrderedDict) return _policy except boto.exception.BotoServerError: return {} def create_role_policy(role_name, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Create or modify a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role_policy myirole mypolicy '{"MyPolicy": "Statement": [{"Action": ["sqs:*"], "Effect": "Allow", "Resource": ["arn:aws:sqs:*:*:*"], "Sid": "MyPolicySqs1"}]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) mode = 'create' if _policy: if _policy == policy: return True mode = 'modify' if isinstance(policy, six.string_types): policy = salt.utils.json.loads(policy, object_pairs_hook=odict.OrderedDict) try: _policy = salt.utils.json.dumps(policy) conn.put_role_policy(role_name, policy_name, _policy) if mode == 'create': msg = 'Successfully added policy %s to IAM role %s.' else: msg = 'Successfully modified policy %s for IAM role %s.' log.info(msg, policy_name, role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to %s policy %s for IAM role %s.', mode, policy_name, role_name) return False def delete_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) if not _policy: return True try: conn.delete_role_policy(role_name, policy_name) log.info('Successfully deleted policy %s for IAM role %s.', policy_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM role %s.', policy_name, role_name) return False def update_assume_role_policy(role_name, policy_document, region=None, key=None, keyid=None, profile=None): ''' Update an assume role policy for a role. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_assume_role_policy myrole '{"Statement":"..."}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(policy_document, six.string_types): policy_document = salt.utils.json.loads(policy_document, object_pairs_hook=odict.OrderedDict) try: _policy_document = salt.utils.json.dumps(policy_document) conn.update_assume_role_policy(role_name, _policy_document) log.info('Successfully updated assume role policy for IAM role %s.', role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to update assume role policy for IAM role %s.', role_name) return False def build_policy(region=None, key=None, keyid=None, profile=None): ''' Build a default assume role policy. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.build_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if hasattr(conn, 'build_policy'): policy = salt.utils.json.loads(conn.build_policy()) elif hasattr(conn, '_build_policy'): policy = salt.utils.json.loads(conn._build_policy()) else: return {} # The format we get from build_policy isn't going to be what we get back # from AWS for the exact same policy. AWS converts single item list values # into strings, so let's do the same here. for key, policy_val in policy.items(): for statement in policy_val: if (isinstance(statement['Action'], list) and len(statement['Action']) == 1): statement['Action'] = statement['Action'][0] if (isinstance(statement['Principal']['Service'], list) and len(statement['Principal']['Service']) == 1): statement['Principal']['Service'] = statement['Principal']['Service'][0] # build_policy doesn't add a version field, which AWS is going to set to a # default value, when we get it back, so let's set it. policy['Version'] = '2008-10-17' return policy def get_account_id(region=None, key=None, keyid=None, profile=None): ''' Get a the AWS account id associated with the used credentials. CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_id ''' cache_key = 'boto_iam.account_id' if cache_key not in __context__: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_user() # The get_user call returns an user ARN: # arn:aws:iam::027050522557:user/salt-test arn = ret['get_user_response']['get_user_result']['user']['arn'] account_id = arn.split(':')[4] except boto.exception.BotoServerError: # If call failed, then let's try to get the ARN from the metadata timeout = boto.config.getfloat( 'Boto', 'metadata_service_timeout', 1.0 ) attempts = boto.config.getint( 'Boto', 'metadata_service_num_attempts', 1 ) identity = boto.utils.get_instance_identity( timeout=timeout, num_retries=attempts ) try: account_id = identity['document']['accountId'] except KeyError: log.error('Failed to get account id from instance_identity in' ' boto_iam.get_account_id.') __context__[cache_key] = account_id return __context__[cache_key] def get_all_roles(path_prefix=None, region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM role details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_roles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _roles = conn.list_roles(path_prefix=path_prefix) roles = _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) while marker: _roles = conn.list_roles(path_prefix=path_prefix, marker=marker) roles = roles + _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) return roles def get_all_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM user details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_users ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _users = conn.get_all_users(path_prefix=path_prefix) users = _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) while marker: _users = conn.get_all_users(path_prefix=path_prefix, marker=marker) users = users + _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) return users def get_all_user_policies(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all user policies. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_user_policies myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_all_user_policies(user_name, marker, max_items) if not info: return False _list = info.list_user_policies_response.list_user_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policies for user %s.', user_name) return False def get_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user_policy myuser mypolicyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user_policy(user_name, policy_name) log.debug('Info for IAM user %s policy %s: %s.', user_name, policy_name, info) if not info: return False info = info.get_user_policy_response.get_user_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policy %s for IAM user %s.', policy_name, user_name) return False def put_user_policy(user_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_user_policy myuser policyname policyrules ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_user_policy(user_name, policy_name, policy_json) if created: log.info('Created policy %s for IAM user %s.', policy_name, user_name) return True log.error('Could not create policy %s for IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy %s for IAM user %s.', policy_name, user_name) return False def delete_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user_policy myuser mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_user_policy( user_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_user_policy(user_name, policy_name) log.info('Successfully deleted policy %s for IAM user %s.', policy_name, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM user %s.', policy_name, user_name) return False def upload_server_cert(cert_name, cert_body, private_key, cert_chain=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Upload a certificate to Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.upload_server_cert mycert_name crt priv_key :param cert_name: The name for the server certificate. Do not include the path in this value. :param cert_body: The contents of the public key certificate in PEM-encoded format. :param private_key: The contents of the private key in PEM-encoded format. :param cert_chain: The contents of the certificate chain. This is typically a concatenation of the PEM-encoded public key certificates of the chain. :param path: The path for the server certificate. :param region: The name of the region to connect to. :param key: The key to be used in order to connect :param keyid: The keyid to be used in order to connect :param profile: The profile that contains a dict of region, key, keyid :return: True / False ''' exists = get_server_certificate(cert_name, region, key, keyid, profile) if exists: return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.upload_server_cert(cert_name, cert_body, private_key, cert_chain) log.info('Created certificate %s.', cert_name) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to failed to create certificate %s.', cert_name) return False def list_server_certificates(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Lists the server certificates stored in IAM that have the specified path prefix. .. versionadded:: ??? :param path_prefix: The path prefix for filtering the results. For example: /company/servercerts would get all server certificates for which the path starts with /company/servercerts . This parameter is optional. If it is not included, it defaults to a slash (/), listing all server certificates. This parameter allows (per its regex pattern) a string of characters consisting of either a forward slash (/) by itself or a string that must begin and end with forward slashes. In addition, it can contain any ASCII character from the ! (u0021) through the DEL character (u007F), including most punctuation characters, digits, and upper and lowercased letters. CLI Example: .. code-block:: bash salt myminion boto_iam.list_server_certificates path_prefix=/somepath/ ''' retries = 10 sleep = 6 conn = __utils__['boto3.get_connection']('iam', region=region, key=key, keyid=keyid, profile=profile) Items = [] while retries: try: log.debug('Garnering list of IAM Server Certificates') IsTruncated = True while IsTruncated: kwargs = {'PathPrefix': path_prefix} ret = conn.list_server_certificates(**kwargs) Items += ret.get('ServerCertificateMetadataList', []) IsTruncated = ret.get('IsTruncated') kwargs.update({'Marker': ret.get('Marker')}) return Items except botocore.exceptions.ParamValidationError as err: raise SaltInvocationError(str(err)) except botocore.exceptions.ClientError as err: if retries and jmespath.search('Error.Code', err.response) == 'Throttling': retries -= 1 log.debug('Throttled by AWS API, retrying in %s seconds...', sleep) time.sleep(sleep) continue log.error('Failed to list IAM Server Certificates: %s', err.message) return None def get_server_certificate(cert_name, region=None, key=None, keyid=None, profile=None): ''' Returns certificate information from Amazon .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_server_certificate mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_server_certificate(cert_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get certificate %s information.', cert_name) return False def delete_server_cert(cert_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a certificate from Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_server_cert mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_server_cert(cert_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete certificate %s.', cert_name) return False def export_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM user details. Produces results that can be used to create an sls file. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.export_users --out=txt | sed "s/local: //" > iam_users.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() users = get_all_users(path_prefix, region, key, keyid, profile) for user in users: name = user.user_name _policies = conn.get_all_user_policies(name, max_items=100) _policies = _policies.list_user_policies_response.list_user_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_user_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_user_policy_response.get_user_policy_result.policy_document )) policies[policy_name] = _policy user_sls = [] user_sls.append({"name": name}) user_sls.append({"policies": policies}) user_sls.append({"path": user.path}) results["manage user " + name] = {"boto_iam.user_present": user_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def export_roles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM role details. Produces results that can be used to create an sls file. CLI Example: salt-call boto_iam.export_roles --out=txt | sed "s/local: //" > iam_roles.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() roles = get_all_roles(path_prefix, region, key, keyid, profile) for role in roles: name = role.role_name _policies = conn.list_role_policies(name, max_items=100) _policies = _policies.list_role_policies_response.list_role_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_role_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_role_policy_response.get_role_policy_result.policy_document )) policies[policy_name] = _policy role_sls = [] role_sls.append({"name": name}) role_sls.append({"policies": policies}) role_sls.append({'policy_document': salt.utils.json.loads(_unquote(role.assume_role_policy_document))}) role_sls.append({"path": role.path}) results["manage role " + name] = {"boto_iam_role.present": role_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def _get_policy_arn(name, region=None, key=None, keyid=None, profile=None): if name.startswith('arn:aws:iam:'): return name account_id = get_account_id( region=region, key=key, keyid=keyid, profile=profile ) return 'arn:aws:iam::{0}:policy/{1}'.format(account_id, name) def policy_exists(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return True except boto.exception.BotoServerError: return False def get_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return ret.get('get_policy_response', {}).get('get_policy_result', {}) except boto.exception.BotoServerError: return None def create_policy(policy_name, policy_document, path=None, description=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in 'path', 'description': if locals()[arg] is not None: params[arg] = locals()[arg] if policy_exists(policy_name, region, key, keyid, profile): return True try: conn.create_policy(policy_name, policy_document, **params) log.info('Created IAM policy %s.', policy_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s.', policy_name) return False return True def delete_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_exists(policy_arn, region, key, keyid, profile): return True try: conn.delete_policy(policy_arn) log.info('Deleted %s policy.', policy_name) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete %s policy: %s.', policy_name, aws.get('message')) return False return True def list_policies(region=None, key=None, keyid=None, profile=None): ''' List policies. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policies ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: policies = [] for ret in __utils__['boto.paged_call'](conn.list_policies): policies.append(ret.get('list_policies_response', {}).get('list_policies_result', {}).get('policies')) return policies except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to list policy versions.' log.error(msg) return [] def policy_version_exists(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.get_policy_version(policy_arn, version_id) return True except boto.exception.BotoServerError: return False def get_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy_version(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile), version_id) retval = ret.get('get_policy_version_response', {}).get('get_policy_version_result', {}).get('policy_version', {}) retval['document'] = _unquote(retval.get('document')) return {'policy_version': retval} except boto.exception.BotoServerError: return None def create_policy_version(policy_name, policy_document, set_as_default=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy version. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy_version mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in ('set_as_default',): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.create_policy_version(policy_arn, policy_document, **params) vid = ret.get('create_policy_version_response', {}).get('create_policy_version_result', {}).get('policy_version', {}).get('version_id') log.info('Created IAM policy %s version %s.', policy_name, vid) return {'created': True, 'version_id': vid} except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s version %s.', policy_name, vid) return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Delete a policy version. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_version_exists(policy_arn, version_id, region, key, keyid, profile): return True try: conn.delete_policy_version(policy_arn, version_id) log.info('Deleted IAM policy %s version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete IAM policy %s version %s: %s', policy_name, version_id, aws.get('message')) return False return True def list_policy_versions(policy_name, region=None, key=None, keyid=None, profile=None): ''' List versions of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policy_versions mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.list_policy_versions(policy_arn) return ret.get('list_policy_versions_response', {}).get('list_policy_versions_result', {}).get('versions') except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list versions for IAM policy %s.', policy_name) return [] def set_default_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Set the default version of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.set_default_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.set_default_policy_version(policy_arn, version_id) log.info('Set %s policy to version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to set %s policy to version %s: %s', policy_name, version_id, aws.get('message')) return False return True def attach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_user_policy(policy_arn, user_name) log.info('Attached policy %s to IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach %s policy to IAM user %s.', policy_name, user_name) return False return True def detach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_user_policy(policy_arn, user_name) log.info('Detached %s policy from IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach %s policy from IAM user %s.', policy_name, user_name) return False return True def attach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_group_policy(policy_arn, group_name) log.info('Attached policy %s to IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM group %s.', policy_name, group_name) return False return True def detach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_group_policy(policy_arn, group_name) log.info('Detached policy %s from IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM group %s.', policy_name, group_name) return False return True def attach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_role_policy(policy_arn, role_name) log.info('Attached policy %s to IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM role %s.', policy_name, role_name) return False return True def detach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_role_policy(policy_arn, role_name) log.info('Detached policy %s from IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM role %s.', policy_name, role_name) return False return True def list_entities_for_policy(policy_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities that a policy is attached to. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 params = {} for arg in ('path_prefix', 'entity_filter'): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) while retries: try: allret = { 'policy_groups': [], 'policy_users': [], 'policy_roles': [], } for ret in __utils__['boto.paged_call'](conn.list_entities_for_policy, policy_arn=policy_arn, **params): for k, v in six.iteritems(allret): v.extend(ret.get('list_entities_for_policy_response', {}).get('list_entities_for_policy_result', {}).get(k)) return allret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('Failed to list entities for IAM policy %s: %s', policy_name, e.message) return {} return {} def list_attached_user_policies(user_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given user. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'UserName': user_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedUserPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_user_policies_response', {}).get('list_attached_user_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM user %s.', user_name) return [] def list_attached_group_policies(group_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given group. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'GroupName': group_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedGroupPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_group_policies_response', {}).get('list_attached_group_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM group %s.', group_name) return [] def list_attached_role_policies(role_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'RoleName': role_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedRolePolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_role_policies_response', {}).get('list_attached_role_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM role %s.', role_name) return [] def create_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Create SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.create_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_saml_provider(saml_metadata_document, name) log.info('Successfully created %s SAML provider.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to create SAML provider %s.', name) return False def get_saml_provider_arn(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider_arn my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_saml_providers() for saml_provider in response.list_saml_providers_response.list_saml_providers_result.saml_provider_list: if saml_provider['arn'].endswith(':saml-provider/' + name): return saml_provider['arn'] return False except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to get ARN of SAML provider %s.', name) return False def delete_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Delete SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.delete_saml_provider my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return True conn.delete_saml_provider(saml_provider_arn) log.info('Successfully deleted SAML provider %s.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete SAML provider %s.', name) return False def list_saml_providers(region=None, key=None, keyid=None, profile=None): ''' List SAML providers. CLI Example: .. code-block:: bash salt myminion boto_iam.list_saml_providers ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: providers = [] info = conn.list_saml_providers() for arn in info['list_saml_providers_response']['list_saml_providers_result']['saml_provider_list']: providers.append(arn['arn'].rsplit('/', 1)[1]) return providers except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get list of SAML providers.') return False def get_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider document. CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider arn ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: provider = conn.get_saml_provider(name) return provider['get_saml_provider_response']['get_saml_provider_result']['saml_metadata_document'] except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get SAML provider document %s.', name) return False def update_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Update SAML provider. CLI Example: .. code-block:: bash salt myminion boto_iam.update_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return False if conn.update_saml_provider(name, saml_metadata_document): return True return False except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to update SAML provider %s.', name) return False
saltstack/salt
salt/modules/boto_iam.py
delete_user
python
def delete_user(user_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user myuser ''' if not get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.delete_user(user_name) log.info('Deleted IAM user : %s .', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM user %s', user_name) return six.text_type(e)
Delete a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user myuser
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iam.py#L305-L328
[ "def get_user(user_name=None, region=None, key=None, keyid=None, profile=None):\n '''\n Get user information.\n\n .. versionadded:: 2015.8.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_iam.get_user myuser\n '''\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n try:\n info = conn.get_user(user_name)\n if not info:\n return False\n return info\n except boto.exception.BotoServerError as e:\n log.debug(e)\n log.error('Failed to get IAM user %s info.', user_name)\n return False\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon IAM .. versionadded:: 2014.7.0 :configuration: This module accepts explicit iam 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 iam.keyid: GKTADJGHEIQSXMKKRBJ08H iam.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs iam.region: 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: boto ''' # keep lint from choking on _get_conn and _cache_id #pylint: disable=E0602 # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import salt libs from salt.ext import six import salt.utils.compat import salt.utils.json import salt.utils.odict as odict import salt.utils.versions from salt.exceptions import SaltInvocationError # Import third party libs # pylint: disable=unused-import from salt.ext.six.moves.urllib.parse import unquote as _unquote # pylint: disable=no-name-in-module try: import boto import boto.iam import boto3 import botocore logging.getLogger('boto').setLevel(logging.CRITICAL) logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=unused-import log = logging.getLogger(__name__) def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'iam', pack=__salt__) def instance_profile_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an instance profile exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: # Boto weirdly returns an exception here if an instance profile doesn't # exist. conn.get_instance_profile(name) return True except boto.exception.BotoServerError: return False def create_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Create an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.create_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if instance_profile_exists(name, region, key, keyid, profile): return True try: # This call returns an instance profile if successful and an exception # if not. It's annoying. conn.create_instance_profile(name) log.info('Created %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create %s instance profile.', name) return False return True def delete_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Delete an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not instance_profile_exists(name, region, key, keyid, profile): return True try: conn.delete_instance_profile(name) log.info('Deleted %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s instance profile.', name) return False return True def role_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an IAM role exists. CLI Example: .. code-block:: bash salt myminion boto_iam.role_exists myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_role(name) return True except boto.exception.BotoServerError: return False def describe_role(name, region=None, key=None, keyid=None, profile=None): ''' Get information for a role. CLI Example: .. code-block:: bash salt myminion boto_iam.describe_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_role(name) if not info: return False role = info.get_role_response.get_role_result.role role['assume_role_policy_document'] = salt.utils.json.loads(_unquote( role.assume_role_policy_document )) # If Sid wasn't defined by the user, boto will still return a Sid in # each policy. To properly check idempotently, let's remove the Sid # from the return if it's not actually set. for policy_key, policy in role['assume_role_policy_document'].items(): if policy_key == 'Statement': for val in policy: if 'Sid' in val and not val['Sid']: del val['Sid'] return role except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get %s information.', name) return False def create_user(user_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_user myuser ''' if not path: path = '/' if get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_user(user_name, path) log.info('Created IAM user : %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM user %s.', user_name) return False def get_all_access_keys(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all access keys from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_access_keys myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.get_all_access_keys(user_name, marker, max_items) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get access keys for IAM user %s.', user_name) return six.text_type(e) def create_access_key(user_name, region=None, key=None, keyid=None, profile=None): ''' Create access key id for a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.create_access_key(user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create access key.') return six.text_type(e) def delete_access_key(access_key_id, user_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete access key id from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_access_key(access_key_id, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete access key id %s.', access_key_id) return six.text_type(e) def get_user(user_name=None, region=None, key=None, keyid=None, profile=None): ''' Get user information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user(user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM user %s info.', user_name) return False def create_group(group_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_group group ''' if not path: path = '/' if get_group(group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_group(group_name, path) log.info('Created IAM group : %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM group %s.', group_name) return False def get_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group(group_name, max_items=1) if not info: return False return info['get_group_response']['get_group_result']['group'] except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_group_members(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: marker = None truncated = True users = [] while truncated: info = conn.get_group(group_name, marker=marker, max_items=1000) if not info: return False truncated = bool(info['get_group_response']['get_group_result']['is_truncated']) if truncated and 'marker' in info['get_group_response']['get_group_result']: marker = info['get_group_response']['get_group_result']['marker'] else: marker = None truncated = False users += info['get_group_response']['get_group_result']['users'] return users except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get members for IAM group %s.', group_name) return False def add_user_to_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Add user to group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.add_user_to_group myuser mygroup ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('Username : %s does not exist.', user_name) return False if user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.add_user_to_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add IAM user %s to group %s.', user_name, group_name) return False def user_exists_in_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Check if user exists in group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.user_exists_in_group myuser mygroup ''' # TODO this should probably use boto.iam.get_groups_for_user users = get_group_members( group_name=group_name, region=region, key=key, keyid=keyid, profile=profile ) if users: for _user in users: if user_name == _user['user_name']: log.debug('IAM user %s is already in IAM group %s.', user_name, group_name) return True return False def remove_user_from_group(group_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Remove user from group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.remove_user_from_group mygroup myuser ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist.', user_name) return False if not user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.remove_user_from_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove IAM user %s from group %s', user_name, group_name) return False def put_group_policy(group_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_group_policy mygroup policyname policyrules ''' group = get_group(group_name, region=region, key=key, keyid=keyid, profile=profile) if not group: log.error('Group %s does not exist', group_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_group_policy(group_name, policy_name, policy_json) if created: log.info('Created policy for IAM group %s.', group_name) return True log.error('Could not create policy for IAM group %s', group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy for IAM group %s', group_name) return False def delete_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group_policy mygroup mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_group_policy( group_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_group_policy(group_name, policy_name) log.info('Successfully deleted policy %s for IAM group %s.', policy_name, group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM group %s.', policy_name, group_name) return False def get_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group_policy mygroup policyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group_policy(group_name, policy_name) log.debug('info for group policy is : %s', info) if not info: return False info = info.get_group_policy_response.get_group_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_all_groups(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM group details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_groups ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _groups = conn.get_all_groups(path_prefix=path_prefix) groups = _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) while marker: _groups = conn.get_all_groups(path_prefix=path_prefix, marker=marker) groups = groups + _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) return groups def get_all_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.get_all_instance_profiles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) marker = False profiles = [] while marker is not None: marker = marker if marker else None p = conn.list_instance_profiles(path_prefix=path_prefix, marker=marker) res = p.list_instance_profiles_response.list_instance_profiles_result profiles += res.instance_profiles marker = getattr(res, 'marker', None) return profiles def list_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' List all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.list_instance_profiles ''' p = get_all_instance_profiles(path_prefix, region, key, keyid, profile) return [i['instance_profile_name'] for i in p] def get_all_group_policies(group_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a group. CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_group_policies mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False try: response = conn.get_all_group_policies(group_name) _list = response.list_group_policies_response.list_group_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def delete_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _group = get_group( group_name, region, key, keyid, profile ) if not _group: return True try: conn.delete_group(group_name) log.info('Successfully deleted IAM group %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM group %s.', group_name) return False def create_login_profile(user_name, password, region=None, key=None, keyid=None, profile=None): ''' Creates a login profile for the specified user, give the user the ability to access AWS services and the AWS Management Console. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_login_profile user_name password ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.create_login_profile(user_name, password) log.info('Created profile for IAM user %s.', user_name) return info except boto.exception.BotoServerError as e: log.debug(e) if 'Conflict' in e: log.info('Profile already exists for IAM user %s.', user_name) return 'Conflict' log.error('Failed to update profile for IAM user %s.', user_name) return False def delete_login_profile(user_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a login profile for the specified user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_login_profile user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.delete_login_profile(user_name) log.info('Deleted login profile for IAM user %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Login profile already deleted for IAM user %s.', user_name) return True log.error('Failed to delete login profile for IAM user %s.', user_name) return False def get_all_mfa_devices(user_name, region=None, key=None, keyid=None, profile=None): ''' Get all MFA devices associated with an IAM user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_mfa_devices user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: result = conn.get_all_mfa_devices(user_name) devices = result['list_mfa_devices_response']['list_mfa_devices_result']['mfa_devices'] return devices except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Could not find IAM user %s.', user_name) return [] log.error('Failed to get all MFA devices for IAM user %s.', user_name) return False def deactivate_mfa_device(user_name, serial, region=None, key=None, keyid=None, profile=None): ''' Deactivates the specified MFA device and removes it from association with the user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.deactivate_mfa_device user_name serial_num ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.deactivate_mfa_device(user_name, serial) log.info('Deactivated MFA device %s for IAM user %s.', serial, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('MFA device %s not associated with IAM user %s.', serial, user_name) return True log.error('Failed to deactivate MFA device %s for IAM user %s.', serial, user_name) return False def delete_virtual_mfa_device(serial, region=None, key=None, keyid=None, profile=None): ''' Deletes the specified virtual MFA device. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_virtual_mfa_device serial_num ''' conn = __utils__['boto3.get_connection_func']('iam')() try: conn.delete_virtual_mfa_device(SerialNumber=serial) log.info('Deleted virtual MFA device %s.', serial) return True except botocore.exceptions.ClientError as e: log.debug(e) if 'NoSuchEntity' in six.text_type(e): log.info('Virtual MFA device %s not found.', serial) return True log.error('Failed to delete virtual MFA device %s.', serial) return False def update_account_password_policy(allow_users_to_change_password=None, hard_expiry=None, max_password_age=None, minimum_password_length=None, password_reuse_prevention=None, require_lowercase_characters=None, require_numbers=None, require_symbols=None, require_uppercase_characters=None, region=None, key=None, keyid=None, profile=None): ''' Update the password policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_account_password_policy True ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.update_account_password_policy(allow_users_to_change_password, hard_expiry, max_password_age, minimum_password_length, password_reuse_prevention, require_lowercase_characters, require_numbers, require_symbols, require_uppercase_characters) log.info('The password policy has been updated.') return True except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy' log.error(msg) return False def get_account_policy(region=None, key=None, keyid=None, profile=None): ''' Get account policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_account_password_policy() return info.get_account_password_policy_response.get_account_password_policy_result.password_policy except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy.' log.error(msg) return False def create_role(name, policy_document=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Create an instance role. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if role_exists(name, region, key, keyid, profile): return True if not policy_document: policy_document = None try: conn.create_role(name, assume_role_policy_document=policy_document, path=path) log.info('Created IAM role %s.', name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to create IAM role %s.', name) return False def delete_role(name, region=None, key=None, keyid=None, profile=None): ''' Delete an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(name, region, key, keyid, profile): return True try: conn.delete_role(name) log.info('Deleted %s IAM role.', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s IAM role.', name) return False def profile_associated(role_name, profile_name, region, key, keyid, profile): ''' Check to see if an instance profile is associated with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.profile_associated myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # The IAM module of boto doesn't return objects. Instead you need to grab # values through its properties. Sigh. try: profiles = conn.list_instance_profiles_for_role(role_name) except boto.exception.BotoServerError as e: log.debug(e) return False profiles = profiles.list_instance_profiles_for_role_response profiles = profiles.list_instance_profiles_for_role_result profiles = profiles.instance_profiles for profile in profiles: if profile.instance_profile_name == profile_name: return True return False def associate_profile_to_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Associate an instance profile with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.associate_profile_to_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if associated: return True else: try: conn.add_role_to_instance_profile(profile_name, role_name) log.info('Added %s instance profile to IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add %s instance profile to IAM role %s', profile_name, role_name) return False def disassociate_profile_from_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Disassociate an instance profile from an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.disassociate_profile_from_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if not associated: return True else: try: conn.remove_role_from_instance_profile(profile_name, role_name) log.info('Removed %s instance profile from IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove %s instance profile from IAM role %s.', profile_name, role_name) return False def list_role_policies(role_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_role_policies myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_role_policies(role_name) _list = response.list_role_policies_response.list_role_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def get_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.get_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: _policy = conn.get_role_policy(role_name, policy_name) # I _hate_ you for not giving me an object boto. _policy = _policy.get_role_policy_response.policy_document # Policy is url encoded _policy = _unquote(_policy) _policy = salt.utils.json.loads(_policy, object_pairs_hook=odict.OrderedDict) return _policy except boto.exception.BotoServerError: return {} def create_role_policy(role_name, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Create or modify a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role_policy myirole mypolicy '{"MyPolicy": "Statement": [{"Action": ["sqs:*"], "Effect": "Allow", "Resource": ["arn:aws:sqs:*:*:*"], "Sid": "MyPolicySqs1"}]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) mode = 'create' if _policy: if _policy == policy: return True mode = 'modify' if isinstance(policy, six.string_types): policy = salt.utils.json.loads(policy, object_pairs_hook=odict.OrderedDict) try: _policy = salt.utils.json.dumps(policy) conn.put_role_policy(role_name, policy_name, _policy) if mode == 'create': msg = 'Successfully added policy %s to IAM role %s.' else: msg = 'Successfully modified policy %s for IAM role %s.' log.info(msg, policy_name, role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to %s policy %s for IAM role %s.', mode, policy_name, role_name) return False def delete_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) if not _policy: return True try: conn.delete_role_policy(role_name, policy_name) log.info('Successfully deleted policy %s for IAM role %s.', policy_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM role %s.', policy_name, role_name) return False def update_assume_role_policy(role_name, policy_document, region=None, key=None, keyid=None, profile=None): ''' Update an assume role policy for a role. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_assume_role_policy myrole '{"Statement":"..."}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(policy_document, six.string_types): policy_document = salt.utils.json.loads(policy_document, object_pairs_hook=odict.OrderedDict) try: _policy_document = salt.utils.json.dumps(policy_document) conn.update_assume_role_policy(role_name, _policy_document) log.info('Successfully updated assume role policy for IAM role %s.', role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to update assume role policy for IAM role %s.', role_name) return False def build_policy(region=None, key=None, keyid=None, profile=None): ''' Build a default assume role policy. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.build_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if hasattr(conn, 'build_policy'): policy = salt.utils.json.loads(conn.build_policy()) elif hasattr(conn, '_build_policy'): policy = salt.utils.json.loads(conn._build_policy()) else: return {} # The format we get from build_policy isn't going to be what we get back # from AWS for the exact same policy. AWS converts single item list values # into strings, so let's do the same here. for key, policy_val in policy.items(): for statement in policy_val: if (isinstance(statement['Action'], list) and len(statement['Action']) == 1): statement['Action'] = statement['Action'][0] if (isinstance(statement['Principal']['Service'], list) and len(statement['Principal']['Service']) == 1): statement['Principal']['Service'] = statement['Principal']['Service'][0] # build_policy doesn't add a version field, which AWS is going to set to a # default value, when we get it back, so let's set it. policy['Version'] = '2008-10-17' return policy def get_account_id(region=None, key=None, keyid=None, profile=None): ''' Get a the AWS account id associated with the used credentials. CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_id ''' cache_key = 'boto_iam.account_id' if cache_key not in __context__: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_user() # The get_user call returns an user ARN: # arn:aws:iam::027050522557:user/salt-test arn = ret['get_user_response']['get_user_result']['user']['arn'] account_id = arn.split(':')[4] except boto.exception.BotoServerError: # If call failed, then let's try to get the ARN from the metadata timeout = boto.config.getfloat( 'Boto', 'metadata_service_timeout', 1.0 ) attempts = boto.config.getint( 'Boto', 'metadata_service_num_attempts', 1 ) identity = boto.utils.get_instance_identity( timeout=timeout, num_retries=attempts ) try: account_id = identity['document']['accountId'] except KeyError: log.error('Failed to get account id from instance_identity in' ' boto_iam.get_account_id.') __context__[cache_key] = account_id return __context__[cache_key] def get_all_roles(path_prefix=None, region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM role details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_roles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _roles = conn.list_roles(path_prefix=path_prefix) roles = _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) while marker: _roles = conn.list_roles(path_prefix=path_prefix, marker=marker) roles = roles + _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) return roles def get_all_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM user details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_users ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _users = conn.get_all_users(path_prefix=path_prefix) users = _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) while marker: _users = conn.get_all_users(path_prefix=path_prefix, marker=marker) users = users + _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) return users def get_all_user_policies(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all user policies. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_user_policies myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_all_user_policies(user_name, marker, max_items) if not info: return False _list = info.list_user_policies_response.list_user_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policies for user %s.', user_name) return False def get_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user_policy myuser mypolicyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user_policy(user_name, policy_name) log.debug('Info for IAM user %s policy %s: %s.', user_name, policy_name, info) if not info: return False info = info.get_user_policy_response.get_user_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policy %s for IAM user %s.', policy_name, user_name) return False def put_user_policy(user_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_user_policy myuser policyname policyrules ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_user_policy(user_name, policy_name, policy_json) if created: log.info('Created policy %s for IAM user %s.', policy_name, user_name) return True log.error('Could not create policy %s for IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy %s for IAM user %s.', policy_name, user_name) return False def delete_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user_policy myuser mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_user_policy( user_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_user_policy(user_name, policy_name) log.info('Successfully deleted policy %s for IAM user %s.', policy_name, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM user %s.', policy_name, user_name) return False def upload_server_cert(cert_name, cert_body, private_key, cert_chain=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Upload a certificate to Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.upload_server_cert mycert_name crt priv_key :param cert_name: The name for the server certificate. Do not include the path in this value. :param cert_body: The contents of the public key certificate in PEM-encoded format. :param private_key: The contents of the private key in PEM-encoded format. :param cert_chain: The contents of the certificate chain. This is typically a concatenation of the PEM-encoded public key certificates of the chain. :param path: The path for the server certificate. :param region: The name of the region to connect to. :param key: The key to be used in order to connect :param keyid: The keyid to be used in order to connect :param profile: The profile that contains a dict of region, key, keyid :return: True / False ''' exists = get_server_certificate(cert_name, region, key, keyid, profile) if exists: return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.upload_server_cert(cert_name, cert_body, private_key, cert_chain) log.info('Created certificate %s.', cert_name) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to failed to create certificate %s.', cert_name) return False def list_server_certificates(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Lists the server certificates stored in IAM that have the specified path prefix. .. versionadded:: ??? :param path_prefix: The path prefix for filtering the results. For example: /company/servercerts would get all server certificates for which the path starts with /company/servercerts . This parameter is optional. If it is not included, it defaults to a slash (/), listing all server certificates. This parameter allows (per its regex pattern) a string of characters consisting of either a forward slash (/) by itself or a string that must begin and end with forward slashes. In addition, it can contain any ASCII character from the ! (u0021) through the DEL character (u007F), including most punctuation characters, digits, and upper and lowercased letters. CLI Example: .. code-block:: bash salt myminion boto_iam.list_server_certificates path_prefix=/somepath/ ''' retries = 10 sleep = 6 conn = __utils__['boto3.get_connection']('iam', region=region, key=key, keyid=keyid, profile=profile) Items = [] while retries: try: log.debug('Garnering list of IAM Server Certificates') IsTruncated = True while IsTruncated: kwargs = {'PathPrefix': path_prefix} ret = conn.list_server_certificates(**kwargs) Items += ret.get('ServerCertificateMetadataList', []) IsTruncated = ret.get('IsTruncated') kwargs.update({'Marker': ret.get('Marker')}) return Items except botocore.exceptions.ParamValidationError as err: raise SaltInvocationError(str(err)) except botocore.exceptions.ClientError as err: if retries and jmespath.search('Error.Code', err.response) == 'Throttling': retries -= 1 log.debug('Throttled by AWS API, retrying in %s seconds...', sleep) time.sleep(sleep) continue log.error('Failed to list IAM Server Certificates: %s', err.message) return None def get_server_certificate(cert_name, region=None, key=None, keyid=None, profile=None): ''' Returns certificate information from Amazon .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_server_certificate mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_server_certificate(cert_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get certificate %s information.', cert_name) return False def delete_server_cert(cert_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a certificate from Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_server_cert mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_server_cert(cert_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete certificate %s.', cert_name) return False def export_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM user details. Produces results that can be used to create an sls file. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.export_users --out=txt | sed "s/local: //" > iam_users.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() users = get_all_users(path_prefix, region, key, keyid, profile) for user in users: name = user.user_name _policies = conn.get_all_user_policies(name, max_items=100) _policies = _policies.list_user_policies_response.list_user_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_user_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_user_policy_response.get_user_policy_result.policy_document )) policies[policy_name] = _policy user_sls = [] user_sls.append({"name": name}) user_sls.append({"policies": policies}) user_sls.append({"path": user.path}) results["manage user " + name] = {"boto_iam.user_present": user_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def export_roles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM role details. Produces results that can be used to create an sls file. CLI Example: salt-call boto_iam.export_roles --out=txt | sed "s/local: //" > iam_roles.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() roles = get_all_roles(path_prefix, region, key, keyid, profile) for role in roles: name = role.role_name _policies = conn.list_role_policies(name, max_items=100) _policies = _policies.list_role_policies_response.list_role_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_role_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_role_policy_response.get_role_policy_result.policy_document )) policies[policy_name] = _policy role_sls = [] role_sls.append({"name": name}) role_sls.append({"policies": policies}) role_sls.append({'policy_document': salt.utils.json.loads(_unquote(role.assume_role_policy_document))}) role_sls.append({"path": role.path}) results["manage role " + name] = {"boto_iam_role.present": role_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def _get_policy_arn(name, region=None, key=None, keyid=None, profile=None): if name.startswith('arn:aws:iam:'): return name account_id = get_account_id( region=region, key=key, keyid=keyid, profile=profile ) return 'arn:aws:iam::{0}:policy/{1}'.format(account_id, name) def policy_exists(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return True except boto.exception.BotoServerError: return False def get_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return ret.get('get_policy_response', {}).get('get_policy_result', {}) except boto.exception.BotoServerError: return None def create_policy(policy_name, policy_document, path=None, description=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in 'path', 'description': if locals()[arg] is not None: params[arg] = locals()[arg] if policy_exists(policy_name, region, key, keyid, profile): return True try: conn.create_policy(policy_name, policy_document, **params) log.info('Created IAM policy %s.', policy_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s.', policy_name) return False return True def delete_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_exists(policy_arn, region, key, keyid, profile): return True try: conn.delete_policy(policy_arn) log.info('Deleted %s policy.', policy_name) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete %s policy: %s.', policy_name, aws.get('message')) return False return True def list_policies(region=None, key=None, keyid=None, profile=None): ''' List policies. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policies ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: policies = [] for ret in __utils__['boto.paged_call'](conn.list_policies): policies.append(ret.get('list_policies_response', {}).get('list_policies_result', {}).get('policies')) return policies except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to list policy versions.' log.error(msg) return [] def policy_version_exists(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.get_policy_version(policy_arn, version_id) return True except boto.exception.BotoServerError: return False def get_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy_version(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile), version_id) retval = ret.get('get_policy_version_response', {}).get('get_policy_version_result', {}).get('policy_version', {}) retval['document'] = _unquote(retval.get('document')) return {'policy_version': retval} except boto.exception.BotoServerError: return None def create_policy_version(policy_name, policy_document, set_as_default=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy version. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy_version mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in ('set_as_default',): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.create_policy_version(policy_arn, policy_document, **params) vid = ret.get('create_policy_version_response', {}).get('create_policy_version_result', {}).get('policy_version', {}).get('version_id') log.info('Created IAM policy %s version %s.', policy_name, vid) return {'created': True, 'version_id': vid} except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s version %s.', policy_name, vid) return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Delete a policy version. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_version_exists(policy_arn, version_id, region, key, keyid, profile): return True try: conn.delete_policy_version(policy_arn, version_id) log.info('Deleted IAM policy %s version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete IAM policy %s version %s: %s', policy_name, version_id, aws.get('message')) return False return True def list_policy_versions(policy_name, region=None, key=None, keyid=None, profile=None): ''' List versions of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policy_versions mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.list_policy_versions(policy_arn) return ret.get('list_policy_versions_response', {}).get('list_policy_versions_result', {}).get('versions') except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list versions for IAM policy %s.', policy_name) return [] def set_default_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Set the default version of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.set_default_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.set_default_policy_version(policy_arn, version_id) log.info('Set %s policy to version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to set %s policy to version %s: %s', policy_name, version_id, aws.get('message')) return False return True def attach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_user_policy(policy_arn, user_name) log.info('Attached policy %s to IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach %s policy to IAM user %s.', policy_name, user_name) return False return True def detach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_user_policy(policy_arn, user_name) log.info('Detached %s policy from IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach %s policy from IAM user %s.', policy_name, user_name) return False return True def attach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_group_policy(policy_arn, group_name) log.info('Attached policy %s to IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM group %s.', policy_name, group_name) return False return True def detach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_group_policy(policy_arn, group_name) log.info('Detached policy %s from IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM group %s.', policy_name, group_name) return False return True def attach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_role_policy(policy_arn, role_name) log.info('Attached policy %s to IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM role %s.', policy_name, role_name) return False return True def detach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_role_policy(policy_arn, role_name) log.info('Detached policy %s from IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM role %s.', policy_name, role_name) return False return True def list_entities_for_policy(policy_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities that a policy is attached to. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 params = {} for arg in ('path_prefix', 'entity_filter'): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) while retries: try: allret = { 'policy_groups': [], 'policy_users': [], 'policy_roles': [], } for ret in __utils__['boto.paged_call'](conn.list_entities_for_policy, policy_arn=policy_arn, **params): for k, v in six.iteritems(allret): v.extend(ret.get('list_entities_for_policy_response', {}).get('list_entities_for_policy_result', {}).get(k)) return allret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('Failed to list entities for IAM policy %s: %s', policy_name, e.message) return {} return {} def list_attached_user_policies(user_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given user. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'UserName': user_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedUserPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_user_policies_response', {}).get('list_attached_user_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM user %s.', user_name) return [] def list_attached_group_policies(group_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given group. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'GroupName': group_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedGroupPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_group_policies_response', {}).get('list_attached_group_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM group %s.', group_name) return [] def list_attached_role_policies(role_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'RoleName': role_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedRolePolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_role_policies_response', {}).get('list_attached_role_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM role %s.', role_name) return [] def create_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Create SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.create_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_saml_provider(saml_metadata_document, name) log.info('Successfully created %s SAML provider.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to create SAML provider %s.', name) return False def get_saml_provider_arn(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider_arn my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_saml_providers() for saml_provider in response.list_saml_providers_response.list_saml_providers_result.saml_provider_list: if saml_provider['arn'].endswith(':saml-provider/' + name): return saml_provider['arn'] return False except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to get ARN of SAML provider %s.', name) return False def delete_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Delete SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.delete_saml_provider my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return True conn.delete_saml_provider(saml_provider_arn) log.info('Successfully deleted SAML provider %s.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete SAML provider %s.', name) return False def list_saml_providers(region=None, key=None, keyid=None, profile=None): ''' List SAML providers. CLI Example: .. code-block:: bash salt myminion boto_iam.list_saml_providers ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: providers = [] info = conn.list_saml_providers() for arn in info['list_saml_providers_response']['list_saml_providers_result']['saml_provider_list']: providers.append(arn['arn'].rsplit('/', 1)[1]) return providers except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get list of SAML providers.') return False def get_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider document. CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider arn ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: provider = conn.get_saml_provider(name) return provider['get_saml_provider_response']['get_saml_provider_result']['saml_metadata_document'] except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get SAML provider document %s.', name) return False def update_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Update SAML provider. CLI Example: .. code-block:: bash salt myminion boto_iam.update_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return False if conn.update_saml_provider(name, saml_metadata_document): return True return False except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to update SAML provider %s.', name) return False
saltstack/salt
salt/modules/boto_iam.py
get_user
python
def get_user(user_name=None, region=None, key=None, keyid=None, profile=None): ''' Get user information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user(user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM user %s info.', user_name) return False
Get user information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user myuser
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iam.py#L331-L352
null
# -*- coding: utf-8 -*- ''' Connection module for Amazon IAM .. versionadded:: 2014.7.0 :configuration: This module accepts explicit iam 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 iam.keyid: GKTADJGHEIQSXMKKRBJ08H iam.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs iam.region: 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: boto ''' # keep lint from choking on _get_conn and _cache_id #pylint: disable=E0602 # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import salt libs from salt.ext import six import salt.utils.compat import salt.utils.json import salt.utils.odict as odict import salt.utils.versions from salt.exceptions import SaltInvocationError # Import third party libs # pylint: disable=unused-import from salt.ext.six.moves.urllib.parse import unquote as _unquote # pylint: disable=no-name-in-module try: import boto import boto.iam import boto3 import botocore logging.getLogger('boto').setLevel(logging.CRITICAL) logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=unused-import log = logging.getLogger(__name__) def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'iam', pack=__salt__) def instance_profile_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an instance profile exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: # Boto weirdly returns an exception here if an instance profile doesn't # exist. conn.get_instance_profile(name) return True except boto.exception.BotoServerError: return False def create_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Create an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.create_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if instance_profile_exists(name, region, key, keyid, profile): return True try: # This call returns an instance profile if successful and an exception # if not. It's annoying. conn.create_instance_profile(name) log.info('Created %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create %s instance profile.', name) return False return True def delete_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Delete an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not instance_profile_exists(name, region, key, keyid, profile): return True try: conn.delete_instance_profile(name) log.info('Deleted %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s instance profile.', name) return False return True def role_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an IAM role exists. CLI Example: .. code-block:: bash salt myminion boto_iam.role_exists myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_role(name) return True except boto.exception.BotoServerError: return False def describe_role(name, region=None, key=None, keyid=None, profile=None): ''' Get information for a role. CLI Example: .. code-block:: bash salt myminion boto_iam.describe_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_role(name) if not info: return False role = info.get_role_response.get_role_result.role role['assume_role_policy_document'] = salt.utils.json.loads(_unquote( role.assume_role_policy_document )) # If Sid wasn't defined by the user, boto will still return a Sid in # each policy. To properly check idempotently, let's remove the Sid # from the return if it's not actually set. for policy_key, policy in role['assume_role_policy_document'].items(): if policy_key == 'Statement': for val in policy: if 'Sid' in val and not val['Sid']: del val['Sid'] return role except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get %s information.', name) return False def create_user(user_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_user myuser ''' if not path: path = '/' if get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_user(user_name, path) log.info('Created IAM user : %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM user %s.', user_name) return False def get_all_access_keys(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all access keys from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_access_keys myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.get_all_access_keys(user_name, marker, max_items) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get access keys for IAM user %s.', user_name) return six.text_type(e) def create_access_key(user_name, region=None, key=None, keyid=None, profile=None): ''' Create access key id for a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.create_access_key(user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create access key.') return six.text_type(e) def delete_access_key(access_key_id, user_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete access key id from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_access_key(access_key_id, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete access key id %s.', access_key_id) return six.text_type(e) def delete_user(user_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user myuser ''' if not get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.delete_user(user_name) log.info('Deleted IAM user : %s .', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM user %s', user_name) return six.text_type(e) def create_group(group_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_group group ''' if not path: path = '/' if get_group(group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_group(group_name, path) log.info('Created IAM group : %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM group %s.', group_name) return False def get_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group(group_name, max_items=1) if not info: return False return info['get_group_response']['get_group_result']['group'] except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_group_members(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: marker = None truncated = True users = [] while truncated: info = conn.get_group(group_name, marker=marker, max_items=1000) if not info: return False truncated = bool(info['get_group_response']['get_group_result']['is_truncated']) if truncated and 'marker' in info['get_group_response']['get_group_result']: marker = info['get_group_response']['get_group_result']['marker'] else: marker = None truncated = False users += info['get_group_response']['get_group_result']['users'] return users except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get members for IAM group %s.', group_name) return False def add_user_to_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Add user to group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.add_user_to_group myuser mygroup ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('Username : %s does not exist.', user_name) return False if user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.add_user_to_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add IAM user %s to group %s.', user_name, group_name) return False def user_exists_in_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Check if user exists in group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.user_exists_in_group myuser mygroup ''' # TODO this should probably use boto.iam.get_groups_for_user users = get_group_members( group_name=group_name, region=region, key=key, keyid=keyid, profile=profile ) if users: for _user in users: if user_name == _user['user_name']: log.debug('IAM user %s is already in IAM group %s.', user_name, group_name) return True return False def remove_user_from_group(group_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Remove user from group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.remove_user_from_group mygroup myuser ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist.', user_name) return False if not user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.remove_user_from_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove IAM user %s from group %s', user_name, group_name) return False def put_group_policy(group_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_group_policy mygroup policyname policyrules ''' group = get_group(group_name, region=region, key=key, keyid=keyid, profile=profile) if not group: log.error('Group %s does not exist', group_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_group_policy(group_name, policy_name, policy_json) if created: log.info('Created policy for IAM group %s.', group_name) return True log.error('Could not create policy for IAM group %s', group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy for IAM group %s', group_name) return False def delete_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group_policy mygroup mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_group_policy( group_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_group_policy(group_name, policy_name) log.info('Successfully deleted policy %s for IAM group %s.', policy_name, group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM group %s.', policy_name, group_name) return False def get_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group_policy mygroup policyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group_policy(group_name, policy_name) log.debug('info for group policy is : %s', info) if not info: return False info = info.get_group_policy_response.get_group_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_all_groups(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM group details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_groups ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _groups = conn.get_all_groups(path_prefix=path_prefix) groups = _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) while marker: _groups = conn.get_all_groups(path_prefix=path_prefix, marker=marker) groups = groups + _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) return groups def get_all_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.get_all_instance_profiles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) marker = False profiles = [] while marker is not None: marker = marker if marker else None p = conn.list_instance_profiles(path_prefix=path_prefix, marker=marker) res = p.list_instance_profiles_response.list_instance_profiles_result profiles += res.instance_profiles marker = getattr(res, 'marker', None) return profiles def list_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' List all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.list_instance_profiles ''' p = get_all_instance_profiles(path_prefix, region, key, keyid, profile) return [i['instance_profile_name'] for i in p] def get_all_group_policies(group_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a group. CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_group_policies mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False try: response = conn.get_all_group_policies(group_name) _list = response.list_group_policies_response.list_group_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def delete_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _group = get_group( group_name, region, key, keyid, profile ) if not _group: return True try: conn.delete_group(group_name) log.info('Successfully deleted IAM group %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM group %s.', group_name) return False def create_login_profile(user_name, password, region=None, key=None, keyid=None, profile=None): ''' Creates a login profile for the specified user, give the user the ability to access AWS services and the AWS Management Console. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_login_profile user_name password ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.create_login_profile(user_name, password) log.info('Created profile for IAM user %s.', user_name) return info except boto.exception.BotoServerError as e: log.debug(e) if 'Conflict' in e: log.info('Profile already exists for IAM user %s.', user_name) return 'Conflict' log.error('Failed to update profile for IAM user %s.', user_name) return False def delete_login_profile(user_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a login profile for the specified user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_login_profile user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.delete_login_profile(user_name) log.info('Deleted login profile for IAM user %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Login profile already deleted for IAM user %s.', user_name) return True log.error('Failed to delete login profile for IAM user %s.', user_name) return False def get_all_mfa_devices(user_name, region=None, key=None, keyid=None, profile=None): ''' Get all MFA devices associated with an IAM user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_mfa_devices user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: result = conn.get_all_mfa_devices(user_name) devices = result['list_mfa_devices_response']['list_mfa_devices_result']['mfa_devices'] return devices except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Could not find IAM user %s.', user_name) return [] log.error('Failed to get all MFA devices for IAM user %s.', user_name) return False def deactivate_mfa_device(user_name, serial, region=None, key=None, keyid=None, profile=None): ''' Deactivates the specified MFA device and removes it from association with the user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.deactivate_mfa_device user_name serial_num ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.deactivate_mfa_device(user_name, serial) log.info('Deactivated MFA device %s for IAM user %s.', serial, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('MFA device %s not associated with IAM user %s.', serial, user_name) return True log.error('Failed to deactivate MFA device %s for IAM user %s.', serial, user_name) return False def delete_virtual_mfa_device(serial, region=None, key=None, keyid=None, profile=None): ''' Deletes the specified virtual MFA device. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_virtual_mfa_device serial_num ''' conn = __utils__['boto3.get_connection_func']('iam')() try: conn.delete_virtual_mfa_device(SerialNumber=serial) log.info('Deleted virtual MFA device %s.', serial) return True except botocore.exceptions.ClientError as e: log.debug(e) if 'NoSuchEntity' in six.text_type(e): log.info('Virtual MFA device %s not found.', serial) return True log.error('Failed to delete virtual MFA device %s.', serial) return False def update_account_password_policy(allow_users_to_change_password=None, hard_expiry=None, max_password_age=None, minimum_password_length=None, password_reuse_prevention=None, require_lowercase_characters=None, require_numbers=None, require_symbols=None, require_uppercase_characters=None, region=None, key=None, keyid=None, profile=None): ''' Update the password policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_account_password_policy True ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.update_account_password_policy(allow_users_to_change_password, hard_expiry, max_password_age, minimum_password_length, password_reuse_prevention, require_lowercase_characters, require_numbers, require_symbols, require_uppercase_characters) log.info('The password policy has been updated.') return True except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy' log.error(msg) return False def get_account_policy(region=None, key=None, keyid=None, profile=None): ''' Get account policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_account_password_policy() return info.get_account_password_policy_response.get_account_password_policy_result.password_policy except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy.' log.error(msg) return False def create_role(name, policy_document=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Create an instance role. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if role_exists(name, region, key, keyid, profile): return True if not policy_document: policy_document = None try: conn.create_role(name, assume_role_policy_document=policy_document, path=path) log.info('Created IAM role %s.', name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to create IAM role %s.', name) return False def delete_role(name, region=None, key=None, keyid=None, profile=None): ''' Delete an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(name, region, key, keyid, profile): return True try: conn.delete_role(name) log.info('Deleted %s IAM role.', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s IAM role.', name) return False def profile_associated(role_name, profile_name, region, key, keyid, profile): ''' Check to see if an instance profile is associated with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.profile_associated myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # The IAM module of boto doesn't return objects. Instead you need to grab # values through its properties. Sigh. try: profiles = conn.list_instance_profiles_for_role(role_name) except boto.exception.BotoServerError as e: log.debug(e) return False profiles = profiles.list_instance_profiles_for_role_response profiles = profiles.list_instance_profiles_for_role_result profiles = profiles.instance_profiles for profile in profiles: if profile.instance_profile_name == profile_name: return True return False def associate_profile_to_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Associate an instance profile with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.associate_profile_to_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if associated: return True else: try: conn.add_role_to_instance_profile(profile_name, role_name) log.info('Added %s instance profile to IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add %s instance profile to IAM role %s', profile_name, role_name) return False def disassociate_profile_from_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Disassociate an instance profile from an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.disassociate_profile_from_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if not associated: return True else: try: conn.remove_role_from_instance_profile(profile_name, role_name) log.info('Removed %s instance profile from IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove %s instance profile from IAM role %s.', profile_name, role_name) return False def list_role_policies(role_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_role_policies myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_role_policies(role_name) _list = response.list_role_policies_response.list_role_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def get_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.get_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: _policy = conn.get_role_policy(role_name, policy_name) # I _hate_ you for not giving me an object boto. _policy = _policy.get_role_policy_response.policy_document # Policy is url encoded _policy = _unquote(_policy) _policy = salt.utils.json.loads(_policy, object_pairs_hook=odict.OrderedDict) return _policy except boto.exception.BotoServerError: return {} def create_role_policy(role_name, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Create or modify a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role_policy myirole mypolicy '{"MyPolicy": "Statement": [{"Action": ["sqs:*"], "Effect": "Allow", "Resource": ["arn:aws:sqs:*:*:*"], "Sid": "MyPolicySqs1"}]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) mode = 'create' if _policy: if _policy == policy: return True mode = 'modify' if isinstance(policy, six.string_types): policy = salt.utils.json.loads(policy, object_pairs_hook=odict.OrderedDict) try: _policy = salt.utils.json.dumps(policy) conn.put_role_policy(role_name, policy_name, _policy) if mode == 'create': msg = 'Successfully added policy %s to IAM role %s.' else: msg = 'Successfully modified policy %s for IAM role %s.' log.info(msg, policy_name, role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to %s policy %s for IAM role %s.', mode, policy_name, role_name) return False def delete_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) if not _policy: return True try: conn.delete_role_policy(role_name, policy_name) log.info('Successfully deleted policy %s for IAM role %s.', policy_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM role %s.', policy_name, role_name) return False def update_assume_role_policy(role_name, policy_document, region=None, key=None, keyid=None, profile=None): ''' Update an assume role policy for a role. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_assume_role_policy myrole '{"Statement":"..."}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(policy_document, six.string_types): policy_document = salt.utils.json.loads(policy_document, object_pairs_hook=odict.OrderedDict) try: _policy_document = salt.utils.json.dumps(policy_document) conn.update_assume_role_policy(role_name, _policy_document) log.info('Successfully updated assume role policy for IAM role %s.', role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to update assume role policy for IAM role %s.', role_name) return False def build_policy(region=None, key=None, keyid=None, profile=None): ''' Build a default assume role policy. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.build_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if hasattr(conn, 'build_policy'): policy = salt.utils.json.loads(conn.build_policy()) elif hasattr(conn, '_build_policy'): policy = salt.utils.json.loads(conn._build_policy()) else: return {} # The format we get from build_policy isn't going to be what we get back # from AWS for the exact same policy. AWS converts single item list values # into strings, so let's do the same here. for key, policy_val in policy.items(): for statement in policy_val: if (isinstance(statement['Action'], list) and len(statement['Action']) == 1): statement['Action'] = statement['Action'][0] if (isinstance(statement['Principal']['Service'], list) and len(statement['Principal']['Service']) == 1): statement['Principal']['Service'] = statement['Principal']['Service'][0] # build_policy doesn't add a version field, which AWS is going to set to a # default value, when we get it back, so let's set it. policy['Version'] = '2008-10-17' return policy def get_account_id(region=None, key=None, keyid=None, profile=None): ''' Get a the AWS account id associated with the used credentials. CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_id ''' cache_key = 'boto_iam.account_id' if cache_key not in __context__: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_user() # The get_user call returns an user ARN: # arn:aws:iam::027050522557:user/salt-test arn = ret['get_user_response']['get_user_result']['user']['arn'] account_id = arn.split(':')[4] except boto.exception.BotoServerError: # If call failed, then let's try to get the ARN from the metadata timeout = boto.config.getfloat( 'Boto', 'metadata_service_timeout', 1.0 ) attempts = boto.config.getint( 'Boto', 'metadata_service_num_attempts', 1 ) identity = boto.utils.get_instance_identity( timeout=timeout, num_retries=attempts ) try: account_id = identity['document']['accountId'] except KeyError: log.error('Failed to get account id from instance_identity in' ' boto_iam.get_account_id.') __context__[cache_key] = account_id return __context__[cache_key] def get_all_roles(path_prefix=None, region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM role details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_roles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _roles = conn.list_roles(path_prefix=path_prefix) roles = _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) while marker: _roles = conn.list_roles(path_prefix=path_prefix, marker=marker) roles = roles + _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) return roles def get_all_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM user details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_users ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _users = conn.get_all_users(path_prefix=path_prefix) users = _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) while marker: _users = conn.get_all_users(path_prefix=path_prefix, marker=marker) users = users + _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) return users def get_all_user_policies(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all user policies. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_user_policies myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_all_user_policies(user_name, marker, max_items) if not info: return False _list = info.list_user_policies_response.list_user_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policies for user %s.', user_name) return False def get_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user_policy myuser mypolicyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user_policy(user_name, policy_name) log.debug('Info for IAM user %s policy %s: %s.', user_name, policy_name, info) if not info: return False info = info.get_user_policy_response.get_user_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policy %s for IAM user %s.', policy_name, user_name) return False def put_user_policy(user_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_user_policy myuser policyname policyrules ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_user_policy(user_name, policy_name, policy_json) if created: log.info('Created policy %s for IAM user %s.', policy_name, user_name) return True log.error('Could not create policy %s for IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy %s for IAM user %s.', policy_name, user_name) return False def delete_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user_policy myuser mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_user_policy( user_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_user_policy(user_name, policy_name) log.info('Successfully deleted policy %s for IAM user %s.', policy_name, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM user %s.', policy_name, user_name) return False def upload_server_cert(cert_name, cert_body, private_key, cert_chain=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Upload a certificate to Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.upload_server_cert mycert_name crt priv_key :param cert_name: The name for the server certificate. Do not include the path in this value. :param cert_body: The contents of the public key certificate in PEM-encoded format. :param private_key: The contents of the private key in PEM-encoded format. :param cert_chain: The contents of the certificate chain. This is typically a concatenation of the PEM-encoded public key certificates of the chain. :param path: The path for the server certificate. :param region: The name of the region to connect to. :param key: The key to be used in order to connect :param keyid: The keyid to be used in order to connect :param profile: The profile that contains a dict of region, key, keyid :return: True / False ''' exists = get_server_certificate(cert_name, region, key, keyid, profile) if exists: return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.upload_server_cert(cert_name, cert_body, private_key, cert_chain) log.info('Created certificate %s.', cert_name) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to failed to create certificate %s.', cert_name) return False def list_server_certificates(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Lists the server certificates stored in IAM that have the specified path prefix. .. versionadded:: ??? :param path_prefix: The path prefix for filtering the results. For example: /company/servercerts would get all server certificates for which the path starts with /company/servercerts . This parameter is optional. If it is not included, it defaults to a slash (/), listing all server certificates. This parameter allows (per its regex pattern) a string of characters consisting of either a forward slash (/) by itself or a string that must begin and end with forward slashes. In addition, it can contain any ASCII character from the ! (u0021) through the DEL character (u007F), including most punctuation characters, digits, and upper and lowercased letters. CLI Example: .. code-block:: bash salt myminion boto_iam.list_server_certificates path_prefix=/somepath/ ''' retries = 10 sleep = 6 conn = __utils__['boto3.get_connection']('iam', region=region, key=key, keyid=keyid, profile=profile) Items = [] while retries: try: log.debug('Garnering list of IAM Server Certificates') IsTruncated = True while IsTruncated: kwargs = {'PathPrefix': path_prefix} ret = conn.list_server_certificates(**kwargs) Items += ret.get('ServerCertificateMetadataList', []) IsTruncated = ret.get('IsTruncated') kwargs.update({'Marker': ret.get('Marker')}) return Items except botocore.exceptions.ParamValidationError as err: raise SaltInvocationError(str(err)) except botocore.exceptions.ClientError as err: if retries and jmespath.search('Error.Code', err.response) == 'Throttling': retries -= 1 log.debug('Throttled by AWS API, retrying in %s seconds...', sleep) time.sleep(sleep) continue log.error('Failed to list IAM Server Certificates: %s', err.message) return None def get_server_certificate(cert_name, region=None, key=None, keyid=None, profile=None): ''' Returns certificate information from Amazon .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_server_certificate mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_server_certificate(cert_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get certificate %s information.', cert_name) return False def delete_server_cert(cert_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a certificate from Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_server_cert mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_server_cert(cert_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete certificate %s.', cert_name) return False def export_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM user details. Produces results that can be used to create an sls file. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.export_users --out=txt | sed "s/local: //" > iam_users.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() users = get_all_users(path_prefix, region, key, keyid, profile) for user in users: name = user.user_name _policies = conn.get_all_user_policies(name, max_items=100) _policies = _policies.list_user_policies_response.list_user_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_user_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_user_policy_response.get_user_policy_result.policy_document )) policies[policy_name] = _policy user_sls = [] user_sls.append({"name": name}) user_sls.append({"policies": policies}) user_sls.append({"path": user.path}) results["manage user " + name] = {"boto_iam.user_present": user_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def export_roles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM role details. Produces results that can be used to create an sls file. CLI Example: salt-call boto_iam.export_roles --out=txt | sed "s/local: //" > iam_roles.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() roles = get_all_roles(path_prefix, region, key, keyid, profile) for role in roles: name = role.role_name _policies = conn.list_role_policies(name, max_items=100) _policies = _policies.list_role_policies_response.list_role_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_role_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_role_policy_response.get_role_policy_result.policy_document )) policies[policy_name] = _policy role_sls = [] role_sls.append({"name": name}) role_sls.append({"policies": policies}) role_sls.append({'policy_document': salt.utils.json.loads(_unquote(role.assume_role_policy_document))}) role_sls.append({"path": role.path}) results["manage role " + name] = {"boto_iam_role.present": role_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def _get_policy_arn(name, region=None, key=None, keyid=None, profile=None): if name.startswith('arn:aws:iam:'): return name account_id = get_account_id( region=region, key=key, keyid=keyid, profile=profile ) return 'arn:aws:iam::{0}:policy/{1}'.format(account_id, name) def policy_exists(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return True except boto.exception.BotoServerError: return False def get_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return ret.get('get_policy_response', {}).get('get_policy_result', {}) except boto.exception.BotoServerError: return None def create_policy(policy_name, policy_document, path=None, description=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in 'path', 'description': if locals()[arg] is not None: params[arg] = locals()[arg] if policy_exists(policy_name, region, key, keyid, profile): return True try: conn.create_policy(policy_name, policy_document, **params) log.info('Created IAM policy %s.', policy_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s.', policy_name) return False return True def delete_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_exists(policy_arn, region, key, keyid, profile): return True try: conn.delete_policy(policy_arn) log.info('Deleted %s policy.', policy_name) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete %s policy: %s.', policy_name, aws.get('message')) return False return True def list_policies(region=None, key=None, keyid=None, profile=None): ''' List policies. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policies ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: policies = [] for ret in __utils__['boto.paged_call'](conn.list_policies): policies.append(ret.get('list_policies_response', {}).get('list_policies_result', {}).get('policies')) return policies except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to list policy versions.' log.error(msg) return [] def policy_version_exists(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.get_policy_version(policy_arn, version_id) return True except boto.exception.BotoServerError: return False def get_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy_version(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile), version_id) retval = ret.get('get_policy_version_response', {}).get('get_policy_version_result', {}).get('policy_version', {}) retval['document'] = _unquote(retval.get('document')) return {'policy_version': retval} except boto.exception.BotoServerError: return None def create_policy_version(policy_name, policy_document, set_as_default=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy version. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy_version mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in ('set_as_default',): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.create_policy_version(policy_arn, policy_document, **params) vid = ret.get('create_policy_version_response', {}).get('create_policy_version_result', {}).get('policy_version', {}).get('version_id') log.info('Created IAM policy %s version %s.', policy_name, vid) return {'created': True, 'version_id': vid} except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s version %s.', policy_name, vid) return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Delete a policy version. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_version_exists(policy_arn, version_id, region, key, keyid, profile): return True try: conn.delete_policy_version(policy_arn, version_id) log.info('Deleted IAM policy %s version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete IAM policy %s version %s: %s', policy_name, version_id, aws.get('message')) return False return True def list_policy_versions(policy_name, region=None, key=None, keyid=None, profile=None): ''' List versions of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policy_versions mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.list_policy_versions(policy_arn) return ret.get('list_policy_versions_response', {}).get('list_policy_versions_result', {}).get('versions') except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list versions for IAM policy %s.', policy_name) return [] def set_default_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Set the default version of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.set_default_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.set_default_policy_version(policy_arn, version_id) log.info('Set %s policy to version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to set %s policy to version %s: %s', policy_name, version_id, aws.get('message')) return False return True def attach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_user_policy(policy_arn, user_name) log.info('Attached policy %s to IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach %s policy to IAM user %s.', policy_name, user_name) return False return True def detach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_user_policy(policy_arn, user_name) log.info('Detached %s policy from IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach %s policy from IAM user %s.', policy_name, user_name) return False return True def attach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_group_policy(policy_arn, group_name) log.info('Attached policy %s to IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM group %s.', policy_name, group_name) return False return True def detach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_group_policy(policy_arn, group_name) log.info('Detached policy %s from IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM group %s.', policy_name, group_name) return False return True def attach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_role_policy(policy_arn, role_name) log.info('Attached policy %s to IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM role %s.', policy_name, role_name) return False return True def detach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_role_policy(policy_arn, role_name) log.info('Detached policy %s from IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM role %s.', policy_name, role_name) return False return True def list_entities_for_policy(policy_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities that a policy is attached to. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 params = {} for arg in ('path_prefix', 'entity_filter'): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) while retries: try: allret = { 'policy_groups': [], 'policy_users': [], 'policy_roles': [], } for ret in __utils__['boto.paged_call'](conn.list_entities_for_policy, policy_arn=policy_arn, **params): for k, v in six.iteritems(allret): v.extend(ret.get('list_entities_for_policy_response', {}).get('list_entities_for_policy_result', {}).get(k)) return allret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('Failed to list entities for IAM policy %s: %s', policy_name, e.message) return {} return {} def list_attached_user_policies(user_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given user. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'UserName': user_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedUserPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_user_policies_response', {}).get('list_attached_user_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM user %s.', user_name) return [] def list_attached_group_policies(group_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given group. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'GroupName': group_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedGroupPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_group_policies_response', {}).get('list_attached_group_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM group %s.', group_name) return [] def list_attached_role_policies(role_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'RoleName': role_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedRolePolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_role_policies_response', {}).get('list_attached_role_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM role %s.', role_name) return [] def create_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Create SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.create_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_saml_provider(saml_metadata_document, name) log.info('Successfully created %s SAML provider.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to create SAML provider %s.', name) return False def get_saml_provider_arn(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider_arn my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_saml_providers() for saml_provider in response.list_saml_providers_response.list_saml_providers_result.saml_provider_list: if saml_provider['arn'].endswith(':saml-provider/' + name): return saml_provider['arn'] return False except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to get ARN of SAML provider %s.', name) return False def delete_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Delete SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.delete_saml_provider my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return True conn.delete_saml_provider(saml_provider_arn) log.info('Successfully deleted SAML provider %s.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete SAML provider %s.', name) return False def list_saml_providers(region=None, key=None, keyid=None, profile=None): ''' List SAML providers. CLI Example: .. code-block:: bash salt myminion boto_iam.list_saml_providers ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: providers = [] info = conn.list_saml_providers() for arn in info['list_saml_providers_response']['list_saml_providers_result']['saml_provider_list']: providers.append(arn['arn'].rsplit('/', 1)[1]) return providers except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get list of SAML providers.') return False def get_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider document. CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider arn ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: provider = conn.get_saml_provider(name) return provider['get_saml_provider_response']['get_saml_provider_result']['saml_metadata_document'] except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get SAML provider document %s.', name) return False def update_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Update SAML provider. CLI Example: .. code-block:: bash salt myminion boto_iam.update_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return False if conn.update_saml_provider(name, saml_metadata_document): return True return False except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to update SAML provider %s.', name) return False
saltstack/salt
salt/modules/boto_iam.py
get_group
python
def get_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group(group_name, max_items=1) if not info: return False return info['get_group_response']['get_group_result']['group'] except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False
Get group information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iam.py#L384-L405
null
# -*- coding: utf-8 -*- ''' Connection module for Amazon IAM .. versionadded:: 2014.7.0 :configuration: This module accepts explicit iam 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 iam.keyid: GKTADJGHEIQSXMKKRBJ08H iam.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs iam.region: 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: boto ''' # keep lint from choking on _get_conn and _cache_id #pylint: disable=E0602 # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import salt libs from salt.ext import six import salt.utils.compat import salt.utils.json import salt.utils.odict as odict import salt.utils.versions from salt.exceptions import SaltInvocationError # Import third party libs # pylint: disable=unused-import from salt.ext.six.moves.urllib.parse import unquote as _unquote # pylint: disable=no-name-in-module try: import boto import boto.iam import boto3 import botocore logging.getLogger('boto').setLevel(logging.CRITICAL) logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=unused-import log = logging.getLogger(__name__) def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'iam', pack=__salt__) def instance_profile_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an instance profile exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: # Boto weirdly returns an exception here if an instance profile doesn't # exist. conn.get_instance_profile(name) return True except boto.exception.BotoServerError: return False def create_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Create an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.create_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if instance_profile_exists(name, region, key, keyid, profile): return True try: # This call returns an instance profile if successful and an exception # if not. It's annoying. conn.create_instance_profile(name) log.info('Created %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create %s instance profile.', name) return False return True def delete_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Delete an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not instance_profile_exists(name, region, key, keyid, profile): return True try: conn.delete_instance_profile(name) log.info('Deleted %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s instance profile.', name) return False return True def role_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an IAM role exists. CLI Example: .. code-block:: bash salt myminion boto_iam.role_exists myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_role(name) return True except boto.exception.BotoServerError: return False def describe_role(name, region=None, key=None, keyid=None, profile=None): ''' Get information for a role. CLI Example: .. code-block:: bash salt myminion boto_iam.describe_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_role(name) if not info: return False role = info.get_role_response.get_role_result.role role['assume_role_policy_document'] = salt.utils.json.loads(_unquote( role.assume_role_policy_document )) # If Sid wasn't defined by the user, boto will still return a Sid in # each policy. To properly check idempotently, let's remove the Sid # from the return if it's not actually set. for policy_key, policy in role['assume_role_policy_document'].items(): if policy_key == 'Statement': for val in policy: if 'Sid' in val and not val['Sid']: del val['Sid'] return role except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get %s information.', name) return False def create_user(user_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_user myuser ''' if not path: path = '/' if get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_user(user_name, path) log.info('Created IAM user : %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM user %s.', user_name) return False def get_all_access_keys(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all access keys from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_access_keys myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.get_all_access_keys(user_name, marker, max_items) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get access keys for IAM user %s.', user_name) return six.text_type(e) def create_access_key(user_name, region=None, key=None, keyid=None, profile=None): ''' Create access key id for a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.create_access_key(user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create access key.') return six.text_type(e) def delete_access_key(access_key_id, user_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete access key id from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_access_key(access_key_id, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete access key id %s.', access_key_id) return six.text_type(e) def delete_user(user_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user myuser ''' if not get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.delete_user(user_name) log.info('Deleted IAM user : %s .', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM user %s', user_name) return six.text_type(e) def get_user(user_name=None, region=None, key=None, keyid=None, profile=None): ''' Get user information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user(user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM user %s info.', user_name) return False def create_group(group_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_group group ''' if not path: path = '/' if get_group(group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_group(group_name, path) log.info('Created IAM group : %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM group %s.', group_name) return False def get_group_members(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: marker = None truncated = True users = [] while truncated: info = conn.get_group(group_name, marker=marker, max_items=1000) if not info: return False truncated = bool(info['get_group_response']['get_group_result']['is_truncated']) if truncated and 'marker' in info['get_group_response']['get_group_result']: marker = info['get_group_response']['get_group_result']['marker'] else: marker = None truncated = False users += info['get_group_response']['get_group_result']['users'] return users except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get members for IAM group %s.', group_name) return False def add_user_to_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Add user to group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.add_user_to_group myuser mygroup ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('Username : %s does not exist.', user_name) return False if user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.add_user_to_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add IAM user %s to group %s.', user_name, group_name) return False def user_exists_in_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Check if user exists in group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.user_exists_in_group myuser mygroup ''' # TODO this should probably use boto.iam.get_groups_for_user users = get_group_members( group_name=group_name, region=region, key=key, keyid=keyid, profile=profile ) if users: for _user in users: if user_name == _user['user_name']: log.debug('IAM user %s is already in IAM group %s.', user_name, group_name) return True return False def remove_user_from_group(group_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Remove user from group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.remove_user_from_group mygroup myuser ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist.', user_name) return False if not user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.remove_user_from_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove IAM user %s from group %s', user_name, group_name) return False def put_group_policy(group_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_group_policy mygroup policyname policyrules ''' group = get_group(group_name, region=region, key=key, keyid=keyid, profile=profile) if not group: log.error('Group %s does not exist', group_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_group_policy(group_name, policy_name, policy_json) if created: log.info('Created policy for IAM group %s.', group_name) return True log.error('Could not create policy for IAM group %s', group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy for IAM group %s', group_name) return False def delete_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group_policy mygroup mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_group_policy( group_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_group_policy(group_name, policy_name) log.info('Successfully deleted policy %s for IAM group %s.', policy_name, group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM group %s.', policy_name, group_name) return False def get_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group_policy mygroup policyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group_policy(group_name, policy_name) log.debug('info for group policy is : %s', info) if not info: return False info = info.get_group_policy_response.get_group_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_all_groups(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM group details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_groups ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _groups = conn.get_all_groups(path_prefix=path_prefix) groups = _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) while marker: _groups = conn.get_all_groups(path_prefix=path_prefix, marker=marker) groups = groups + _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) return groups def get_all_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.get_all_instance_profiles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) marker = False profiles = [] while marker is not None: marker = marker if marker else None p = conn.list_instance_profiles(path_prefix=path_prefix, marker=marker) res = p.list_instance_profiles_response.list_instance_profiles_result profiles += res.instance_profiles marker = getattr(res, 'marker', None) return profiles def list_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' List all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.list_instance_profiles ''' p = get_all_instance_profiles(path_prefix, region, key, keyid, profile) return [i['instance_profile_name'] for i in p] def get_all_group_policies(group_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a group. CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_group_policies mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False try: response = conn.get_all_group_policies(group_name) _list = response.list_group_policies_response.list_group_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def delete_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _group = get_group( group_name, region, key, keyid, profile ) if not _group: return True try: conn.delete_group(group_name) log.info('Successfully deleted IAM group %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM group %s.', group_name) return False def create_login_profile(user_name, password, region=None, key=None, keyid=None, profile=None): ''' Creates a login profile for the specified user, give the user the ability to access AWS services and the AWS Management Console. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_login_profile user_name password ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.create_login_profile(user_name, password) log.info('Created profile for IAM user %s.', user_name) return info except boto.exception.BotoServerError as e: log.debug(e) if 'Conflict' in e: log.info('Profile already exists for IAM user %s.', user_name) return 'Conflict' log.error('Failed to update profile for IAM user %s.', user_name) return False def delete_login_profile(user_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a login profile for the specified user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_login_profile user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.delete_login_profile(user_name) log.info('Deleted login profile for IAM user %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Login profile already deleted for IAM user %s.', user_name) return True log.error('Failed to delete login profile for IAM user %s.', user_name) return False def get_all_mfa_devices(user_name, region=None, key=None, keyid=None, profile=None): ''' Get all MFA devices associated with an IAM user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_mfa_devices user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: result = conn.get_all_mfa_devices(user_name) devices = result['list_mfa_devices_response']['list_mfa_devices_result']['mfa_devices'] return devices except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Could not find IAM user %s.', user_name) return [] log.error('Failed to get all MFA devices for IAM user %s.', user_name) return False def deactivate_mfa_device(user_name, serial, region=None, key=None, keyid=None, profile=None): ''' Deactivates the specified MFA device and removes it from association with the user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.deactivate_mfa_device user_name serial_num ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.deactivate_mfa_device(user_name, serial) log.info('Deactivated MFA device %s for IAM user %s.', serial, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('MFA device %s not associated with IAM user %s.', serial, user_name) return True log.error('Failed to deactivate MFA device %s for IAM user %s.', serial, user_name) return False def delete_virtual_mfa_device(serial, region=None, key=None, keyid=None, profile=None): ''' Deletes the specified virtual MFA device. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_virtual_mfa_device serial_num ''' conn = __utils__['boto3.get_connection_func']('iam')() try: conn.delete_virtual_mfa_device(SerialNumber=serial) log.info('Deleted virtual MFA device %s.', serial) return True except botocore.exceptions.ClientError as e: log.debug(e) if 'NoSuchEntity' in six.text_type(e): log.info('Virtual MFA device %s not found.', serial) return True log.error('Failed to delete virtual MFA device %s.', serial) return False def update_account_password_policy(allow_users_to_change_password=None, hard_expiry=None, max_password_age=None, minimum_password_length=None, password_reuse_prevention=None, require_lowercase_characters=None, require_numbers=None, require_symbols=None, require_uppercase_characters=None, region=None, key=None, keyid=None, profile=None): ''' Update the password policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_account_password_policy True ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.update_account_password_policy(allow_users_to_change_password, hard_expiry, max_password_age, minimum_password_length, password_reuse_prevention, require_lowercase_characters, require_numbers, require_symbols, require_uppercase_characters) log.info('The password policy has been updated.') return True except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy' log.error(msg) return False def get_account_policy(region=None, key=None, keyid=None, profile=None): ''' Get account policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_account_password_policy() return info.get_account_password_policy_response.get_account_password_policy_result.password_policy except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy.' log.error(msg) return False def create_role(name, policy_document=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Create an instance role. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if role_exists(name, region, key, keyid, profile): return True if not policy_document: policy_document = None try: conn.create_role(name, assume_role_policy_document=policy_document, path=path) log.info('Created IAM role %s.', name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to create IAM role %s.', name) return False def delete_role(name, region=None, key=None, keyid=None, profile=None): ''' Delete an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(name, region, key, keyid, profile): return True try: conn.delete_role(name) log.info('Deleted %s IAM role.', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s IAM role.', name) return False def profile_associated(role_name, profile_name, region, key, keyid, profile): ''' Check to see if an instance profile is associated with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.profile_associated myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # The IAM module of boto doesn't return objects. Instead you need to grab # values through its properties. Sigh. try: profiles = conn.list_instance_profiles_for_role(role_name) except boto.exception.BotoServerError as e: log.debug(e) return False profiles = profiles.list_instance_profiles_for_role_response profiles = profiles.list_instance_profiles_for_role_result profiles = profiles.instance_profiles for profile in profiles: if profile.instance_profile_name == profile_name: return True return False def associate_profile_to_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Associate an instance profile with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.associate_profile_to_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if associated: return True else: try: conn.add_role_to_instance_profile(profile_name, role_name) log.info('Added %s instance profile to IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add %s instance profile to IAM role %s', profile_name, role_name) return False def disassociate_profile_from_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Disassociate an instance profile from an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.disassociate_profile_from_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if not associated: return True else: try: conn.remove_role_from_instance_profile(profile_name, role_name) log.info('Removed %s instance profile from IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove %s instance profile from IAM role %s.', profile_name, role_name) return False def list_role_policies(role_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_role_policies myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_role_policies(role_name) _list = response.list_role_policies_response.list_role_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def get_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.get_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: _policy = conn.get_role_policy(role_name, policy_name) # I _hate_ you for not giving me an object boto. _policy = _policy.get_role_policy_response.policy_document # Policy is url encoded _policy = _unquote(_policy) _policy = salt.utils.json.loads(_policy, object_pairs_hook=odict.OrderedDict) return _policy except boto.exception.BotoServerError: return {} def create_role_policy(role_name, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Create or modify a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role_policy myirole mypolicy '{"MyPolicy": "Statement": [{"Action": ["sqs:*"], "Effect": "Allow", "Resource": ["arn:aws:sqs:*:*:*"], "Sid": "MyPolicySqs1"}]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) mode = 'create' if _policy: if _policy == policy: return True mode = 'modify' if isinstance(policy, six.string_types): policy = salt.utils.json.loads(policy, object_pairs_hook=odict.OrderedDict) try: _policy = salt.utils.json.dumps(policy) conn.put_role_policy(role_name, policy_name, _policy) if mode == 'create': msg = 'Successfully added policy %s to IAM role %s.' else: msg = 'Successfully modified policy %s for IAM role %s.' log.info(msg, policy_name, role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to %s policy %s for IAM role %s.', mode, policy_name, role_name) return False def delete_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) if not _policy: return True try: conn.delete_role_policy(role_name, policy_name) log.info('Successfully deleted policy %s for IAM role %s.', policy_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM role %s.', policy_name, role_name) return False def update_assume_role_policy(role_name, policy_document, region=None, key=None, keyid=None, profile=None): ''' Update an assume role policy for a role. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_assume_role_policy myrole '{"Statement":"..."}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(policy_document, six.string_types): policy_document = salt.utils.json.loads(policy_document, object_pairs_hook=odict.OrderedDict) try: _policy_document = salt.utils.json.dumps(policy_document) conn.update_assume_role_policy(role_name, _policy_document) log.info('Successfully updated assume role policy for IAM role %s.', role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to update assume role policy for IAM role %s.', role_name) return False def build_policy(region=None, key=None, keyid=None, profile=None): ''' Build a default assume role policy. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.build_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if hasattr(conn, 'build_policy'): policy = salt.utils.json.loads(conn.build_policy()) elif hasattr(conn, '_build_policy'): policy = salt.utils.json.loads(conn._build_policy()) else: return {} # The format we get from build_policy isn't going to be what we get back # from AWS for the exact same policy. AWS converts single item list values # into strings, so let's do the same here. for key, policy_val in policy.items(): for statement in policy_val: if (isinstance(statement['Action'], list) and len(statement['Action']) == 1): statement['Action'] = statement['Action'][0] if (isinstance(statement['Principal']['Service'], list) and len(statement['Principal']['Service']) == 1): statement['Principal']['Service'] = statement['Principal']['Service'][0] # build_policy doesn't add a version field, which AWS is going to set to a # default value, when we get it back, so let's set it. policy['Version'] = '2008-10-17' return policy def get_account_id(region=None, key=None, keyid=None, profile=None): ''' Get a the AWS account id associated with the used credentials. CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_id ''' cache_key = 'boto_iam.account_id' if cache_key not in __context__: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_user() # The get_user call returns an user ARN: # arn:aws:iam::027050522557:user/salt-test arn = ret['get_user_response']['get_user_result']['user']['arn'] account_id = arn.split(':')[4] except boto.exception.BotoServerError: # If call failed, then let's try to get the ARN from the metadata timeout = boto.config.getfloat( 'Boto', 'metadata_service_timeout', 1.0 ) attempts = boto.config.getint( 'Boto', 'metadata_service_num_attempts', 1 ) identity = boto.utils.get_instance_identity( timeout=timeout, num_retries=attempts ) try: account_id = identity['document']['accountId'] except KeyError: log.error('Failed to get account id from instance_identity in' ' boto_iam.get_account_id.') __context__[cache_key] = account_id return __context__[cache_key] def get_all_roles(path_prefix=None, region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM role details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_roles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _roles = conn.list_roles(path_prefix=path_prefix) roles = _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) while marker: _roles = conn.list_roles(path_prefix=path_prefix, marker=marker) roles = roles + _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) return roles def get_all_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM user details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_users ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _users = conn.get_all_users(path_prefix=path_prefix) users = _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) while marker: _users = conn.get_all_users(path_prefix=path_prefix, marker=marker) users = users + _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) return users def get_all_user_policies(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all user policies. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_user_policies myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_all_user_policies(user_name, marker, max_items) if not info: return False _list = info.list_user_policies_response.list_user_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policies for user %s.', user_name) return False def get_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user_policy myuser mypolicyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user_policy(user_name, policy_name) log.debug('Info for IAM user %s policy %s: %s.', user_name, policy_name, info) if not info: return False info = info.get_user_policy_response.get_user_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policy %s for IAM user %s.', policy_name, user_name) return False def put_user_policy(user_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_user_policy myuser policyname policyrules ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_user_policy(user_name, policy_name, policy_json) if created: log.info('Created policy %s for IAM user %s.', policy_name, user_name) return True log.error('Could not create policy %s for IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy %s for IAM user %s.', policy_name, user_name) return False def delete_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user_policy myuser mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_user_policy( user_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_user_policy(user_name, policy_name) log.info('Successfully deleted policy %s for IAM user %s.', policy_name, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM user %s.', policy_name, user_name) return False def upload_server_cert(cert_name, cert_body, private_key, cert_chain=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Upload a certificate to Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.upload_server_cert mycert_name crt priv_key :param cert_name: The name for the server certificate. Do not include the path in this value. :param cert_body: The contents of the public key certificate in PEM-encoded format. :param private_key: The contents of the private key in PEM-encoded format. :param cert_chain: The contents of the certificate chain. This is typically a concatenation of the PEM-encoded public key certificates of the chain. :param path: The path for the server certificate. :param region: The name of the region to connect to. :param key: The key to be used in order to connect :param keyid: The keyid to be used in order to connect :param profile: The profile that contains a dict of region, key, keyid :return: True / False ''' exists = get_server_certificate(cert_name, region, key, keyid, profile) if exists: return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.upload_server_cert(cert_name, cert_body, private_key, cert_chain) log.info('Created certificate %s.', cert_name) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to failed to create certificate %s.', cert_name) return False def list_server_certificates(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Lists the server certificates stored in IAM that have the specified path prefix. .. versionadded:: ??? :param path_prefix: The path prefix for filtering the results. For example: /company/servercerts would get all server certificates for which the path starts with /company/servercerts . This parameter is optional. If it is not included, it defaults to a slash (/), listing all server certificates. This parameter allows (per its regex pattern) a string of characters consisting of either a forward slash (/) by itself or a string that must begin and end with forward slashes. In addition, it can contain any ASCII character from the ! (u0021) through the DEL character (u007F), including most punctuation characters, digits, and upper and lowercased letters. CLI Example: .. code-block:: bash salt myminion boto_iam.list_server_certificates path_prefix=/somepath/ ''' retries = 10 sleep = 6 conn = __utils__['boto3.get_connection']('iam', region=region, key=key, keyid=keyid, profile=profile) Items = [] while retries: try: log.debug('Garnering list of IAM Server Certificates') IsTruncated = True while IsTruncated: kwargs = {'PathPrefix': path_prefix} ret = conn.list_server_certificates(**kwargs) Items += ret.get('ServerCertificateMetadataList', []) IsTruncated = ret.get('IsTruncated') kwargs.update({'Marker': ret.get('Marker')}) return Items except botocore.exceptions.ParamValidationError as err: raise SaltInvocationError(str(err)) except botocore.exceptions.ClientError as err: if retries and jmespath.search('Error.Code', err.response) == 'Throttling': retries -= 1 log.debug('Throttled by AWS API, retrying in %s seconds...', sleep) time.sleep(sleep) continue log.error('Failed to list IAM Server Certificates: %s', err.message) return None def get_server_certificate(cert_name, region=None, key=None, keyid=None, profile=None): ''' Returns certificate information from Amazon .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_server_certificate mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_server_certificate(cert_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get certificate %s information.', cert_name) return False def delete_server_cert(cert_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a certificate from Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_server_cert mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_server_cert(cert_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete certificate %s.', cert_name) return False def export_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM user details. Produces results that can be used to create an sls file. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.export_users --out=txt | sed "s/local: //" > iam_users.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() users = get_all_users(path_prefix, region, key, keyid, profile) for user in users: name = user.user_name _policies = conn.get_all_user_policies(name, max_items=100) _policies = _policies.list_user_policies_response.list_user_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_user_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_user_policy_response.get_user_policy_result.policy_document )) policies[policy_name] = _policy user_sls = [] user_sls.append({"name": name}) user_sls.append({"policies": policies}) user_sls.append({"path": user.path}) results["manage user " + name] = {"boto_iam.user_present": user_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def export_roles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM role details. Produces results that can be used to create an sls file. CLI Example: salt-call boto_iam.export_roles --out=txt | sed "s/local: //" > iam_roles.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() roles = get_all_roles(path_prefix, region, key, keyid, profile) for role in roles: name = role.role_name _policies = conn.list_role_policies(name, max_items=100) _policies = _policies.list_role_policies_response.list_role_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_role_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_role_policy_response.get_role_policy_result.policy_document )) policies[policy_name] = _policy role_sls = [] role_sls.append({"name": name}) role_sls.append({"policies": policies}) role_sls.append({'policy_document': salt.utils.json.loads(_unquote(role.assume_role_policy_document))}) role_sls.append({"path": role.path}) results["manage role " + name] = {"boto_iam_role.present": role_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def _get_policy_arn(name, region=None, key=None, keyid=None, profile=None): if name.startswith('arn:aws:iam:'): return name account_id = get_account_id( region=region, key=key, keyid=keyid, profile=profile ) return 'arn:aws:iam::{0}:policy/{1}'.format(account_id, name) def policy_exists(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return True except boto.exception.BotoServerError: return False def get_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return ret.get('get_policy_response', {}).get('get_policy_result', {}) except boto.exception.BotoServerError: return None def create_policy(policy_name, policy_document, path=None, description=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in 'path', 'description': if locals()[arg] is not None: params[arg] = locals()[arg] if policy_exists(policy_name, region, key, keyid, profile): return True try: conn.create_policy(policy_name, policy_document, **params) log.info('Created IAM policy %s.', policy_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s.', policy_name) return False return True def delete_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_exists(policy_arn, region, key, keyid, profile): return True try: conn.delete_policy(policy_arn) log.info('Deleted %s policy.', policy_name) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete %s policy: %s.', policy_name, aws.get('message')) return False return True def list_policies(region=None, key=None, keyid=None, profile=None): ''' List policies. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policies ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: policies = [] for ret in __utils__['boto.paged_call'](conn.list_policies): policies.append(ret.get('list_policies_response', {}).get('list_policies_result', {}).get('policies')) return policies except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to list policy versions.' log.error(msg) return [] def policy_version_exists(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.get_policy_version(policy_arn, version_id) return True except boto.exception.BotoServerError: return False def get_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy_version(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile), version_id) retval = ret.get('get_policy_version_response', {}).get('get_policy_version_result', {}).get('policy_version', {}) retval['document'] = _unquote(retval.get('document')) return {'policy_version': retval} except boto.exception.BotoServerError: return None def create_policy_version(policy_name, policy_document, set_as_default=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy version. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy_version mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in ('set_as_default',): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.create_policy_version(policy_arn, policy_document, **params) vid = ret.get('create_policy_version_response', {}).get('create_policy_version_result', {}).get('policy_version', {}).get('version_id') log.info('Created IAM policy %s version %s.', policy_name, vid) return {'created': True, 'version_id': vid} except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s version %s.', policy_name, vid) return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Delete a policy version. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_version_exists(policy_arn, version_id, region, key, keyid, profile): return True try: conn.delete_policy_version(policy_arn, version_id) log.info('Deleted IAM policy %s version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete IAM policy %s version %s: %s', policy_name, version_id, aws.get('message')) return False return True def list_policy_versions(policy_name, region=None, key=None, keyid=None, profile=None): ''' List versions of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policy_versions mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.list_policy_versions(policy_arn) return ret.get('list_policy_versions_response', {}).get('list_policy_versions_result', {}).get('versions') except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list versions for IAM policy %s.', policy_name) return [] def set_default_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Set the default version of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.set_default_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.set_default_policy_version(policy_arn, version_id) log.info('Set %s policy to version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to set %s policy to version %s: %s', policy_name, version_id, aws.get('message')) return False return True def attach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_user_policy(policy_arn, user_name) log.info('Attached policy %s to IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach %s policy to IAM user %s.', policy_name, user_name) return False return True def detach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_user_policy(policy_arn, user_name) log.info('Detached %s policy from IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach %s policy from IAM user %s.', policy_name, user_name) return False return True def attach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_group_policy(policy_arn, group_name) log.info('Attached policy %s to IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM group %s.', policy_name, group_name) return False return True def detach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_group_policy(policy_arn, group_name) log.info('Detached policy %s from IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM group %s.', policy_name, group_name) return False return True def attach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_role_policy(policy_arn, role_name) log.info('Attached policy %s to IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM role %s.', policy_name, role_name) return False return True def detach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_role_policy(policy_arn, role_name) log.info('Detached policy %s from IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM role %s.', policy_name, role_name) return False return True def list_entities_for_policy(policy_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities that a policy is attached to. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 params = {} for arg in ('path_prefix', 'entity_filter'): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) while retries: try: allret = { 'policy_groups': [], 'policy_users': [], 'policy_roles': [], } for ret in __utils__['boto.paged_call'](conn.list_entities_for_policy, policy_arn=policy_arn, **params): for k, v in six.iteritems(allret): v.extend(ret.get('list_entities_for_policy_response', {}).get('list_entities_for_policy_result', {}).get(k)) return allret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('Failed to list entities for IAM policy %s: %s', policy_name, e.message) return {} return {} def list_attached_user_policies(user_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given user. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'UserName': user_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedUserPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_user_policies_response', {}).get('list_attached_user_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM user %s.', user_name) return [] def list_attached_group_policies(group_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given group. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'GroupName': group_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedGroupPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_group_policies_response', {}).get('list_attached_group_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM group %s.', group_name) return [] def list_attached_role_policies(role_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'RoleName': role_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedRolePolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_role_policies_response', {}).get('list_attached_role_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM role %s.', role_name) return [] def create_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Create SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.create_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_saml_provider(saml_metadata_document, name) log.info('Successfully created %s SAML provider.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to create SAML provider %s.', name) return False def get_saml_provider_arn(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider_arn my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_saml_providers() for saml_provider in response.list_saml_providers_response.list_saml_providers_result.saml_provider_list: if saml_provider['arn'].endswith(':saml-provider/' + name): return saml_provider['arn'] return False except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to get ARN of SAML provider %s.', name) return False def delete_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Delete SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.delete_saml_provider my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return True conn.delete_saml_provider(saml_provider_arn) log.info('Successfully deleted SAML provider %s.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete SAML provider %s.', name) return False def list_saml_providers(region=None, key=None, keyid=None, profile=None): ''' List SAML providers. CLI Example: .. code-block:: bash salt myminion boto_iam.list_saml_providers ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: providers = [] info = conn.list_saml_providers() for arn in info['list_saml_providers_response']['list_saml_providers_result']['saml_provider_list']: providers.append(arn['arn'].rsplit('/', 1)[1]) return providers except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get list of SAML providers.') return False def get_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider document. CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider arn ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: provider = conn.get_saml_provider(name) return provider['get_saml_provider_response']['get_saml_provider_result']['saml_metadata_document'] except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get SAML provider document %s.', name) return False def update_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Update SAML provider. CLI Example: .. code-block:: bash salt myminion boto_iam.update_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return False if conn.update_saml_provider(name, saml_metadata_document): return True return False except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to update SAML provider %s.', name) return False
saltstack/salt
salt/modules/boto_iam.py
get_group_members
python
def get_group_members(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: marker = None truncated = True users = [] while truncated: info = conn.get_group(group_name, marker=marker, max_items=1000) if not info: return False truncated = bool(info['get_group_response']['get_group_result']['is_truncated']) if truncated and 'marker' in info['get_group_response']['get_group_result']: marker = info['get_group_response']['get_group_result']['marker'] else: marker = None truncated = False users += info['get_group_response']['get_group_result']['users'] return users except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get members for IAM group %s.', group_name) return False
Get group information. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iam.py#L408-L440
null
# -*- coding: utf-8 -*- ''' Connection module for Amazon IAM .. versionadded:: 2014.7.0 :configuration: This module accepts explicit iam 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 iam.keyid: GKTADJGHEIQSXMKKRBJ08H iam.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs iam.region: 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: boto ''' # keep lint from choking on _get_conn and _cache_id #pylint: disable=E0602 # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import salt libs from salt.ext import six import salt.utils.compat import salt.utils.json import salt.utils.odict as odict import salt.utils.versions from salt.exceptions import SaltInvocationError # Import third party libs # pylint: disable=unused-import from salt.ext.six.moves.urllib.parse import unquote as _unquote # pylint: disable=no-name-in-module try: import boto import boto.iam import boto3 import botocore logging.getLogger('boto').setLevel(logging.CRITICAL) logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=unused-import log = logging.getLogger(__name__) def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'iam', pack=__salt__) def instance_profile_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an instance profile exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: # Boto weirdly returns an exception here if an instance profile doesn't # exist. conn.get_instance_profile(name) return True except boto.exception.BotoServerError: return False def create_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Create an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.create_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if instance_profile_exists(name, region, key, keyid, profile): return True try: # This call returns an instance profile if successful and an exception # if not. It's annoying. conn.create_instance_profile(name) log.info('Created %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create %s instance profile.', name) return False return True def delete_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Delete an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not instance_profile_exists(name, region, key, keyid, profile): return True try: conn.delete_instance_profile(name) log.info('Deleted %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s instance profile.', name) return False return True def role_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an IAM role exists. CLI Example: .. code-block:: bash salt myminion boto_iam.role_exists myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_role(name) return True except boto.exception.BotoServerError: return False def describe_role(name, region=None, key=None, keyid=None, profile=None): ''' Get information for a role. CLI Example: .. code-block:: bash salt myminion boto_iam.describe_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_role(name) if not info: return False role = info.get_role_response.get_role_result.role role['assume_role_policy_document'] = salt.utils.json.loads(_unquote( role.assume_role_policy_document )) # If Sid wasn't defined by the user, boto will still return a Sid in # each policy. To properly check idempotently, let's remove the Sid # from the return if it's not actually set. for policy_key, policy in role['assume_role_policy_document'].items(): if policy_key == 'Statement': for val in policy: if 'Sid' in val and not val['Sid']: del val['Sid'] return role except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get %s information.', name) return False def create_user(user_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_user myuser ''' if not path: path = '/' if get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_user(user_name, path) log.info('Created IAM user : %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM user %s.', user_name) return False def get_all_access_keys(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all access keys from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_access_keys myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.get_all_access_keys(user_name, marker, max_items) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get access keys for IAM user %s.', user_name) return six.text_type(e) def create_access_key(user_name, region=None, key=None, keyid=None, profile=None): ''' Create access key id for a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.create_access_key(user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create access key.') return six.text_type(e) def delete_access_key(access_key_id, user_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete access key id from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_access_key(access_key_id, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete access key id %s.', access_key_id) return six.text_type(e) def delete_user(user_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user myuser ''' if not get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.delete_user(user_name) log.info('Deleted IAM user : %s .', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM user %s', user_name) return six.text_type(e) def get_user(user_name=None, region=None, key=None, keyid=None, profile=None): ''' Get user information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user(user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM user %s info.', user_name) return False def create_group(group_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_group group ''' if not path: path = '/' if get_group(group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_group(group_name, path) log.info('Created IAM group : %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM group %s.', group_name) return False def get_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group(group_name, max_items=1) if not info: return False return info['get_group_response']['get_group_result']['group'] except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def add_user_to_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Add user to group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.add_user_to_group myuser mygroup ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('Username : %s does not exist.', user_name) return False if user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.add_user_to_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add IAM user %s to group %s.', user_name, group_name) return False def user_exists_in_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Check if user exists in group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.user_exists_in_group myuser mygroup ''' # TODO this should probably use boto.iam.get_groups_for_user users = get_group_members( group_name=group_name, region=region, key=key, keyid=keyid, profile=profile ) if users: for _user in users: if user_name == _user['user_name']: log.debug('IAM user %s is already in IAM group %s.', user_name, group_name) return True return False def remove_user_from_group(group_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Remove user from group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.remove_user_from_group mygroup myuser ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist.', user_name) return False if not user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.remove_user_from_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove IAM user %s from group %s', user_name, group_name) return False def put_group_policy(group_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_group_policy mygroup policyname policyrules ''' group = get_group(group_name, region=region, key=key, keyid=keyid, profile=profile) if not group: log.error('Group %s does not exist', group_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_group_policy(group_name, policy_name, policy_json) if created: log.info('Created policy for IAM group %s.', group_name) return True log.error('Could not create policy for IAM group %s', group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy for IAM group %s', group_name) return False def delete_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group_policy mygroup mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_group_policy( group_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_group_policy(group_name, policy_name) log.info('Successfully deleted policy %s for IAM group %s.', policy_name, group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM group %s.', policy_name, group_name) return False def get_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group_policy mygroup policyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group_policy(group_name, policy_name) log.debug('info for group policy is : %s', info) if not info: return False info = info.get_group_policy_response.get_group_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_all_groups(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM group details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_groups ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _groups = conn.get_all_groups(path_prefix=path_prefix) groups = _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) while marker: _groups = conn.get_all_groups(path_prefix=path_prefix, marker=marker) groups = groups + _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) return groups def get_all_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.get_all_instance_profiles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) marker = False profiles = [] while marker is not None: marker = marker if marker else None p = conn.list_instance_profiles(path_prefix=path_prefix, marker=marker) res = p.list_instance_profiles_response.list_instance_profiles_result profiles += res.instance_profiles marker = getattr(res, 'marker', None) return profiles def list_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' List all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.list_instance_profiles ''' p = get_all_instance_profiles(path_prefix, region, key, keyid, profile) return [i['instance_profile_name'] for i in p] def get_all_group_policies(group_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a group. CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_group_policies mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False try: response = conn.get_all_group_policies(group_name) _list = response.list_group_policies_response.list_group_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def delete_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _group = get_group( group_name, region, key, keyid, profile ) if not _group: return True try: conn.delete_group(group_name) log.info('Successfully deleted IAM group %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM group %s.', group_name) return False def create_login_profile(user_name, password, region=None, key=None, keyid=None, profile=None): ''' Creates a login profile for the specified user, give the user the ability to access AWS services and the AWS Management Console. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_login_profile user_name password ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.create_login_profile(user_name, password) log.info('Created profile for IAM user %s.', user_name) return info except boto.exception.BotoServerError as e: log.debug(e) if 'Conflict' in e: log.info('Profile already exists for IAM user %s.', user_name) return 'Conflict' log.error('Failed to update profile for IAM user %s.', user_name) return False def delete_login_profile(user_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a login profile for the specified user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_login_profile user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.delete_login_profile(user_name) log.info('Deleted login profile for IAM user %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Login profile already deleted for IAM user %s.', user_name) return True log.error('Failed to delete login profile for IAM user %s.', user_name) return False def get_all_mfa_devices(user_name, region=None, key=None, keyid=None, profile=None): ''' Get all MFA devices associated with an IAM user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_mfa_devices user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: result = conn.get_all_mfa_devices(user_name) devices = result['list_mfa_devices_response']['list_mfa_devices_result']['mfa_devices'] return devices except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Could not find IAM user %s.', user_name) return [] log.error('Failed to get all MFA devices for IAM user %s.', user_name) return False def deactivate_mfa_device(user_name, serial, region=None, key=None, keyid=None, profile=None): ''' Deactivates the specified MFA device and removes it from association with the user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.deactivate_mfa_device user_name serial_num ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.deactivate_mfa_device(user_name, serial) log.info('Deactivated MFA device %s for IAM user %s.', serial, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('MFA device %s not associated with IAM user %s.', serial, user_name) return True log.error('Failed to deactivate MFA device %s for IAM user %s.', serial, user_name) return False def delete_virtual_mfa_device(serial, region=None, key=None, keyid=None, profile=None): ''' Deletes the specified virtual MFA device. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_virtual_mfa_device serial_num ''' conn = __utils__['boto3.get_connection_func']('iam')() try: conn.delete_virtual_mfa_device(SerialNumber=serial) log.info('Deleted virtual MFA device %s.', serial) return True except botocore.exceptions.ClientError as e: log.debug(e) if 'NoSuchEntity' in six.text_type(e): log.info('Virtual MFA device %s not found.', serial) return True log.error('Failed to delete virtual MFA device %s.', serial) return False def update_account_password_policy(allow_users_to_change_password=None, hard_expiry=None, max_password_age=None, minimum_password_length=None, password_reuse_prevention=None, require_lowercase_characters=None, require_numbers=None, require_symbols=None, require_uppercase_characters=None, region=None, key=None, keyid=None, profile=None): ''' Update the password policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_account_password_policy True ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.update_account_password_policy(allow_users_to_change_password, hard_expiry, max_password_age, minimum_password_length, password_reuse_prevention, require_lowercase_characters, require_numbers, require_symbols, require_uppercase_characters) log.info('The password policy has been updated.') return True except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy' log.error(msg) return False def get_account_policy(region=None, key=None, keyid=None, profile=None): ''' Get account policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_account_password_policy() return info.get_account_password_policy_response.get_account_password_policy_result.password_policy except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy.' log.error(msg) return False def create_role(name, policy_document=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Create an instance role. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if role_exists(name, region, key, keyid, profile): return True if not policy_document: policy_document = None try: conn.create_role(name, assume_role_policy_document=policy_document, path=path) log.info('Created IAM role %s.', name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to create IAM role %s.', name) return False def delete_role(name, region=None, key=None, keyid=None, profile=None): ''' Delete an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(name, region, key, keyid, profile): return True try: conn.delete_role(name) log.info('Deleted %s IAM role.', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s IAM role.', name) return False def profile_associated(role_name, profile_name, region, key, keyid, profile): ''' Check to see if an instance profile is associated with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.profile_associated myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # The IAM module of boto doesn't return objects. Instead you need to grab # values through its properties. Sigh. try: profiles = conn.list_instance_profiles_for_role(role_name) except boto.exception.BotoServerError as e: log.debug(e) return False profiles = profiles.list_instance_profiles_for_role_response profiles = profiles.list_instance_profiles_for_role_result profiles = profiles.instance_profiles for profile in profiles: if profile.instance_profile_name == profile_name: return True return False def associate_profile_to_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Associate an instance profile with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.associate_profile_to_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if associated: return True else: try: conn.add_role_to_instance_profile(profile_name, role_name) log.info('Added %s instance profile to IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add %s instance profile to IAM role %s', profile_name, role_name) return False def disassociate_profile_from_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Disassociate an instance profile from an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.disassociate_profile_from_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if not associated: return True else: try: conn.remove_role_from_instance_profile(profile_name, role_name) log.info('Removed %s instance profile from IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove %s instance profile from IAM role %s.', profile_name, role_name) return False def list_role_policies(role_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_role_policies myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_role_policies(role_name) _list = response.list_role_policies_response.list_role_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def get_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.get_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: _policy = conn.get_role_policy(role_name, policy_name) # I _hate_ you for not giving me an object boto. _policy = _policy.get_role_policy_response.policy_document # Policy is url encoded _policy = _unquote(_policy) _policy = salt.utils.json.loads(_policy, object_pairs_hook=odict.OrderedDict) return _policy except boto.exception.BotoServerError: return {} def create_role_policy(role_name, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Create or modify a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role_policy myirole mypolicy '{"MyPolicy": "Statement": [{"Action": ["sqs:*"], "Effect": "Allow", "Resource": ["arn:aws:sqs:*:*:*"], "Sid": "MyPolicySqs1"}]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) mode = 'create' if _policy: if _policy == policy: return True mode = 'modify' if isinstance(policy, six.string_types): policy = salt.utils.json.loads(policy, object_pairs_hook=odict.OrderedDict) try: _policy = salt.utils.json.dumps(policy) conn.put_role_policy(role_name, policy_name, _policy) if mode == 'create': msg = 'Successfully added policy %s to IAM role %s.' else: msg = 'Successfully modified policy %s for IAM role %s.' log.info(msg, policy_name, role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to %s policy %s for IAM role %s.', mode, policy_name, role_name) return False def delete_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) if not _policy: return True try: conn.delete_role_policy(role_name, policy_name) log.info('Successfully deleted policy %s for IAM role %s.', policy_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM role %s.', policy_name, role_name) return False def update_assume_role_policy(role_name, policy_document, region=None, key=None, keyid=None, profile=None): ''' Update an assume role policy for a role. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_assume_role_policy myrole '{"Statement":"..."}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(policy_document, six.string_types): policy_document = salt.utils.json.loads(policy_document, object_pairs_hook=odict.OrderedDict) try: _policy_document = salt.utils.json.dumps(policy_document) conn.update_assume_role_policy(role_name, _policy_document) log.info('Successfully updated assume role policy for IAM role %s.', role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to update assume role policy for IAM role %s.', role_name) return False def build_policy(region=None, key=None, keyid=None, profile=None): ''' Build a default assume role policy. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.build_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if hasattr(conn, 'build_policy'): policy = salt.utils.json.loads(conn.build_policy()) elif hasattr(conn, '_build_policy'): policy = salt.utils.json.loads(conn._build_policy()) else: return {} # The format we get from build_policy isn't going to be what we get back # from AWS for the exact same policy. AWS converts single item list values # into strings, so let's do the same here. for key, policy_val in policy.items(): for statement in policy_val: if (isinstance(statement['Action'], list) and len(statement['Action']) == 1): statement['Action'] = statement['Action'][0] if (isinstance(statement['Principal']['Service'], list) and len(statement['Principal']['Service']) == 1): statement['Principal']['Service'] = statement['Principal']['Service'][0] # build_policy doesn't add a version field, which AWS is going to set to a # default value, when we get it back, so let's set it. policy['Version'] = '2008-10-17' return policy def get_account_id(region=None, key=None, keyid=None, profile=None): ''' Get a the AWS account id associated with the used credentials. CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_id ''' cache_key = 'boto_iam.account_id' if cache_key not in __context__: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_user() # The get_user call returns an user ARN: # arn:aws:iam::027050522557:user/salt-test arn = ret['get_user_response']['get_user_result']['user']['arn'] account_id = arn.split(':')[4] except boto.exception.BotoServerError: # If call failed, then let's try to get the ARN from the metadata timeout = boto.config.getfloat( 'Boto', 'metadata_service_timeout', 1.0 ) attempts = boto.config.getint( 'Boto', 'metadata_service_num_attempts', 1 ) identity = boto.utils.get_instance_identity( timeout=timeout, num_retries=attempts ) try: account_id = identity['document']['accountId'] except KeyError: log.error('Failed to get account id from instance_identity in' ' boto_iam.get_account_id.') __context__[cache_key] = account_id return __context__[cache_key] def get_all_roles(path_prefix=None, region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM role details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_roles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _roles = conn.list_roles(path_prefix=path_prefix) roles = _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) while marker: _roles = conn.list_roles(path_prefix=path_prefix, marker=marker) roles = roles + _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) return roles def get_all_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM user details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_users ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _users = conn.get_all_users(path_prefix=path_prefix) users = _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) while marker: _users = conn.get_all_users(path_prefix=path_prefix, marker=marker) users = users + _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) return users def get_all_user_policies(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all user policies. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_user_policies myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_all_user_policies(user_name, marker, max_items) if not info: return False _list = info.list_user_policies_response.list_user_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policies for user %s.', user_name) return False def get_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user_policy myuser mypolicyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user_policy(user_name, policy_name) log.debug('Info for IAM user %s policy %s: %s.', user_name, policy_name, info) if not info: return False info = info.get_user_policy_response.get_user_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policy %s for IAM user %s.', policy_name, user_name) return False def put_user_policy(user_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_user_policy myuser policyname policyrules ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_user_policy(user_name, policy_name, policy_json) if created: log.info('Created policy %s for IAM user %s.', policy_name, user_name) return True log.error('Could not create policy %s for IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy %s for IAM user %s.', policy_name, user_name) return False def delete_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user_policy myuser mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_user_policy( user_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_user_policy(user_name, policy_name) log.info('Successfully deleted policy %s for IAM user %s.', policy_name, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM user %s.', policy_name, user_name) return False def upload_server_cert(cert_name, cert_body, private_key, cert_chain=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Upload a certificate to Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.upload_server_cert mycert_name crt priv_key :param cert_name: The name for the server certificate. Do not include the path in this value. :param cert_body: The contents of the public key certificate in PEM-encoded format. :param private_key: The contents of the private key in PEM-encoded format. :param cert_chain: The contents of the certificate chain. This is typically a concatenation of the PEM-encoded public key certificates of the chain. :param path: The path for the server certificate. :param region: The name of the region to connect to. :param key: The key to be used in order to connect :param keyid: The keyid to be used in order to connect :param profile: The profile that contains a dict of region, key, keyid :return: True / False ''' exists = get_server_certificate(cert_name, region, key, keyid, profile) if exists: return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.upload_server_cert(cert_name, cert_body, private_key, cert_chain) log.info('Created certificate %s.', cert_name) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to failed to create certificate %s.', cert_name) return False def list_server_certificates(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Lists the server certificates stored in IAM that have the specified path prefix. .. versionadded:: ??? :param path_prefix: The path prefix for filtering the results. For example: /company/servercerts would get all server certificates for which the path starts with /company/servercerts . This parameter is optional. If it is not included, it defaults to a slash (/), listing all server certificates. This parameter allows (per its regex pattern) a string of characters consisting of either a forward slash (/) by itself or a string that must begin and end with forward slashes. In addition, it can contain any ASCII character from the ! (u0021) through the DEL character (u007F), including most punctuation characters, digits, and upper and lowercased letters. CLI Example: .. code-block:: bash salt myminion boto_iam.list_server_certificates path_prefix=/somepath/ ''' retries = 10 sleep = 6 conn = __utils__['boto3.get_connection']('iam', region=region, key=key, keyid=keyid, profile=profile) Items = [] while retries: try: log.debug('Garnering list of IAM Server Certificates') IsTruncated = True while IsTruncated: kwargs = {'PathPrefix': path_prefix} ret = conn.list_server_certificates(**kwargs) Items += ret.get('ServerCertificateMetadataList', []) IsTruncated = ret.get('IsTruncated') kwargs.update({'Marker': ret.get('Marker')}) return Items except botocore.exceptions.ParamValidationError as err: raise SaltInvocationError(str(err)) except botocore.exceptions.ClientError as err: if retries and jmespath.search('Error.Code', err.response) == 'Throttling': retries -= 1 log.debug('Throttled by AWS API, retrying in %s seconds...', sleep) time.sleep(sleep) continue log.error('Failed to list IAM Server Certificates: %s', err.message) return None def get_server_certificate(cert_name, region=None, key=None, keyid=None, profile=None): ''' Returns certificate information from Amazon .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_server_certificate mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_server_certificate(cert_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get certificate %s information.', cert_name) return False def delete_server_cert(cert_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a certificate from Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_server_cert mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_server_cert(cert_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete certificate %s.', cert_name) return False def export_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM user details. Produces results that can be used to create an sls file. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.export_users --out=txt | sed "s/local: //" > iam_users.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() users = get_all_users(path_prefix, region, key, keyid, profile) for user in users: name = user.user_name _policies = conn.get_all_user_policies(name, max_items=100) _policies = _policies.list_user_policies_response.list_user_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_user_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_user_policy_response.get_user_policy_result.policy_document )) policies[policy_name] = _policy user_sls = [] user_sls.append({"name": name}) user_sls.append({"policies": policies}) user_sls.append({"path": user.path}) results["manage user " + name] = {"boto_iam.user_present": user_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def export_roles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM role details. Produces results that can be used to create an sls file. CLI Example: salt-call boto_iam.export_roles --out=txt | sed "s/local: //" > iam_roles.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() roles = get_all_roles(path_prefix, region, key, keyid, profile) for role in roles: name = role.role_name _policies = conn.list_role_policies(name, max_items=100) _policies = _policies.list_role_policies_response.list_role_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_role_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_role_policy_response.get_role_policy_result.policy_document )) policies[policy_name] = _policy role_sls = [] role_sls.append({"name": name}) role_sls.append({"policies": policies}) role_sls.append({'policy_document': salt.utils.json.loads(_unquote(role.assume_role_policy_document))}) role_sls.append({"path": role.path}) results["manage role " + name] = {"boto_iam_role.present": role_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def _get_policy_arn(name, region=None, key=None, keyid=None, profile=None): if name.startswith('arn:aws:iam:'): return name account_id = get_account_id( region=region, key=key, keyid=keyid, profile=profile ) return 'arn:aws:iam::{0}:policy/{1}'.format(account_id, name) def policy_exists(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return True except boto.exception.BotoServerError: return False def get_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return ret.get('get_policy_response', {}).get('get_policy_result', {}) except boto.exception.BotoServerError: return None def create_policy(policy_name, policy_document, path=None, description=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in 'path', 'description': if locals()[arg] is not None: params[arg] = locals()[arg] if policy_exists(policy_name, region, key, keyid, profile): return True try: conn.create_policy(policy_name, policy_document, **params) log.info('Created IAM policy %s.', policy_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s.', policy_name) return False return True def delete_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_exists(policy_arn, region, key, keyid, profile): return True try: conn.delete_policy(policy_arn) log.info('Deleted %s policy.', policy_name) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete %s policy: %s.', policy_name, aws.get('message')) return False return True def list_policies(region=None, key=None, keyid=None, profile=None): ''' List policies. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policies ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: policies = [] for ret in __utils__['boto.paged_call'](conn.list_policies): policies.append(ret.get('list_policies_response', {}).get('list_policies_result', {}).get('policies')) return policies except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to list policy versions.' log.error(msg) return [] def policy_version_exists(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.get_policy_version(policy_arn, version_id) return True except boto.exception.BotoServerError: return False def get_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy_version(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile), version_id) retval = ret.get('get_policy_version_response', {}).get('get_policy_version_result', {}).get('policy_version', {}) retval['document'] = _unquote(retval.get('document')) return {'policy_version': retval} except boto.exception.BotoServerError: return None def create_policy_version(policy_name, policy_document, set_as_default=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy version. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy_version mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in ('set_as_default',): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.create_policy_version(policy_arn, policy_document, **params) vid = ret.get('create_policy_version_response', {}).get('create_policy_version_result', {}).get('policy_version', {}).get('version_id') log.info('Created IAM policy %s version %s.', policy_name, vid) return {'created': True, 'version_id': vid} except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s version %s.', policy_name, vid) return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Delete a policy version. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_version_exists(policy_arn, version_id, region, key, keyid, profile): return True try: conn.delete_policy_version(policy_arn, version_id) log.info('Deleted IAM policy %s version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete IAM policy %s version %s: %s', policy_name, version_id, aws.get('message')) return False return True def list_policy_versions(policy_name, region=None, key=None, keyid=None, profile=None): ''' List versions of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policy_versions mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.list_policy_versions(policy_arn) return ret.get('list_policy_versions_response', {}).get('list_policy_versions_result', {}).get('versions') except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list versions for IAM policy %s.', policy_name) return [] def set_default_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Set the default version of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.set_default_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.set_default_policy_version(policy_arn, version_id) log.info('Set %s policy to version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to set %s policy to version %s: %s', policy_name, version_id, aws.get('message')) return False return True def attach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_user_policy(policy_arn, user_name) log.info('Attached policy %s to IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach %s policy to IAM user %s.', policy_name, user_name) return False return True def detach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_user_policy(policy_arn, user_name) log.info('Detached %s policy from IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach %s policy from IAM user %s.', policy_name, user_name) return False return True def attach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_group_policy(policy_arn, group_name) log.info('Attached policy %s to IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM group %s.', policy_name, group_name) return False return True def detach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_group_policy(policy_arn, group_name) log.info('Detached policy %s from IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM group %s.', policy_name, group_name) return False return True def attach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_role_policy(policy_arn, role_name) log.info('Attached policy %s to IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM role %s.', policy_name, role_name) return False return True def detach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_role_policy(policy_arn, role_name) log.info('Detached policy %s from IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM role %s.', policy_name, role_name) return False return True def list_entities_for_policy(policy_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities that a policy is attached to. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 params = {} for arg in ('path_prefix', 'entity_filter'): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) while retries: try: allret = { 'policy_groups': [], 'policy_users': [], 'policy_roles': [], } for ret in __utils__['boto.paged_call'](conn.list_entities_for_policy, policy_arn=policy_arn, **params): for k, v in six.iteritems(allret): v.extend(ret.get('list_entities_for_policy_response', {}).get('list_entities_for_policy_result', {}).get(k)) return allret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('Failed to list entities for IAM policy %s: %s', policy_name, e.message) return {} return {} def list_attached_user_policies(user_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given user. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'UserName': user_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedUserPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_user_policies_response', {}).get('list_attached_user_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM user %s.', user_name) return [] def list_attached_group_policies(group_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given group. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'GroupName': group_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedGroupPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_group_policies_response', {}).get('list_attached_group_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM group %s.', group_name) return [] def list_attached_role_policies(role_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'RoleName': role_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedRolePolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_role_policies_response', {}).get('list_attached_role_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM role %s.', role_name) return [] def create_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Create SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.create_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_saml_provider(saml_metadata_document, name) log.info('Successfully created %s SAML provider.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to create SAML provider %s.', name) return False def get_saml_provider_arn(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider_arn my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_saml_providers() for saml_provider in response.list_saml_providers_response.list_saml_providers_result.saml_provider_list: if saml_provider['arn'].endswith(':saml-provider/' + name): return saml_provider['arn'] return False except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to get ARN of SAML provider %s.', name) return False def delete_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Delete SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.delete_saml_provider my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return True conn.delete_saml_provider(saml_provider_arn) log.info('Successfully deleted SAML provider %s.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete SAML provider %s.', name) return False def list_saml_providers(region=None, key=None, keyid=None, profile=None): ''' List SAML providers. CLI Example: .. code-block:: bash salt myminion boto_iam.list_saml_providers ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: providers = [] info = conn.list_saml_providers() for arn in info['list_saml_providers_response']['list_saml_providers_result']['saml_provider_list']: providers.append(arn['arn'].rsplit('/', 1)[1]) return providers except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get list of SAML providers.') return False def get_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider document. CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider arn ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: provider = conn.get_saml_provider(name) return provider['get_saml_provider_response']['get_saml_provider_result']['saml_metadata_document'] except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get SAML provider document %s.', name) return False def update_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Update SAML provider. CLI Example: .. code-block:: bash salt myminion boto_iam.update_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return False if conn.update_saml_provider(name, saml_metadata_document): return True return False except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to update SAML provider %s.', name) return False
saltstack/salt
salt/modules/boto_iam.py
add_user_to_group
python
def add_user_to_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Add user to group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.add_user_to_group myuser mygroup ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('Username : %s does not exist.', user_name) return False if user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.add_user_to_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add IAM user %s to group %s.', user_name, group_name) return False
Add user to group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.add_user_to_group myuser mygroup
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iam.py#L443-L472
[ "def get_user(user_name=None, region=None, key=None, keyid=None, profile=None):\n '''\n Get user information.\n\n .. versionadded:: 2015.8.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_iam.get_user myuser\n '''\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n try:\n info = conn.get_user(user_name)\n if not info:\n return False\n return info\n except boto.exception.BotoServerError as e:\n log.debug(e)\n log.error('Failed to get IAM user %s info.', user_name)\n return False\n", "def user_exists_in_group(user_name, group_name, region=None, key=None, keyid=None,\n profile=None):\n '''\n Check if user exists in group.\n\n .. versionadded:: 2015.8.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_iam.user_exists_in_group myuser mygroup\n '''\n # TODO this should probably use boto.iam.get_groups_for_user\n users = get_group_members(\n group_name=group_name, region=region, key=key, keyid=keyid,\n profile=profile\n )\n if users:\n for _user in users:\n if user_name == _user['user_name']:\n log.debug('IAM user %s is already in IAM group %s.', user_name, group_name)\n return True\n return False\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon IAM .. versionadded:: 2014.7.0 :configuration: This module accepts explicit iam 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 iam.keyid: GKTADJGHEIQSXMKKRBJ08H iam.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs iam.region: 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: boto ''' # keep lint from choking on _get_conn and _cache_id #pylint: disable=E0602 # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import salt libs from salt.ext import six import salt.utils.compat import salt.utils.json import salt.utils.odict as odict import salt.utils.versions from salt.exceptions import SaltInvocationError # Import third party libs # pylint: disable=unused-import from salt.ext.six.moves.urllib.parse import unquote as _unquote # pylint: disable=no-name-in-module try: import boto import boto.iam import boto3 import botocore logging.getLogger('boto').setLevel(logging.CRITICAL) logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=unused-import log = logging.getLogger(__name__) def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'iam', pack=__salt__) def instance_profile_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an instance profile exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: # Boto weirdly returns an exception here if an instance profile doesn't # exist. conn.get_instance_profile(name) return True except boto.exception.BotoServerError: return False def create_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Create an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.create_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if instance_profile_exists(name, region, key, keyid, profile): return True try: # This call returns an instance profile if successful and an exception # if not. It's annoying. conn.create_instance_profile(name) log.info('Created %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create %s instance profile.', name) return False return True def delete_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Delete an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not instance_profile_exists(name, region, key, keyid, profile): return True try: conn.delete_instance_profile(name) log.info('Deleted %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s instance profile.', name) return False return True def role_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an IAM role exists. CLI Example: .. code-block:: bash salt myminion boto_iam.role_exists myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_role(name) return True except boto.exception.BotoServerError: return False def describe_role(name, region=None, key=None, keyid=None, profile=None): ''' Get information for a role. CLI Example: .. code-block:: bash salt myminion boto_iam.describe_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_role(name) if not info: return False role = info.get_role_response.get_role_result.role role['assume_role_policy_document'] = salt.utils.json.loads(_unquote( role.assume_role_policy_document )) # If Sid wasn't defined by the user, boto will still return a Sid in # each policy. To properly check idempotently, let's remove the Sid # from the return if it's not actually set. for policy_key, policy in role['assume_role_policy_document'].items(): if policy_key == 'Statement': for val in policy: if 'Sid' in val and not val['Sid']: del val['Sid'] return role except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get %s information.', name) return False def create_user(user_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_user myuser ''' if not path: path = '/' if get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_user(user_name, path) log.info('Created IAM user : %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM user %s.', user_name) return False def get_all_access_keys(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all access keys from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_access_keys myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.get_all_access_keys(user_name, marker, max_items) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get access keys for IAM user %s.', user_name) return six.text_type(e) def create_access_key(user_name, region=None, key=None, keyid=None, profile=None): ''' Create access key id for a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.create_access_key(user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create access key.') return six.text_type(e) def delete_access_key(access_key_id, user_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete access key id from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_access_key(access_key_id, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete access key id %s.', access_key_id) return six.text_type(e) def delete_user(user_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user myuser ''' if not get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.delete_user(user_name) log.info('Deleted IAM user : %s .', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM user %s', user_name) return six.text_type(e) def get_user(user_name=None, region=None, key=None, keyid=None, profile=None): ''' Get user information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user(user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM user %s info.', user_name) return False def create_group(group_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_group group ''' if not path: path = '/' if get_group(group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_group(group_name, path) log.info('Created IAM group : %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM group %s.', group_name) return False def get_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group(group_name, max_items=1) if not info: return False return info['get_group_response']['get_group_result']['group'] except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_group_members(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: marker = None truncated = True users = [] while truncated: info = conn.get_group(group_name, marker=marker, max_items=1000) if not info: return False truncated = bool(info['get_group_response']['get_group_result']['is_truncated']) if truncated and 'marker' in info['get_group_response']['get_group_result']: marker = info['get_group_response']['get_group_result']['marker'] else: marker = None truncated = False users += info['get_group_response']['get_group_result']['users'] return users except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get members for IAM group %s.', group_name) return False def user_exists_in_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Check if user exists in group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.user_exists_in_group myuser mygroup ''' # TODO this should probably use boto.iam.get_groups_for_user users = get_group_members( group_name=group_name, region=region, key=key, keyid=keyid, profile=profile ) if users: for _user in users: if user_name == _user['user_name']: log.debug('IAM user %s is already in IAM group %s.', user_name, group_name) return True return False def remove_user_from_group(group_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Remove user from group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.remove_user_from_group mygroup myuser ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist.', user_name) return False if not user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.remove_user_from_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove IAM user %s from group %s', user_name, group_name) return False def put_group_policy(group_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_group_policy mygroup policyname policyrules ''' group = get_group(group_name, region=region, key=key, keyid=keyid, profile=profile) if not group: log.error('Group %s does not exist', group_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_group_policy(group_name, policy_name, policy_json) if created: log.info('Created policy for IAM group %s.', group_name) return True log.error('Could not create policy for IAM group %s', group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy for IAM group %s', group_name) return False def delete_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group_policy mygroup mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_group_policy( group_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_group_policy(group_name, policy_name) log.info('Successfully deleted policy %s for IAM group %s.', policy_name, group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM group %s.', policy_name, group_name) return False def get_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group_policy mygroup policyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group_policy(group_name, policy_name) log.debug('info for group policy is : %s', info) if not info: return False info = info.get_group_policy_response.get_group_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_all_groups(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM group details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_groups ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _groups = conn.get_all_groups(path_prefix=path_prefix) groups = _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) while marker: _groups = conn.get_all_groups(path_prefix=path_prefix, marker=marker) groups = groups + _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) return groups def get_all_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.get_all_instance_profiles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) marker = False profiles = [] while marker is not None: marker = marker if marker else None p = conn.list_instance_profiles(path_prefix=path_prefix, marker=marker) res = p.list_instance_profiles_response.list_instance_profiles_result profiles += res.instance_profiles marker = getattr(res, 'marker', None) return profiles def list_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' List all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.list_instance_profiles ''' p = get_all_instance_profiles(path_prefix, region, key, keyid, profile) return [i['instance_profile_name'] for i in p] def get_all_group_policies(group_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a group. CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_group_policies mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False try: response = conn.get_all_group_policies(group_name) _list = response.list_group_policies_response.list_group_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def delete_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _group = get_group( group_name, region, key, keyid, profile ) if not _group: return True try: conn.delete_group(group_name) log.info('Successfully deleted IAM group %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM group %s.', group_name) return False def create_login_profile(user_name, password, region=None, key=None, keyid=None, profile=None): ''' Creates a login profile for the specified user, give the user the ability to access AWS services and the AWS Management Console. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_login_profile user_name password ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.create_login_profile(user_name, password) log.info('Created profile for IAM user %s.', user_name) return info except boto.exception.BotoServerError as e: log.debug(e) if 'Conflict' in e: log.info('Profile already exists for IAM user %s.', user_name) return 'Conflict' log.error('Failed to update profile for IAM user %s.', user_name) return False def delete_login_profile(user_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a login profile for the specified user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_login_profile user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.delete_login_profile(user_name) log.info('Deleted login profile for IAM user %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Login profile already deleted for IAM user %s.', user_name) return True log.error('Failed to delete login profile for IAM user %s.', user_name) return False def get_all_mfa_devices(user_name, region=None, key=None, keyid=None, profile=None): ''' Get all MFA devices associated with an IAM user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_mfa_devices user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: result = conn.get_all_mfa_devices(user_name) devices = result['list_mfa_devices_response']['list_mfa_devices_result']['mfa_devices'] return devices except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Could not find IAM user %s.', user_name) return [] log.error('Failed to get all MFA devices for IAM user %s.', user_name) return False def deactivate_mfa_device(user_name, serial, region=None, key=None, keyid=None, profile=None): ''' Deactivates the specified MFA device and removes it from association with the user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.deactivate_mfa_device user_name serial_num ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.deactivate_mfa_device(user_name, serial) log.info('Deactivated MFA device %s for IAM user %s.', serial, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('MFA device %s not associated with IAM user %s.', serial, user_name) return True log.error('Failed to deactivate MFA device %s for IAM user %s.', serial, user_name) return False def delete_virtual_mfa_device(serial, region=None, key=None, keyid=None, profile=None): ''' Deletes the specified virtual MFA device. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_virtual_mfa_device serial_num ''' conn = __utils__['boto3.get_connection_func']('iam')() try: conn.delete_virtual_mfa_device(SerialNumber=serial) log.info('Deleted virtual MFA device %s.', serial) return True except botocore.exceptions.ClientError as e: log.debug(e) if 'NoSuchEntity' in six.text_type(e): log.info('Virtual MFA device %s not found.', serial) return True log.error('Failed to delete virtual MFA device %s.', serial) return False def update_account_password_policy(allow_users_to_change_password=None, hard_expiry=None, max_password_age=None, minimum_password_length=None, password_reuse_prevention=None, require_lowercase_characters=None, require_numbers=None, require_symbols=None, require_uppercase_characters=None, region=None, key=None, keyid=None, profile=None): ''' Update the password policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_account_password_policy True ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.update_account_password_policy(allow_users_to_change_password, hard_expiry, max_password_age, minimum_password_length, password_reuse_prevention, require_lowercase_characters, require_numbers, require_symbols, require_uppercase_characters) log.info('The password policy has been updated.') return True except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy' log.error(msg) return False def get_account_policy(region=None, key=None, keyid=None, profile=None): ''' Get account policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_account_password_policy() return info.get_account_password_policy_response.get_account_password_policy_result.password_policy except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy.' log.error(msg) return False def create_role(name, policy_document=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Create an instance role. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if role_exists(name, region, key, keyid, profile): return True if not policy_document: policy_document = None try: conn.create_role(name, assume_role_policy_document=policy_document, path=path) log.info('Created IAM role %s.', name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to create IAM role %s.', name) return False def delete_role(name, region=None, key=None, keyid=None, profile=None): ''' Delete an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(name, region, key, keyid, profile): return True try: conn.delete_role(name) log.info('Deleted %s IAM role.', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s IAM role.', name) return False def profile_associated(role_name, profile_name, region, key, keyid, profile): ''' Check to see if an instance profile is associated with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.profile_associated myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # The IAM module of boto doesn't return objects. Instead you need to grab # values through its properties. Sigh. try: profiles = conn.list_instance_profiles_for_role(role_name) except boto.exception.BotoServerError as e: log.debug(e) return False profiles = profiles.list_instance_profiles_for_role_response profiles = profiles.list_instance_profiles_for_role_result profiles = profiles.instance_profiles for profile in profiles: if profile.instance_profile_name == profile_name: return True return False def associate_profile_to_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Associate an instance profile with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.associate_profile_to_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if associated: return True else: try: conn.add_role_to_instance_profile(profile_name, role_name) log.info('Added %s instance profile to IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add %s instance profile to IAM role %s', profile_name, role_name) return False def disassociate_profile_from_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Disassociate an instance profile from an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.disassociate_profile_from_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if not associated: return True else: try: conn.remove_role_from_instance_profile(profile_name, role_name) log.info('Removed %s instance profile from IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove %s instance profile from IAM role %s.', profile_name, role_name) return False def list_role_policies(role_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_role_policies myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_role_policies(role_name) _list = response.list_role_policies_response.list_role_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def get_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.get_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: _policy = conn.get_role_policy(role_name, policy_name) # I _hate_ you for not giving me an object boto. _policy = _policy.get_role_policy_response.policy_document # Policy is url encoded _policy = _unquote(_policy) _policy = salt.utils.json.loads(_policy, object_pairs_hook=odict.OrderedDict) return _policy except boto.exception.BotoServerError: return {} def create_role_policy(role_name, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Create or modify a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role_policy myirole mypolicy '{"MyPolicy": "Statement": [{"Action": ["sqs:*"], "Effect": "Allow", "Resource": ["arn:aws:sqs:*:*:*"], "Sid": "MyPolicySqs1"}]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) mode = 'create' if _policy: if _policy == policy: return True mode = 'modify' if isinstance(policy, six.string_types): policy = salt.utils.json.loads(policy, object_pairs_hook=odict.OrderedDict) try: _policy = salt.utils.json.dumps(policy) conn.put_role_policy(role_name, policy_name, _policy) if mode == 'create': msg = 'Successfully added policy %s to IAM role %s.' else: msg = 'Successfully modified policy %s for IAM role %s.' log.info(msg, policy_name, role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to %s policy %s for IAM role %s.', mode, policy_name, role_name) return False def delete_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) if not _policy: return True try: conn.delete_role_policy(role_name, policy_name) log.info('Successfully deleted policy %s for IAM role %s.', policy_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM role %s.', policy_name, role_name) return False def update_assume_role_policy(role_name, policy_document, region=None, key=None, keyid=None, profile=None): ''' Update an assume role policy for a role. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_assume_role_policy myrole '{"Statement":"..."}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(policy_document, six.string_types): policy_document = salt.utils.json.loads(policy_document, object_pairs_hook=odict.OrderedDict) try: _policy_document = salt.utils.json.dumps(policy_document) conn.update_assume_role_policy(role_name, _policy_document) log.info('Successfully updated assume role policy for IAM role %s.', role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to update assume role policy for IAM role %s.', role_name) return False def build_policy(region=None, key=None, keyid=None, profile=None): ''' Build a default assume role policy. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.build_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if hasattr(conn, 'build_policy'): policy = salt.utils.json.loads(conn.build_policy()) elif hasattr(conn, '_build_policy'): policy = salt.utils.json.loads(conn._build_policy()) else: return {} # The format we get from build_policy isn't going to be what we get back # from AWS for the exact same policy. AWS converts single item list values # into strings, so let's do the same here. for key, policy_val in policy.items(): for statement in policy_val: if (isinstance(statement['Action'], list) and len(statement['Action']) == 1): statement['Action'] = statement['Action'][0] if (isinstance(statement['Principal']['Service'], list) and len(statement['Principal']['Service']) == 1): statement['Principal']['Service'] = statement['Principal']['Service'][0] # build_policy doesn't add a version field, which AWS is going to set to a # default value, when we get it back, so let's set it. policy['Version'] = '2008-10-17' return policy def get_account_id(region=None, key=None, keyid=None, profile=None): ''' Get a the AWS account id associated with the used credentials. CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_id ''' cache_key = 'boto_iam.account_id' if cache_key not in __context__: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_user() # The get_user call returns an user ARN: # arn:aws:iam::027050522557:user/salt-test arn = ret['get_user_response']['get_user_result']['user']['arn'] account_id = arn.split(':')[4] except boto.exception.BotoServerError: # If call failed, then let's try to get the ARN from the metadata timeout = boto.config.getfloat( 'Boto', 'metadata_service_timeout', 1.0 ) attempts = boto.config.getint( 'Boto', 'metadata_service_num_attempts', 1 ) identity = boto.utils.get_instance_identity( timeout=timeout, num_retries=attempts ) try: account_id = identity['document']['accountId'] except KeyError: log.error('Failed to get account id from instance_identity in' ' boto_iam.get_account_id.') __context__[cache_key] = account_id return __context__[cache_key] def get_all_roles(path_prefix=None, region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM role details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_roles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _roles = conn.list_roles(path_prefix=path_prefix) roles = _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) while marker: _roles = conn.list_roles(path_prefix=path_prefix, marker=marker) roles = roles + _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) return roles def get_all_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM user details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_users ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _users = conn.get_all_users(path_prefix=path_prefix) users = _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) while marker: _users = conn.get_all_users(path_prefix=path_prefix, marker=marker) users = users + _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) return users def get_all_user_policies(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all user policies. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_user_policies myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_all_user_policies(user_name, marker, max_items) if not info: return False _list = info.list_user_policies_response.list_user_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policies for user %s.', user_name) return False def get_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user_policy myuser mypolicyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user_policy(user_name, policy_name) log.debug('Info for IAM user %s policy %s: %s.', user_name, policy_name, info) if not info: return False info = info.get_user_policy_response.get_user_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policy %s for IAM user %s.', policy_name, user_name) return False def put_user_policy(user_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_user_policy myuser policyname policyrules ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_user_policy(user_name, policy_name, policy_json) if created: log.info('Created policy %s for IAM user %s.', policy_name, user_name) return True log.error('Could not create policy %s for IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy %s for IAM user %s.', policy_name, user_name) return False def delete_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user_policy myuser mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_user_policy( user_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_user_policy(user_name, policy_name) log.info('Successfully deleted policy %s for IAM user %s.', policy_name, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM user %s.', policy_name, user_name) return False def upload_server_cert(cert_name, cert_body, private_key, cert_chain=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Upload a certificate to Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.upload_server_cert mycert_name crt priv_key :param cert_name: The name for the server certificate. Do not include the path in this value. :param cert_body: The contents of the public key certificate in PEM-encoded format. :param private_key: The contents of the private key in PEM-encoded format. :param cert_chain: The contents of the certificate chain. This is typically a concatenation of the PEM-encoded public key certificates of the chain. :param path: The path for the server certificate. :param region: The name of the region to connect to. :param key: The key to be used in order to connect :param keyid: The keyid to be used in order to connect :param profile: The profile that contains a dict of region, key, keyid :return: True / False ''' exists = get_server_certificate(cert_name, region, key, keyid, profile) if exists: return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.upload_server_cert(cert_name, cert_body, private_key, cert_chain) log.info('Created certificate %s.', cert_name) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to failed to create certificate %s.', cert_name) return False def list_server_certificates(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Lists the server certificates stored in IAM that have the specified path prefix. .. versionadded:: ??? :param path_prefix: The path prefix for filtering the results. For example: /company/servercerts would get all server certificates for which the path starts with /company/servercerts . This parameter is optional. If it is not included, it defaults to a slash (/), listing all server certificates. This parameter allows (per its regex pattern) a string of characters consisting of either a forward slash (/) by itself or a string that must begin and end with forward slashes. In addition, it can contain any ASCII character from the ! (u0021) through the DEL character (u007F), including most punctuation characters, digits, and upper and lowercased letters. CLI Example: .. code-block:: bash salt myminion boto_iam.list_server_certificates path_prefix=/somepath/ ''' retries = 10 sleep = 6 conn = __utils__['boto3.get_connection']('iam', region=region, key=key, keyid=keyid, profile=profile) Items = [] while retries: try: log.debug('Garnering list of IAM Server Certificates') IsTruncated = True while IsTruncated: kwargs = {'PathPrefix': path_prefix} ret = conn.list_server_certificates(**kwargs) Items += ret.get('ServerCertificateMetadataList', []) IsTruncated = ret.get('IsTruncated') kwargs.update({'Marker': ret.get('Marker')}) return Items except botocore.exceptions.ParamValidationError as err: raise SaltInvocationError(str(err)) except botocore.exceptions.ClientError as err: if retries and jmespath.search('Error.Code', err.response) == 'Throttling': retries -= 1 log.debug('Throttled by AWS API, retrying in %s seconds...', sleep) time.sleep(sleep) continue log.error('Failed to list IAM Server Certificates: %s', err.message) return None def get_server_certificate(cert_name, region=None, key=None, keyid=None, profile=None): ''' Returns certificate information from Amazon .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_server_certificate mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_server_certificate(cert_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get certificate %s information.', cert_name) return False def delete_server_cert(cert_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a certificate from Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_server_cert mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_server_cert(cert_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete certificate %s.', cert_name) return False def export_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM user details. Produces results that can be used to create an sls file. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.export_users --out=txt | sed "s/local: //" > iam_users.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() users = get_all_users(path_prefix, region, key, keyid, profile) for user in users: name = user.user_name _policies = conn.get_all_user_policies(name, max_items=100) _policies = _policies.list_user_policies_response.list_user_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_user_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_user_policy_response.get_user_policy_result.policy_document )) policies[policy_name] = _policy user_sls = [] user_sls.append({"name": name}) user_sls.append({"policies": policies}) user_sls.append({"path": user.path}) results["manage user " + name] = {"boto_iam.user_present": user_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def export_roles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM role details. Produces results that can be used to create an sls file. CLI Example: salt-call boto_iam.export_roles --out=txt | sed "s/local: //" > iam_roles.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() roles = get_all_roles(path_prefix, region, key, keyid, profile) for role in roles: name = role.role_name _policies = conn.list_role_policies(name, max_items=100) _policies = _policies.list_role_policies_response.list_role_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_role_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_role_policy_response.get_role_policy_result.policy_document )) policies[policy_name] = _policy role_sls = [] role_sls.append({"name": name}) role_sls.append({"policies": policies}) role_sls.append({'policy_document': salt.utils.json.loads(_unquote(role.assume_role_policy_document))}) role_sls.append({"path": role.path}) results["manage role " + name] = {"boto_iam_role.present": role_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def _get_policy_arn(name, region=None, key=None, keyid=None, profile=None): if name.startswith('arn:aws:iam:'): return name account_id = get_account_id( region=region, key=key, keyid=keyid, profile=profile ) return 'arn:aws:iam::{0}:policy/{1}'.format(account_id, name) def policy_exists(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return True except boto.exception.BotoServerError: return False def get_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return ret.get('get_policy_response', {}).get('get_policy_result', {}) except boto.exception.BotoServerError: return None def create_policy(policy_name, policy_document, path=None, description=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in 'path', 'description': if locals()[arg] is not None: params[arg] = locals()[arg] if policy_exists(policy_name, region, key, keyid, profile): return True try: conn.create_policy(policy_name, policy_document, **params) log.info('Created IAM policy %s.', policy_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s.', policy_name) return False return True def delete_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_exists(policy_arn, region, key, keyid, profile): return True try: conn.delete_policy(policy_arn) log.info('Deleted %s policy.', policy_name) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete %s policy: %s.', policy_name, aws.get('message')) return False return True def list_policies(region=None, key=None, keyid=None, profile=None): ''' List policies. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policies ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: policies = [] for ret in __utils__['boto.paged_call'](conn.list_policies): policies.append(ret.get('list_policies_response', {}).get('list_policies_result', {}).get('policies')) return policies except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to list policy versions.' log.error(msg) return [] def policy_version_exists(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.get_policy_version(policy_arn, version_id) return True except boto.exception.BotoServerError: return False def get_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy_version(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile), version_id) retval = ret.get('get_policy_version_response', {}).get('get_policy_version_result', {}).get('policy_version', {}) retval['document'] = _unquote(retval.get('document')) return {'policy_version': retval} except boto.exception.BotoServerError: return None def create_policy_version(policy_name, policy_document, set_as_default=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy version. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy_version mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in ('set_as_default',): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.create_policy_version(policy_arn, policy_document, **params) vid = ret.get('create_policy_version_response', {}).get('create_policy_version_result', {}).get('policy_version', {}).get('version_id') log.info('Created IAM policy %s version %s.', policy_name, vid) return {'created': True, 'version_id': vid} except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s version %s.', policy_name, vid) return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Delete a policy version. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_version_exists(policy_arn, version_id, region, key, keyid, profile): return True try: conn.delete_policy_version(policy_arn, version_id) log.info('Deleted IAM policy %s version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete IAM policy %s version %s: %s', policy_name, version_id, aws.get('message')) return False return True def list_policy_versions(policy_name, region=None, key=None, keyid=None, profile=None): ''' List versions of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policy_versions mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.list_policy_versions(policy_arn) return ret.get('list_policy_versions_response', {}).get('list_policy_versions_result', {}).get('versions') except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list versions for IAM policy %s.', policy_name) return [] def set_default_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Set the default version of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.set_default_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.set_default_policy_version(policy_arn, version_id) log.info('Set %s policy to version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to set %s policy to version %s: %s', policy_name, version_id, aws.get('message')) return False return True def attach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_user_policy(policy_arn, user_name) log.info('Attached policy %s to IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach %s policy to IAM user %s.', policy_name, user_name) return False return True def detach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_user_policy(policy_arn, user_name) log.info('Detached %s policy from IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach %s policy from IAM user %s.', policy_name, user_name) return False return True def attach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_group_policy(policy_arn, group_name) log.info('Attached policy %s to IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM group %s.', policy_name, group_name) return False return True def detach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_group_policy(policy_arn, group_name) log.info('Detached policy %s from IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM group %s.', policy_name, group_name) return False return True def attach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_role_policy(policy_arn, role_name) log.info('Attached policy %s to IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM role %s.', policy_name, role_name) return False return True def detach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_role_policy(policy_arn, role_name) log.info('Detached policy %s from IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM role %s.', policy_name, role_name) return False return True def list_entities_for_policy(policy_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities that a policy is attached to. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 params = {} for arg in ('path_prefix', 'entity_filter'): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) while retries: try: allret = { 'policy_groups': [], 'policy_users': [], 'policy_roles': [], } for ret in __utils__['boto.paged_call'](conn.list_entities_for_policy, policy_arn=policy_arn, **params): for k, v in six.iteritems(allret): v.extend(ret.get('list_entities_for_policy_response', {}).get('list_entities_for_policy_result', {}).get(k)) return allret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('Failed to list entities for IAM policy %s: %s', policy_name, e.message) return {} return {} def list_attached_user_policies(user_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given user. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'UserName': user_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedUserPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_user_policies_response', {}).get('list_attached_user_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM user %s.', user_name) return [] def list_attached_group_policies(group_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given group. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'GroupName': group_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedGroupPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_group_policies_response', {}).get('list_attached_group_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM group %s.', group_name) return [] def list_attached_role_policies(role_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'RoleName': role_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedRolePolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_role_policies_response', {}).get('list_attached_role_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM role %s.', role_name) return [] def create_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Create SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.create_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_saml_provider(saml_metadata_document, name) log.info('Successfully created %s SAML provider.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to create SAML provider %s.', name) return False def get_saml_provider_arn(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider_arn my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_saml_providers() for saml_provider in response.list_saml_providers_response.list_saml_providers_result.saml_provider_list: if saml_provider['arn'].endswith(':saml-provider/' + name): return saml_provider['arn'] return False except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to get ARN of SAML provider %s.', name) return False def delete_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Delete SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.delete_saml_provider my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return True conn.delete_saml_provider(saml_provider_arn) log.info('Successfully deleted SAML provider %s.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete SAML provider %s.', name) return False def list_saml_providers(region=None, key=None, keyid=None, profile=None): ''' List SAML providers. CLI Example: .. code-block:: bash salt myminion boto_iam.list_saml_providers ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: providers = [] info = conn.list_saml_providers() for arn in info['list_saml_providers_response']['list_saml_providers_result']['saml_provider_list']: providers.append(arn['arn'].rsplit('/', 1)[1]) return providers except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get list of SAML providers.') return False def get_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider document. CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider arn ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: provider = conn.get_saml_provider(name) return provider['get_saml_provider_response']['get_saml_provider_result']['saml_metadata_document'] except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get SAML provider document %s.', name) return False def update_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Update SAML provider. CLI Example: .. code-block:: bash salt myminion boto_iam.update_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return False if conn.update_saml_provider(name, saml_metadata_document): return True return False except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to update SAML provider %s.', name) return False
saltstack/salt
salt/modules/boto_iam.py
user_exists_in_group
python
def user_exists_in_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Check if user exists in group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.user_exists_in_group myuser mygroup ''' # TODO this should probably use boto.iam.get_groups_for_user users = get_group_members( group_name=group_name, region=region, key=key, keyid=keyid, profile=profile ) if users: for _user in users: if user_name == _user['user_name']: log.debug('IAM user %s is already in IAM group %s.', user_name, group_name) return True return False
Check if user exists in group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.user_exists_in_group myuser mygroup
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iam.py#L475-L498
[ "def get_group_members(group_name, region=None, key=None, keyid=None, profile=None):\n '''\n Get group information.\n\n .. versionadded:: 2016.3.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_iam.get_group mygroup\n '''\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n try:\n marker = None\n truncated = True\n users = []\n while truncated:\n info = conn.get_group(group_name, marker=marker, max_items=1000)\n if not info:\n return False\n truncated = bool(info['get_group_response']['get_group_result']['is_truncated'])\n if truncated and 'marker' in info['get_group_response']['get_group_result']:\n marker = info['get_group_response']['get_group_result']['marker']\n else:\n marker = None\n truncated = False\n users += info['get_group_response']['get_group_result']['users']\n return users\n except boto.exception.BotoServerError as e:\n log.debug(e)\n log.error('Failed to get members for IAM group %s.', group_name)\n return False\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon IAM .. versionadded:: 2014.7.0 :configuration: This module accepts explicit iam 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 iam.keyid: GKTADJGHEIQSXMKKRBJ08H iam.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs iam.region: 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: boto ''' # keep lint from choking on _get_conn and _cache_id #pylint: disable=E0602 # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import salt libs from salt.ext import six import salt.utils.compat import salt.utils.json import salt.utils.odict as odict import salt.utils.versions from salt.exceptions import SaltInvocationError # Import third party libs # pylint: disable=unused-import from salt.ext.six.moves.urllib.parse import unquote as _unquote # pylint: disable=no-name-in-module try: import boto import boto.iam import boto3 import botocore logging.getLogger('boto').setLevel(logging.CRITICAL) logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=unused-import log = logging.getLogger(__name__) def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'iam', pack=__salt__) def instance_profile_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an instance profile exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: # Boto weirdly returns an exception here if an instance profile doesn't # exist. conn.get_instance_profile(name) return True except boto.exception.BotoServerError: return False def create_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Create an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.create_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if instance_profile_exists(name, region, key, keyid, profile): return True try: # This call returns an instance profile if successful and an exception # if not. It's annoying. conn.create_instance_profile(name) log.info('Created %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create %s instance profile.', name) return False return True def delete_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Delete an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not instance_profile_exists(name, region, key, keyid, profile): return True try: conn.delete_instance_profile(name) log.info('Deleted %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s instance profile.', name) return False return True def role_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an IAM role exists. CLI Example: .. code-block:: bash salt myminion boto_iam.role_exists myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_role(name) return True except boto.exception.BotoServerError: return False def describe_role(name, region=None, key=None, keyid=None, profile=None): ''' Get information for a role. CLI Example: .. code-block:: bash salt myminion boto_iam.describe_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_role(name) if not info: return False role = info.get_role_response.get_role_result.role role['assume_role_policy_document'] = salt.utils.json.loads(_unquote( role.assume_role_policy_document )) # If Sid wasn't defined by the user, boto will still return a Sid in # each policy. To properly check idempotently, let's remove the Sid # from the return if it's not actually set. for policy_key, policy in role['assume_role_policy_document'].items(): if policy_key == 'Statement': for val in policy: if 'Sid' in val and not val['Sid']: del val['Sid'] return role except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get %s information.', name) return False def create_user(user_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_user myuser ''' if not path: path = '/' if get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_user(user_name, path) log.info('Created IAM user : %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM user %s.', user_name) return False def get_all_access_keys(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all access keys from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_access_keys myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.get_all_access_keys(user_name, marker, max_items) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get access keys for IAM user %s.', user_name) return six.text_type(e) def create_access_key(user_name, region=None, key=None, keyid=None, profile=None): ''' Create access key id for a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.create_access_key(user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create access key.') return six.text_type(e) def delete_access_key(access_key_id, user_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete access key id from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_access_key(access_key_id, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete access key id %s.', access_key_id) return six.text_type(e) def delete_user(user_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user myuser ''' if not get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.delete_user(user_name) log.info('Deleted IAM user : %s .', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM user %s', user_name) return six.text_type(e) def get_user(user_name=None, region=None, key=None, keyid=None, profile=None): ''' Get user information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user(user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM user %s info.', user_name) return False def create_group(group_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_group group ''' if not path: path = '/' if get_group(group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_group(group_name, path) log.info('Created IAM group : %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM group %s.', group_name) return False def get_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group(group_name, max_items=1) if not info: return False return info['get_group_response']['get_group_result']['group'] except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_group_members(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: marker = None truncated = True users = [] while truncated: info = conn.get_group(group_name, marker=marker, max_items=1000) if not info: return False truncated = bool(info['get_group_response']['get_group_result']['is_truncated']) if truncated and 'marker' in info['get_group_response']['get_group_result']: marker = info['get_group_response']['get_group_result']['marker'] else: marker = None truncated = False users += info['get_group_response']['get_group_result']['users'] return users except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get members for IAM group %s.', group_name) return False def add_user_to_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Add user to group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.add_user_to_group myuser mygroup ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('Username : %s does not exist.', user_name) return False if user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.add_user_to_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add IAM user %s to group %s.', user_name, group_name) return False def remove_user_from_group(group_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Remove user from group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.remove_user_from_group mygroup myuser ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist.', user_name) return False if not user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.remove_user_from_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove IAM user %s from group %s', user_name, group_name) return False def put_group_policy(group_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_group_policy mygroup policyname policyrules ''' group = get_group(group_name, region=region, key=key, keyid=keyid, profile=profile) if not group: log.error('Group %s does not exist', group_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_group_policy(group_name, policy_name, policy_json) if created: log.info('Created policy for IAM group %s.', group_name) return True log.error('Could not create policy for IAM group %s', group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy for IAM group %s', group_name) return False def delete_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group_policy mygroup mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_group_policy( group_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_group_policy(group_name, policy_name) log.info('Successfully deleted policy %s for IAM group %s.', policy_name, group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM group %s.', policy_name, group_name) return False def get_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group_policy mygroup policyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group_policy(group_name, policy_name) log.debug('info for group policy is : %s', info) if not info: return False info = info.get_group_policy_response.get_group_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_all_groups(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM group details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_groups ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _groups = conn.get_all_groups(path_prefix=path_prefix) groups = _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) while marker: _groups = conn.get_all_groups(path_prefix=path_prefix, marker=marker) groups = groups + _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) return groups def get_all_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.get_all_instance_profiles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) marker = False profiles = [] while marker is not None: marker = marker if marker else None p = conn.list_instance_profiles(path_prefix=path_prefix, marker=marker) res = p.list_instance_profiles_response.list_instance_profiles_result profiles += res.instance_profiles marker = getattr(res, 'marker', None) return profiles def list_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' List all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.list_instance_profiles ''' p = get_all_instance_profiles(path_prefix, region, key, keyid, profile) return [i['instance_profile_name'] for i in p] def get_all_group_policies(group_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a group. CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_group_policies mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False try: response = conn.get_all_group_policies(group_name) _list = response.list_group_policies_response.list_group_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def delete_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _group = get_group( group_name, region, key, keyid, profile ) if not _group: return True try: conn.delete_group(group_name) log.info('Successfully deleted IAM group %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM group %s.', group_name) return False def create_login_profile(user_name, password, region=None, key=None, keyid=None, profile=None): ''' Creates a login profile for the specified user, give the user the ability to access AWS services and the AWS Management Console. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_login_profile user_name password ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.create_login_profile(user_name, password) log.info('Created profile for IAM user %s.', user_name) return info except boto.exception.BotoServerError as e: log.debug(e) if 'Conflict' in e: log.info('Profile already exists for IAM user %s.', user_name) return 'Conflict' log.error('Failed to update profile for IAM user %s.', user_name) return False def delete_login_profile(user_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a login profile for the specified user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_login_profile user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.delete_login_profile(user_name) log.info('Deleted login profile for IAM user %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Login profile already deleted for IAM user %s.', user_name) return True log.error('Failed to delete login profile for IAM user %s.', user_name) return False def get_all_mfa_devices(user_name, region=None, key=None, keyid=None, profile=None): ''' Get all MFA devices associated with an IAM user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_mfa_devices user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: result = conn.get_all_mfa_devices(user_name) devices = result['list_mfa_devices_response']['list_mfa_devices_result']['mfa_devices'] return devices except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Could not find IAM user %s.', user_name) return [] log.error('Failed to get all MFA devices for IAM user %s.', user_name) return False def deactivate_mfa_device(user_name, serial, region=None, key=None, keyid=None, profile=None): ''' Deactivates the specified MFA device and removes it from association with the user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.deactivate_mfa_device user_name serial_num ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.deactivate_mfa_device(user_name, serial) log.info('Deactivated MFA device %s for IAM user %s.', serial, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('MFA device %s not associated with IAM user %s.', serial, user_name) return True log.error('Failed to deactivate MFA device %s for IAM user %s.', serial, user_name) return False def delete_virtual_mfa_device(serial, region=None, key=None, keyid=None, profile=None): ''' Deletes the specified virtual MFA device. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_virtual_mfa_device serial_num ''' conn = __utils__['boto3.get_connection_func']('iam')() try: conn.delete_virtual_mfa_device(SerialNumber=serial) log.info('Deleted virtual MFA device %s.', serial) return True except botocore.exceptions.ClientError as e: log.debug(e) if 'NoSuchEntity' in six.text_type(e): log.info('Virtual MFA device %s not found.', serial) return True log.error('Failed to delete virtual MFA device %s.', serial) return False def update_account_password_policy(allow_users_to_change_password=None, hard_expiry=None, max_password_age=None, minimum_password_length=None, password_reuse_prevention=None, require_lowercase_characters=None, require_numbers=None, require_symbols=None, require_uppercase_characters=None, region=None, key=None, keyid=None, profile=None): ''' Update the password policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_account_password_policy True ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.update_account_password_policy(allow_users_to_change_password, hard_expiry, max_password_age, minimum_password_length, password_reuse_prevention, require_lowercase_characters, require_numbers, require_symbols, require_uppercase_characters) log.info('The password policy has been updated.') return True except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy' log.error(msg) return False def get_account_policy(region=None, key=None, keyid=None, profile=None): ''' Get account policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_account_password_policy() return info.get_account_password_policy_response.get_account_password_policy_result.password_policy except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy.' log.error(msg) return False def create_role(name, policy_document=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Create an instance role. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if role_exists(name, region, key, keyid, profile): return True if not policy_document: policy_document = None try: conn.create_role(name, assume_role_policy_document=policy_document, path=path) log.info('Created IAM role %s.', name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to create IAM role %s.', name) return False def delete_role(name, region=None, key=None, keyid=None, profile=None): ''' Delete an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(name, region, key, keyid, profile): return True try: conn.delete_role(name) log.info('Deleted %s IAM role.', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s IAM role.', name) return False def profile_associated(role_name, profile_name, region, key, keyid, profile): ''' Check to see if an instance profile is associated with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.profile_associated myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # The IAM module of boto doesn't return objects. Instead you need to grab # values through its properties. Sigh. try: profiles = conn.list_instance_profiles_for_role(role_name) except boto.exception.BotoServerError as e: log.debug(e) return False profiles = profiles.list_instance_profiles_for_role_response profiles = profiles.list_instance_profiles_for_role_result profiles = profiles.instance_profiles for profile in profiles: if profile.instance_profile_name == profile_name: return True return False def associate_profile_to_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Associate an instance profile with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.associate_profile_to_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if associated: return True else: try: conn.add_role_to_instance_profile(profile_name, role_name) log.info('Added %s instance profile to IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add %s instance profile to IAM role %s', profile_name, role_name) return False def disassociate_profile_from_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Disassociate an instance profile from an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.disassociate_profile_from_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if not associated: return True else: try: conn.remove_role_from_instance_profile(profile_name, role_name) log.info('Removed %s instance profile from IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove %s instance profile from IAM role %s.', profile_name, role_name) return False def list_role_policies(role_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_role_policies myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_role_policies(role_name) _list = response.list_role_policies_response.list_role_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def get_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.get_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: _policy = conn.get_role_policy(role_name, policy_name) # I _hate_ you for not giving me an object boto. _policy = _policy.get_role_policy_response.policy_document # Policy is url encoded _policy = _unquote(_policy) _policy = salt.utils.json.loads(_policy, object_pairs_hook=odict.OrderedDict) return _policy except boto.exception.BotoServerError: return {} def create_role_policy(role_name, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Create or modify a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role_policy myirole mypolicy '{"MyPolicy": "Statement": [{"Action": ["sqs:*"], "Effect": "Allow", "Resource": ["arn:aws:sqs:*:*:*"], "Sid": "MyPolicySqs1"}]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) mode = 'create' if _policy: if _policy == policy: return True mode = 'modify' if isinstance(policy, six.string_types): policy = salt.utils.json.loads(policy, object_pairs_hook=odict.OrderedDict) try: _policy = salt.utils.json.dumps(policy) conn.put_role_policy(role_name, policy_name, _policy) if mode == 'create': msg = 'Successfully added policy %s to IAM role %s.' else: msg = 'Successfully modified policy %s for IAM role %s.' log.info(msg, policy_name, role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to %s policy %s for IAM role %s.', mode, policy_name, role_name) return False def delete_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) if not _policy: return True try: conn.delete_role_policy(role_name, policy_name) log.info('Successfully deleted policy %s for IAM role %s.', policy_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM role %s.', policy_name, role_name) return False def update_assume_role_policy(role_name, policy_document, region=None, key=None, keyid=None, profile=None): ''' Update an assume role policy for a role. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_assume_role_policy myrole '{"Statement":"..."}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(policy_document, six.string_types): policy_document = salt.utils.json.loads(policy_document, object_pairs_hook=odict.OrderedDict) try: _policy_document = salt.utils.json.dumps(policy_document) conn.update_assume_role_policy(role_name, _policy_document) log.info('Successfully updated assume role policy for IAM role %s.', role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to update assume role policy for IAM role %s.', role_name) return False def build_policy(region=None, key=None, keyid=None, profile=None): ''' Build a default assume role policy. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.build_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if hasattr(conn, 'build_policy'): policy = salt.utils.json.loads(conn.build_policy()) elif hasattr(conn, '_build_policy'): policy = salt.utils.json.loads(conn._build_policy()) else: return {} # The format we get from build_policy isn't going to be what we get back # from AWS for the exact same policy. AWS converts single item list values # into strings, so let's do the same here. for key, policy_val in policy.items(): for statement in policy_val: if (isinstance(statement['Action'], list) and len(statement['Action']) == 1): statement['Action'] = statement['Action'][0] if (isinstance(statement['Principal']['Service'], list) and len(statement['Principal']['Service']) == 1): statement['Principal']['Service'] = statement['Principal']['Service'][0] # build_policy doesn't add a version field, which AWS is going to set to a # default value, when we get it back, so let's set it. policy['Version'] = '2008-10-17' return policy def get_account_id(region=None, key=None, keyid=None, profile=None): ''' Get a the AWS account id associated with the used credentials. CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_id ''' cache_key = 'boto_iam.account_id' if cache_key not in __context__: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_user() # The get_user call returns an user ARN: # arn:aws:iam::027050522557:user/salt-test arn = ret['get_user_response']['get_user_result']['user']['arn'] account_id = arn.split(':')[4] except boto.exception.BotoServerError: # If call failed, then let's try to get the ARN from the metadata timeout = boto.config.getfloat( 'Boto', 'metadata_service_timeout', 1.0 ) attempts = boto.config.getint( 'Boto', 'metadata_service_num_attempts', 1 ) identity = boto.utils.get_instance_identity( timeout=timeout, num_retries=attempts ) try: account_id = identity['document']['accountId'] except KeyError: log.error('Failed to get account id from instance_identity in' ' boto_iam.get_account_id.') __context__[cache_key] = account_id return __context__[cache_key] def get_all_roles(path_prefix=None, region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM role details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_roles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _roles = conn.list_roles(path_prefix=path_prefix) roles = _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) while marker: _roles = conn.list_roles(path_prefix=path_prefix, marker=marker) roles = roles + _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) return roles def get_all_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM user details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_users ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _users = conn.get_all_users(path_prefix=path_prefix) users = _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) while marker: _users = conn.get_all_users(path_prefix=path_prefix, marker=marker) users = users + _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) return users def get_all_user_policies(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all user policies. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_user_policies myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_all_user_policies(user_name, marker, max_items) if not info: return False _list = info.list_user_policies_response.list_user_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policies for user %s.', user_name) return False def get_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user_policy myuser mypolicyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user_policy(user_name, policy_name) log.debug('Info for IAM user %s policy %s: %s.', user_name, policy_name, info) if not info: return False info = info.get_user_policy_response.get_user_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policy %s for IAM user %s.', policy_name, user_name) return False def put_user_policy(user_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_user_policy myuser policyname policyrules ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_user_policy(user_name, policy_name, policy_json) if created: log.info('Created policy %s for IAM user %s.', policy_name, user_name) return True log.error('Could not create policy %s for IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy %s for IAM user %s.', policy_name, user_name) return False def delete_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user_policy myuser mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_user_policy( user_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_user_policy(user_name, policy_name) log.info('Successfully deleted policy %s for IAM user %s.', policy_name, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM user %s.', policy_name, user_name) return False def upload_server_cert(cert_name, cert_body, private_key, cert_chain=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Upload a certificate to Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.upload_server_cert mycert_name crt priv_key :param cert_name: The name for the server certificate. Do not include the path in this value. :param cert_body: The contents of the public key certificate in PEM-encoded format. :param private_key: The contents of the private key in PEM-encoded format. :param cert_chain: The contents of the certificate chain. This is typically a concatenation of the PEM-encoded public key certificates of the chain. :param path: The path for the server certificate. :param region: The name of the region to connect to. :param key: The key to be used in order to connect :param keyid: The keyid to be used in order to connect :param profile: The profile that contains a dict of region, key, keyid :return: True / False ''' exists = get_server_certificate(cert_name, region, key, keyid, profile) if exists: return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.upload_server_cert(cert_name, cert_body, private_key, cert_chain) log.info('Created certificate %s.', cert_name) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to failed to create certificate %s.', cert_name) return False def list_server_certificates(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Lists the server certificates stored in IAM that have the specified path prefix. .. versionadded:: ??? :param path_prefix: The path prefix for filtering the results. For example: /company/servercerts would get all server certificates for which the path starts with /company/servercerts . This parameter is optional. If it is not included, it defaults to a slash (/), listing all server certificates. This parameter allows (per its regex pattern) a string of characters consisting of either a forward slash (/) by itself or a string that must begin and end with forward slashes. In addition, it can contain any ASCII character from the ! (u0021) through the DEL character (u007F), including most punctuation characters, digits, and upper and lowercased letters. CLI Example: .. code-block:: bash salt myminion boto_iam.list_server_certificates path_prefix=/somepath/ ''' retries = 10 sleep = 6 conn = __utils__['boto3.get_connection']('iam', region=region, key=key, keyid=keyid, profile=profile) Items = [] while retries: try: log.debug('Garnering list of IAM Server Certificates') IsTruncated = True while IsTruncated: kwargs = {'PathPrefix': path_prefix} ret = conn.list_server_certificates(**kwargs) Items += ret.get('ServerCertificateMetadataList', []) IsTruncated = ret.get('IsTruncated') kwargs.update({'Marker': ret.get('Marker')}) return Items except botocore.exceptions.ParamValidationError as err: raise SaltInvocationError(str(err)) except botocore.exceptions.ClientError as err: if retries and jmespath.search('Error.Code', err.response) == 'Throttling': retries -= 1 log.debug('Throttled by AWS API, retrying in %s seconds...', sleep) time.sleep(sleep) continue log.error('Failed to list IAM Server Certificates: %s', err.message) return None def get_server_certificate(cert_name, region=None, key=None, keyid=None, profile=None): ''' Returns certificate information from Amazon .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_server_certificate mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_server_certificate(cert_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get certificate %s information.', cert_name) return False def delete_server_cert(cert_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a certificate from Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_server_cert mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_server_cert(cert_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete certificate %s.', cert_name) return False def export_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM user details. Produces results that can be used to create an sls file. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.export_users --out=txt | sed "s/local: //" > iam_users.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() users = get_all_users(path_prefix, region, key, keyid, profile) for user in users: name = user.user_name _policies = conn.get_all_user_policies(name, max_items=100) _policies = _policies.list_user_policies_response.list_user_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_user_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_user_policy_response.get_user_policy_result.policy_document )) policies[policy_name] = _policy user_sls = [] user_sls.append({"name": name}) user_sls.append({"policies": policies}) user_sls.append({"path": user.path}) results["manage user " + name] = {"boto_iam.user_present": user_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def export_roles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM role details. Produces results that can be used to create an sls file. CLI Example: salt-call boto_iam.export_roles --out=txt | sed "s/local: //" > iam_roles.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() roles = get_all_roles(path_prefix, region, key, keyid, profile) for role in roles: name = role.role_name _policies = conn.list_role_policies(name, max_items=100) _policies = _policies.list_role_policies_response.list_role_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_role_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_role_policy_response.get_role_policy_result.policy_document )) policies[policy_name] = _policy role_sls = [] role_sls.append({"name": name}) role_sls.append({"policies": policies}) role_sls.append({'policy_document': salt.utils.json.loads(_unquote(role.assume_role_policy_document))}) role_sls.append({"path": role.path}) results["manage role " + name] = {"boto_iam_role.present": role_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def _get_policy_arn(name, region=None, key=None, keyid=None, profile=None): if name.startswith('arn:aws:iam:'): return name account_id = get_account_id( region=region, key=key, keyid=keyid, profile=profile ) return 'arn:aws:iam::{0}:policy/{1}'.format(account_id, name) def policy_exists(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return True except boto.exception.BotoServerError: return False def get_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return ret.get('get_policy_response', {}).get('get_policy_result', {}) except boto.exception.BotoServerError: return None def create_policy(policy_name, policy_document, path=None, description=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in 'path', 'description': if locals()[arg] is not None: params[arg] = locals()[arg] if policy_exists(policy_name, region, key, keyid, profile): return True try: conn.create_policy(policy_name, policy_document, **params) log.info('Created IAM policy %s.', policy_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s.', policy_name) return False return True def delete_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_exists(policy_arn, region, key, keyid, profile): return True try: conn.delete_policy(policy_arn) log.info('Deleted %s policy.', policy_name) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete %s policy: %s.', policy_name, aws.get('message')) return False return True def list_policies(region=None, key=None, keyid=None, profile=None): ''' List policies. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policies ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: policies = [] for ret in __utils__['boto.paged_call'](conn.list_policies): policies.append(ret.get('list_policies_response', {}).get('list_policies_result', {}).get('policies')) return policies except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to list policy versions.' log.error(msg) return [] def policy_version_exists(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.get_policy_version(policy_arn, version_id) return True except boto.exception.BotoServerError: return False def get_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy_version(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile), version_id) retval = ret.get('get_policy_version_response', {}).get('get_policy_version_result', {}).get('policy_version', {}) retval['document'] = _unquote(retval.get('document')) return {'policy_version': retval} except boto.exception.BotoServerError: return None def create_policy_version(policy_name, policy_document, set_as_default=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy version. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy_version mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in ('set_as_default',): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.create_policy_version(policy_arn, policy_document, **params) vid = ret.get('create_policy_version_response', {}).get('create_policy_version_result', {}).get('policy_version', {}).get('version_id') log.info('Created IAM policy %s version %s.', policy_name, vid) return {'created': True, 'version_id': vid} except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s version %s.', policy_name, vid) return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Delete a policy version. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_version_exists(policy_arn, version_id, region, key, keyid, profile): return True try: conn.delete_policy_version(policy_arn, version_id) log.info('Deleted IAM policy %s version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete IAM policy %s version %s: %s', policy_name, version_id, aws.get('message')) return False return True def list_policy_versions(policy_name, region=None, key=None, keyid=None, profile=None): ''' List versions of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policy_versions mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.list_policy_versions(policy_arn) return ret.get('list_policy_versions_response', {}).get('list_policy_versions_result', {}).get('versions') except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list versions for IAM policy %s.', policy_name) return [] def set_default_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Set the default version of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.set_default_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.set_default_policy_version(policy_arn, version_id) log.info('Set %s policy to version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to set %s policy to version %s: %s', policy_name, version_id, aws.get('message')) return False return True def attach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_user_policy(policy_arn, user_name) log.info('Attached policy %s to IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach %s policy to IAM user %s.', policy_name, user_name) return False return True def detach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_user_policy(policy_arn, user_name) log.info('Detached %s policy from IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach %s policy from IAM user %s.', policy_name, user_name) return False return True def attach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_group_policy(policy_arn, group_name) log.info('Attached policy %s to IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM group %s.', policy_name, group_name) return False return True def detach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_group_policy(policy_arn, group_name) log.info('Detached policy %s from IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM group %s.', policy_name, group_name) return False return True def attach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_role_policy(policy_arn, role_name) log.info('Attached policy %s to IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM role %s.', policy_name, role_name) return False return True def detach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_role_policy(policy_arn, role_name) log.info('Detached policy %s from IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM role %s.', policy_name, role_name) return False return True def list_entities_for_policy(policy_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities that a policy is attached to. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 params = {} for arg in ('path_prefix', 'entity_filter'): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) while retries: try: allret = { 'policy_groups': [], 'policy_users': [], 'policy_roles': [], } for ret in __utils__['boto.paged_call'](conn.list_entities_for_policy, policy_arn=policy_arn, **params): for k, v in six.iteritems(allret): v.extend(ret.get('list_entities_for_policy_response', {}).get('list_entities_for_policy_result', {}).get(k)) return allret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('Failed to list entities for IAM policy %s: %s', policy_name, e.message) return {} return {} def list_attached_user_policies(user_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given user. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'UserName': user_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedUserPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_user_policies_response', {}).get('list_attached_user_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM user %s.', user_name) return [] def list_attached_group_policies(group_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given group. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'GroupName': group_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedGroupPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_group_policies_response', {}).get('list_attached_group_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM group %s.', group_name) return [] def list_attached_role_policies(role_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'RoleName': role_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedRolePolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_role_policies_response', {}).get('list_attached_role_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM role %s.', role_name) return [] def create_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Create SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.create_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_saml_provider(saml_metadata_document, name) log.info('Successfully created %s SAML provider.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to create SAML provider %s.', name) return False def get_saml_provider_arn(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider_arn my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_saml_providers() for saml_provider in response.list_saml_providers_response.list_saml_providers_result.saml_provider_list: if saml_provider['arn'].endswith(':saml-provider/' + name): return saml_provider['arn'] return False except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to get ARN of SAML provider %s.', name) return False def delete_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Delete SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.delete_saml_provider my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return True conn.delete_saml_provider(saml_provider_arn) log.info('Successfully deleted SAML provider %s.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete SAML provider %s.', name) return False def list_saml_providers(region=None, key=None, keyid=None, profile=None): ''' List SAML providers. CLI Example: .. code-block:: bash salt myminion boto_iam.list_saml_providers ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: providers = [] info = conn.list_saml_providers() for arn in info['list_saml_providers_response']['list_saml_providers_result']['saml_provider_list']: providers.append(arn['arn'].rsplit('/', 1)[1]) return providers except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get list of SAML providers.') return False def get_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider document. CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider arn ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: provider = conn.get_saml_provider(name) return provider['get_saml_provider_response']['get_saml_provider_result']['saml_metadata_document'] except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get SAML provider document %s.', name) return False def update_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Update SAML provider. CLI Example: .. code-block:: bash salt myminion boto_iam.update_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return False if conn.update_saml_provider(name, saml_metadata_document): return True return False except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to update SAML provider %s.', name) return False
saltstack/salt
salt/modules/boto_iam.py
put_group_policy
python
def put_group_policy(group_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_group_policy mygroup policyname policyrules ''' group = get_group(group_name, region=region, key=key, keyid=keyid, profile=profile) if not group: log.error('Group %s does not exist', group_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_group_policy(group_name, policy_name, policy_json) if created: log.info('Created policy for IAM group %s.', group_name) return True log.error('Could not create policy for IAM group %s', group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy for IAM group %s', group_name) return False
Adds or updates the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_group_policy mygroup policyname policyrules
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iam.py#L533-L564
[ "def dumps(obj, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.dumps, and assumes that ensure_ascii is False (unless explicitly\n passed as True) for unicode compatibility. Note that setting it to True\n will mess up any unicode characters, as they will be dumped as the string\n literal version of the unicode code point.\n\n On Python 2, encodes the result to a str since json.dumps does not want\n unicode types.\n\n You can pass an alternate json module (loaded via import_json() above)\n using the _json_module argument)\n '''\n json_module = kwargs.pop('_json_module', json)\n orig_enc_func = kwargs.pop('default', lambda x: x)\n\n def _enc_func(obj):\n obj = ThreadLocalProxy.unproxy(obj)\n return orig_enc_func(obj)\n\n if 'ensure_ascii' not in kwargs:\n kwargs['ensure_ascii'] = False\n if six.PY2:\n obj = salt.utils.data.encode(obj)\n return json_module.dumps(obj, default=_enc_func, **kwargs) # future lint: blacklisted-function\n", "def get_group(group_name, region=None, key=None, keyid=None, profile=None):\n '''\n Get group information.\n\n .. versionadded:: 2015.8.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_iam.get_group mygroup\n '''\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n try:\n info = conn.get_group(group_name, max_items=1)\n if not info:\n return False\n return info['get_group_response']['get_group_result']['group']\n except boto.exception.BotoServerError as e:\n log.debug(e)\n log.error('Failed to get IAM group %s info.', group_name)\n return False\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon IAM .. versionadded:: 2014.7.0 :configuration: This module accepts explicit iam 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 iam.keyid: GKTADJGHEIQSXMKKRBJ08H iam.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs iam.region: 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: boto ''' # keep lint from choking on _get_conn and _cache_id #pylint: disable=E0602 # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import salt libs from salt.ext import six import salt.utils.compat import salt.utils.json import salt.utils.odict as odict import salt.utils.versions from salt.exceptions import SaltInvocationError # Import third party libs # pylint: disable=unused-import from salt.ext.six.moves.urllib.parse import unquote as _unquote # pylint: disable=no-name-in-module try: import boto import boto.iam import boto3 import botocore logging.getLogger('boto').setLevel(logging.CRITICAL) logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=unused-import log = logging.getLogger(__name__) def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'iam', pack=__salt__) def instance_profile_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an instance profile exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: # Boto weirdly returns an exception here if an instance profile doesn't # exist. conn.get_instance_profile(name) return True except boto.exception.BotoServerError: return False def create_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Create an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.create_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if instance_profile_exists(name, region, key, keyid, profile): return True try: # This call returns an instance profile if successful and an exception # if not. It's annoying. conn.create_instance_profile(name) log.info('Created %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create %s instance profile.', name) return False return True def delete_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Delete an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not instance_profile_exists(name, region, key, keyid, profile): return True try: conn.delete_instance_profile(name) log.info('Deleted %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s instance profile.', name) return False return True def role_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an IAM role exists. CLI Example: .. code-block:: bash salt myminion boto_iam.role_exists myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_role(name) return True except boto.exception.BotoServerError: return False def describe_role(name, region=None, key=None, keyid=None, profile=None): ''' Get information for a role. CLI Example: .. code-block:: bash salt myminion boto_iam.describe_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_role(name) if not info: return False role = info.get_role_response.get_role_result.role role['assume_role_policy_document'] = salt.utils.json.loads(_unquote( role.assume_role_policy_document )) # If Sid wasn't defined by the user, boto will still return a Sid in # each policy. To properly check idempotently, let's remove the Sid # from the return if it's not actually set. for policy_key, policy in role['assume_role_policy_document'].items(): if policy_key == 'Statement': for val in policy: if 'Sid' in val and not val['Sid']: del val['Sid'] return role except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get %s information.', name) return False def create_user(user_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_user myuser ''' if not path: path = '/' if get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_user(user_name, path) log.info('Created IAM user : %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM user %s.', user_name) return False def get_all_access_keys(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all access keys from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_access_keys myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.get_all_access_keys(user_name, marker, max_items) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get access keys for IAM user %s.', user_name) return six.text_type(e) def create_access_key(user_name, region=None, key=None, keyid=None, profile=None): ''' Create access key id for a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.create_access_key(user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create access key.') return six.text_type(e) def delete_access_key(access_key_id, user_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete access key id from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_access_key(access_key_id, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete access key id %s.', access_key_id) return six.text_type(e) def delete_user(user_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user myuser ''' if not get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.delete_user(user_name) log.info('Deleted IAM user : %s .', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM user %s', user_name) return six.text_type(e) def get_user(user_name=None, region=None, key=None, keyid=None, profile=None): ''' Get user information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user(user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM user %s info.', user_name) return False def create_group(group_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_group group ''' if not path: path = '/' if get_group(group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_group(group_name, path) log.info('Created IAM group : %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM group %s.', group_name) return False def get_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group(group_name, max_items=1) if not info: return False return info['get_group_response']['get_group_result']['group'] except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_group_members(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: marker = None truncated = True users = [] while truncated: info = conn.get_group(group_name, marker=marker, max_items=1000) if not info: return False truncated = bool(info['get_group_response']['get_group_result']['is_truncated']) if truncated and 'marker' in info['get_group_response']['get_group_result']: marker = info['get_group_response']['get_group_result']['marker'] else: marker = None truncated = False users += info['get_group_response']['get_group_result']['users'] return users except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get members for IAM group %s.', group_name) return False def add_user_to_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Add user to group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.add_user_to_group myuser mygroup ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('Username : %s does not exist.', user_name) return False if user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.add_user_to_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add IAM user %s to group %s.', user_name, group_name) return False def user_exists_in_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Check if user exists in group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.user_exists_in_group myuser mygroup ''' # TODO this should probably use boto.iam.get_groups_for_user users = get_group_members( group_name=group_name, region=region, key=key, keyid=keyid, profile=profile ) if users: for _user in users: if user_name == _user['user_name']: log.debug('IAM user %s is already in IAM group %s.', user_name, group_name) return True return False def remove_user_from_group(group_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Remove user from group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.remove_user_from_group mygroup myuser ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist.', user_name) return False if not user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.remove_user_from_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove IAM user %s from group %s', user_name, group_name) return False def delete_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group_policy mygroup mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_group_policy( group_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_group_policy(group_name, policy_name) log.info('Successfully deleted policy %s for IAM group %s.', policy_name, group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM group %s.', policy_name, group_name) return False def get_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group_policy mygroup policyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group_policy(group_name, policy_name) log.debug('info for group policy is : %s', info) if not info: return False info = info.get_group_policy_response.get_group_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_all_groups(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM group details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_groups ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _groups = conn.get_all_groups(path_prefix=path_prefix) groups = _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) while marker: _groups = conn.get_all_groups(path_prefix=path_prefix, marker=marker) groups = groups + _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) return groups def get_all_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.get_all_instance_profiles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) marker = False profiles = [] while marker is not None: marker = marker if marker else None p = conn.list_instance_profiles(path_prefix=path_prefix, marker=marker) res = p.list_instance_profiles_response.list_instance_profiles_result profiles += res.instance_profiles marker = getattr(res, 'marker', None) return profiles def list_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' List all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.list_instance_profiles ''' p = get_all_instance_profiles(path_prefix, region, key, keyid, profile) return [i['instance_profile_name'] for i in p] def get_all_group_policies(group_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a group. CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_group_policies mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False try: response = conn.get_all_group_policies(group_name) _list = response.list_group_policies_response.list_group_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def delete_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _group = get_group( group_name, region, key, keyid, profile ) if not _group: return True try: conn.delete_group(group_name) log.info('Successfully deleted IAM group %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM group %s.', group_name) return False def create_login_profile(user_name, password, region=None, key=None, keyid=None, profile=None): ''' Creates a login profile for the specified user, give the user the ability to access AWS services and the AWS Management Console. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_login_profile user_name password ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.create_login_profile(user_name, password) log.info('Created profile for IAM user %s.', user_name) return info except boto.exception.BotoServerError as e: log.debug(e) if 'Conflict' in e: log.info('Profile already exists for IAM user %s.', user_name) return 'Conflict' log.error('Failed to update profile for IAM user %s.', user_name) return False def delete_login_profile(user_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a login profile for the specified user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_login_profile user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.delete_login_profile(user_name) log.info('Deleted login profile for IAM user %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Login profile already deleted for IAM user %s.', user_name) return True log.error('Failed to delete login profile for IAM user %s.', user_name) return False def get_all_mfa_devices(user_name, region=None, key=None, keyid=None, profile=None): ''' Get all MFA devices associated with an IAM user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_mfa_devices user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: result = conn.get_all_mfa_devices(user_name) devices = result['list_mfa_devices_response']['list_mfa_devices_result']['mfa_devices'] return devices except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Could not find IAM user %s.', user_name) return [] log.error('Failed to get all MFA devices for IAM user %s.', user_name) return False def deactivate_mfa_device(user_name, serial, region=None, key=None, keyid=None, profile=None): ''' Deactivates the specified MFA device and removes it from association with the user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.deactivate_mfa_device user_name serial_num ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.deactivate_mfa_device(user_name, serial) log.info('Deactivated MFA device %s for IAM user %s.', serial, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('MFA device %s not associated with IAM user %s.', serial, user_name) return True log.error('Failed to deactivate MFA device %s for IAM user %s.', serial, user_name) return False def delete_virtual_mfa_device(serial, region=None, key=None, keyid=None, profile=None): ''' Deletes the specified virtual MFA device. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_virtual_mfa_device serial_num ''' conn = __utils__['boto3.get_connection_func']('iam')() try: conn.delete_virtual_mfa_device(SerialNumber=serial) log.info('Deleted virtual MFA device %s.', serial) return True except botocore.exceptions.ClientError as e: log.debug(e) if 'NoSuchEntity' in six.text_type(e): log.info('Virtual MFA device %s not found.', serial) return True log.error('Failed to delete virtual MFA device %s.', serial) return False def update_account_password_policy(allow_users_to_change_password=None, hard_expiry=None, max_password_age=None, minimum_password_length=None, password_reuse_prevention=None, require_lowercase_characters=None, require_numbers=None, require_symbols=None, require_uppercase_characters=None, region=None, key=None, keyid=None, profile=None): ''' Update the password policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_account_password_policy True ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.update_account_password_policy(allow_users_to_change_password, hard_expiry, max_password_age, minimum_password_length, password_reuse_prevention, require_lowercase_characters, require_numbers, require_symbols, require_uppercase_characters) log.info('The password policy has been updated.') return True except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy' log.error(msg) return False def get_account_policy(region=None, key=None, keyid=None, profile=None): ''' Get account policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_account_password_policy() return info.get_account_password_policy_response.get_account_password_policy_result.password_policy except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy.' log.error(msg) return False def create_role(name, policy_document=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Create an instance role. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if role_exists(name, region, key, keyid, profile): return True if not policy_document: policy_document = None try: conn.create_role(name, assume_role_policy_document=policy_document, path=path) log.info('Created IAM role %s.', name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to create IAM role %s.', name) return False def delete_role(name, region=None, key=None, keyid=None, profile=None): ''' Delete an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(name, region, key, keyid, profile): return True try: conn.delete_role(name) log.info('Deleted %s IAM role.', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s IAM role.', name) return False def profile_associated(role_name, profile_name, region, key, keyid, profile): ''' Check to see if an instance profile is associated with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.profile_associated myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # The IAM module of boto doesn't return objects. Instead you need to grab # values through its properties. Sigh. try: profiles = conn.list_instance_profiles_for_role(role_name) except boto.exception.BotoServerError as e: log.debug(e) return False profiles = profiles.list_instance_profiles_for_role_response profiles = profiles.list_instance_profiles_for_role_result profiles = profiles.instance_profiles for profile in profiles: if profile.instance_profile_name == profile_name: return True return False def associate_profile_to_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Associate an instance profile with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.associate_profile_to_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if associated: return True else: try: conn.add_role_to_instance_profile(profile_name, role_name) log.info('Added %s instance profile to IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add %s instance profile to IAM role %s', profile_name, role_name) return False def disassociate_profile_from_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Disassociate an instance profile from an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.disassociate_profile_from_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if not associated: return True else: try: conn.remove_role_from_instance_profile(profile_name, role_name) log.info('Removed %s instance profile from IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove %s instance profile from IAM role %s.', profile_name, role_name) return False def list_role_policies(role_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_role_policies myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_role_policies(role_name) _list = response.list_role_policies_response.list_role_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def get_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.get_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: _policy = conn.get_role_policy(role_name, policy_name) # I _hate_ you for not giving me an object boto. _policy = _policy.get_role_policy_response.policy_document # Policy is url encoded _policy = _unquote(_policy) _policy = salt.utils.json.loads(_policy, object_pairs_hook=odict.OrderedDict) return _policy except boto.exception.BotoServerError: return {} def create_role_policy(role_name, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Create or modify a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role_policy myirole mypolicy '{"MyPolicy": "Statement": [{"Action": ["sqs:*"], "Effect": "Allow", "Resource": ["arn:aws:sqs:*:*:*"], "Sid": "MyPolicySqs1"}]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) mode = 'create' if _policy: if _policy == policy: return True mode = 'modify' if isinstance(policy, six.string_types): policy = salt.utils.json.loads(policy, object_pairs_hook=odict.OrderedDict) try: _policy = salt.utils.json.dumps(policy) conn.put_role_policy(role_name, policy_name, _policy) if mode == 'create': msg = 'Successfully added policy %s to IAM role %s.' else: msg = 'Successfully modified policy %s for IAM role %s.' log.info(msg, policy_name, role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to %s policy %s for IAM role %s.', mode, policy_name, role_name) return False def delete_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) if not _policy: return True try: conn.delete_role_policy(role_name, policy_name) log.info('Successfully deleted policy %s for IAM role %s.', policy_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM role %s.', policy_name, role_name) return False def update_assume_role_policy(role_name, policy_document, region=None, key=None, keyid=None, profile=None): ''' Update an assume role policy for a role. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_assume_role_policy myrole '{"Statement":"..."}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(policy_document, six.string_types): policy_document = salt.utils.json.loads(policy_document, object_pairs_hook=odict.OrderedDict) try: _policy_document = salt.utils.json.dumps(policy_document) conn.update_assume_role_policy(role_name, _policy_document) log.info('Successfully updated assume role policy for IAM role %s.', role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to update assume role policy for IAM role %s.', role_name) return False def build_policy(region=None, key=None, keyid=None, profile=None): ''' Build a default assume role policy. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.build_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if hasattr(conn, 'build_policy'): policy = salt.utils.json.loads(conn.build_policy()) elif hasattr(conn, '_build_policy'): policy = salt.utils.json.loads(conn._build_policy()) else: return {} # The format we get from build_policy isn't going to be what we get back # from AWS for the exact same policy. AWS converts single item list values # into strings, so let's do the same here. for key, policy_val in policy.items(): for statement in policy_val: if (isinstance(statement['Action'], list) and len(statement['Action']) == 1): statement['Action'] = statement['Action'][0] if (isinstance(statement['Principal']['Service'], list) and len(statement['Principal']['Service']) == 1): statement['Principal']['Service'] = statement['Principal']['Service'][0] # build_policy doesn't add a version field, which AWS is going to set to a # default value, when we get it back, so let's set it. policy['Version'] = '2008-10-17' return policy def get_account_id(region=None, key=None, keyid=None, profile=None): ''' Get a the AWS account id associated with the used credentials. CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_id ''' cache_key = 'boto_iam.account_id' if cache_key not in __context__: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_user() # The get_user call returns an user ARN: # arn:aws:iam::027050522557:user/salt-test arn = ret['get_user_response']['get_user_result']['user']['arn'] account_id = arn.split(':')[4] except boto.exception.BotoServerError: # If call failed, then let's try to get the ARN from the metadata timeout = boto.config.getfloat( 'Boto', 'metadata_service_timeout', 1.0 ) attempts = boto.config.getint( 'Boto', 'metadata_service_num_attempts', 1 ) identity = boto.utils.get_instance_identity( timeout=timeout, num_retries=attempts ) try: account_id = identity['document']['accountId'] except KeyError: log.error('Failed to get account id from instance_identity in' ' boto_iam.get_account_id.') __context__[cache_key] = account_id return __context__[cache_key] def get_all_roles(path_prefix=None, region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM role details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_roles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _roles = conn.list_roles(path_prefix=path_prefix) roles = _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) while marker: _roles = conn.list_roles(path_prefix=path_prefix, marker=marker) roles = roles + _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) return roles def get_all_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM user details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_users ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _users = conn.get_all_users(path_prefix=path_prefix) users = _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) while marker: _users = conn.get_all_users(path_prefix=path_prefix, marker=marker) users = users + _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) return users def get_all_user_policies(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all user policies. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_user_policies myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_all_user_policies(user_name, marker, max_items) if not info: return False _list = info.list_user_policies_response.list_user_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policies for user %s.', user_name) return False def get_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user_policy myuser mypolicyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user_policy(user_name, policy_name) log.debug('Info for IAM user %s policy %s: %s.', user_name, policy_name, info) if not info: return False info = info.get_user_policy_response.get_user_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policy %s for IAM user %s.', policy_name, user_name) return False def put_user_policy(user_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_user_policy myuser policyname policyrules ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_user_policy(user_name, policy_name, policy_json) if created: log.info('Created policy %s for IAM user %s.', policy_name, user_name) return True log.error('Could not create policy %s for IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy %s for IAM user %s.', policy_name, user_name) return False def delete_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user_policy myuser mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_user_policy( user_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_user_policy(user_name, policy_name) log.info('Successfully deleted policy %s for IAM user %s.', policy_name, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM user %s.', policy_name, user_name) return False def upload_server_cert(cert_name, cert_body, private_key, cert_chain=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Upload a certificate to Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.upload_server_cert mycert_name crt priv_key :param cert_name: The name for the server certificate. Do not include the path in this value. :param cert_body: The contents of the public key certificate in PEM-encoded format. :param private_key: The contents of the private key in PEM-encoded format. :param cert_chain: The contents of the certificate chain. This is typically a concatenation of the PEM-encoded public key certificates of the chain. :param path: The path for the server certificate. :param region: The name of the region to connect to. :param key: The key to be used in order to connect :param keyid: The keyid to be used in order to connect :param profile: The profile that contains a dict of region, key, keyid :return: True / False ''' exists = get_server_certificate(cert_name, region, key, keyid, profile) if exists: return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.upload_server_cert(cert_name, cert_body, private_key, cert_chain) log.info('Created certificate %s.', cert_name) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to failed to create certificate %s.', cert_name) return False def list_server_certificates(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Lists the server certificates stored in IAM that have the specified path prefix. .. versionadded:: ??? :param path_prefix: The path prefix for filtering the results. For example: /company/servercerts would get all server certificates for which the path starts with /company/servercerts . This parameter is optional. If it is not included, it defaults to a slash (/), listing all server certificates. This parameter allows (per its regex pattern) a string of characters consisting of either a forward slash (/) by itself or a string that must begin and end with forward slashes. In addition, it can contain any ASCII character from the ! (u0021) through the DEL character (u007F), including most punctuation characters, digits, and upper and lowercased letters. CLI Example: .. code-block:: bash salt myminion boto_iam.list_server_certificates path_prefix=/somepath/ ''' retries = 10 sleep = 6 conn = __utils__['boto3.get_connection']('iam', region=region, key=key, keyid=keyid, profile=profile) Items = [] while retries: try: log.debug('Garnering list of IAM Server Certificates') IsTruncated = True while IsTruncated: kwargs = {'PathPrefix': path_prefix} ret = conn.list_server_certificates(**kwargs) Items += ret.get('ServerCertificateMetadataList', []) IsTruncated = ret.get('IsTruncated') kwargs.update({'Marker': ret.get('Marker')}) return Items except botocore.exceptions.ParamValidationError as err: raise SaltInvocationError(str(err)) except botocore.exceptions.ClientError as err: if retries and jmespath.search('Error.Code', err.response) == 'Throttling': retries -= 1 log.debug('Throttled by AWS API, retrying in %s seconds...', sleep) time.sleep(sleep) continue log.error('Failed to list IAM Server Certificates: %s', err.message) return None def get_server_certificate(cert_name, region=None, key=None, keyid=None, profile=None): ''' Returns certificate information from Amazon .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_server_certificate mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_server_certificate(cert_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get certificate %s information.', cert_name) return False def delete_server_cert(cert_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a certificate from Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_server_cert mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_server_cert(cert_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete certificate %s.', cert_name) return False def export_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM user details. Produces results that can be used to create an sls file. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.export_users --out=txt | sed "s/local: //" > iam_users.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() users = get_all_users(path_prefix, region, key, keyid, profile) for user in users: name = user.user_name _policies = conn.get_all_user_policies(name, max_items=100) _policies = _policies.list_user_policies_response.list_user_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_user_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_user_policy_response.get_user_policy_result.policy_document )) policies[policy_name] = _policy user_sls = [] user_sls.append({"name": name}) user_sls.append({"policies": policies}) user_sls.append({"path": user.path}) results["manage user " + name] = {"boto_iam.user_present": user_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def export_roles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM role details. Produces results that can be used to create an sls file. CLI Example: salt-call boto_iam.export_roles --out=txt | sed "s/local: //" > iam_roles.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() roles = get_all_roles(path_prefix, region, key, keyid, profile) for role in roles: name = role.role_name _policies = conn.list_role_policies(name, max_items=100) _policies = _policies.list_role_policies_response.list_role_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_role_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_role_policy_response.get_role_policy_result.policy_document )) policies[policy_name] = _policy role_sls = [] role_sls.append({"name": name}) role_sls.append({"policies": policies}) role_sls.append({'policy_document': salt.utils.json.loads(_unquote(role.assume_role_policy_document))}) role_sls.append({"path": role.path}) results["manage role " + name] = {"boto_iam_role.present": role_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def _get_policy_arn(name, region=None, key=None, keyid=None, profile=None): if name.startswith('arn:aws:iam:'): return name account_id = get_account_id( region=region, key=key, keyid=keyid, profile=profile ) return 'arn:aws:iam::{0}:policy/{1}'.format(account_id, name) def policy_exists(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return True except boto.exception.BotoServerError: return False def get_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return ret.get('get_policy_response', {}).get('get_policy_result', {}) except boto.exception.BotoServerError: return None def create_policy(policy_name, policy_document, path=None, description=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in 'path', 'description': if locals()[arg] is not None: params[arg] = locals()[arg] if policy_exists(policy_name, region, key, keyid, profile): return True try: conn.create_policy(policy_name, policy_document, **params) log.info('Created IAM policy %s.', policy_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s.', policy_name) return False return True def delete_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_exists(policy_arn, region, key, keyid, profile): return True try: conn.delete_policy(policy_arn) log.info('Deleted %s policy.', policy_name) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete %s policy: %s.', policy_name, aws.get('message')) return False return True def list_policies(region=None, key=None, keyid=None, profile=None): ''' List policies. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policies ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: policies = [] for ret in __utils__['boto.paged_call'](conn.list_policies): policies.append(ret.get('list_policies_response', {}).get('list_policies_result', {}).get('policies')) return policies except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to list policy versions.' log.error(msg) return [] def policy_version_exists(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.get_policy_version(policy_arn, version_id) return True except boto.exception.BotoServerError: return False def get_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy_version(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile), version_id) retval = ret.get('get_policy_version_response', {}).get('get_policy_version_result', {}).get('policy_version', {}) retval['document'] = _unquote(retval.get('document')) return {'policy_version': retval} except boto.exception.BotoServerError: return None def create_policy_version(policy_name, policy_document, set_as_default=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy version. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy_version mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in ('set_as_default',): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.create_policy_version(policy_arn, policy_document, **params) vid = ret.get('create_policy_version_response', {}).get('create_policy_version_result', {}).get('policy_version', {}).get('version_id') log.info('Created IAM policy %s version %s.', policy_name, vid) return {'created': True, 'version_id': vid} except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s version %s.', policy_name, vid) return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Delete a policy version. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_version_exists(policy_arn, version_id, region, key, keyid, profile): return True try: conn.delete_policy_version(policy_arn, version_id) log.info('Deleted IAM policy %s version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete IAM policy %s version %s: %s', policy_name, version_id, aws.get('message')) return False return True def list_policy_versions(policy_name, region=None, key=None, keyid=None, profile=None): ''' List versions of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policy_versions mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.list_policy_versions(policy_arn) return ret.get('list_policy_versions_response', {}).get('list_policy_versions_result', {}).get('versions') except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list versions for IAM policy %s.', policy_name) return [] def set_default_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Set the default version of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.set_default_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.set_default_policy_version(policy_arn, version_id) log.info('Set %s policy to version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to set %s policy to version %s: %s', policy_name, version_id, aws.get('message')) return False return True def attach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_user_policy(policy_arn, user_name) log.info('Attached policy %s to IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach %s policy to IAM user %s.', policy_name, user_name) return False return True def detach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_user_policy(policy_arn, user_name) log.info('Detached %s policy from IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach %s policy from IAM user %s.', policy_name, user_name) return False return True def attach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_group_policy(policy_arn, group_name) log.info('Attached policy %s to IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM group %s.', policy_name, group_name) return False return True def detach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_group_policy(policy_arn, group_name) log.info('Detached policy %s from IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM group %s.', policy_name, group_name) return False return True def attach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_role_policy(policy_arn, role_name) log.info('Attached policy %s to IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM role %s.', policy_name, role_name) return False return True def detach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_role_policy(policy_arn, role_name) log.info('Detached policy %s from IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM role %s.', policy_name, role_name) return False return True def list_entities_for_policy(policy_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities that a policy is attached to. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 params = {} for arg in ('path_prefix', 'entity_filter'): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) while retries: try: allret = { 'policy_groups': [], 'policy_users': [], 'policy_roles': [], } for ret in __utils__['boto.paged_call'](conn.list_entities_for_policy, policy_arn=policy_arn, **params): for k, v in six.iteritems(allret): v.extend(ret.get('list_entities_for_policy_response', {}).get('list_entities_for_policy_result', {}).get(k)) return allret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('Failed to list entities for IAM policy %s: %s', policy_name, e.message) return {} return {} def list_attached_user_policies(user_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given user. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'UserName': user_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedUserPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_user_policies_response', {}).get('list_attached_user_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM user %s.', user_name) return [] def list_attached_group_policies(group_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given group. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'GroupName': group_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedGroupPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_group_policies_response', {}).get('list_attached_group_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM group %s.', group_name) return [] def list_attached_role_policies(role_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'RoleName': role_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedRolePolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_role_policies_response', {}).get('list_attached_role_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM role %s.', role_name) return [] def create_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Create SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.create_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_saml_provider(saml_metadata_document, name) log.info('Successfully created %s SAML provider.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to create SAML provider %s.', name) return False def get_saml_provider_arn(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider_arn my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_saml_providers() for saml_provider in response.list_saml_providers_response.list_saml_providers_result.saml_provider_list: if saml_provider['arn'].endswith(':saml-provider/' + name): return saml_provider['arn'] return False except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to get ARN of SAML provider %s.', name) return False def delete_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Delete SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.delete_saml_provider my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return True conn.delete_saml_provider(saml_provider_arn) log.info('Successfully deleted SAML provider %s.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete SAML provider %s.', name) return False def list_saml_providers(region=None, key=None, keyid=None, profile=None): ''' List SAML providers. CLI Example: .. code-block:: bash salt myminion boto_iam.list_saml_providers ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: providers = [] info = conn.list_saml_providers() for arn in info['list_saml_providers_response']['list_saml_providers_result']['saml_provider_list']: providers.append(arn['arn'].rsplit('/', 1)[1]) return providers except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get list of SAML providers.') return False def get_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider document. CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider arn ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: provider = conn.get_saml_provider(name) return provider['get_saml_provider_response']['get_saml_provider_result']['saml_metadata_document'] except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get SAML provider document %s.', name) return False def update_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Update SAML provider. CLI Example: .. code-block:: bash salt myminion boto_iam.update_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return False if conn.update_saml_provider(name, saml_metadata_document): return True return False except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to update SAML provider %s.', name) return False
saltstack/salt
salt/modules/boto_iam.py
delete_group_policy
python
def delete_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group_policy mygroup mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_group_policy( group_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_group_policy(group_name, policy_name) log.info('Successfully deleted policy %s for IAM group %s.', policy_name, group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM group %s.', policy_name, group_name) return False
Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group_policy mygroup mypolicy
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iam.py#L567-L593
[ "def get_group_policy(group_name, policy_name, region=None, key=None,\n keyid=None, profile=None):\n '''\n Retrieves the specified policy document for the specified group.\n\n .. versionadded:: 2015.8.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_iam.get_group_policy mygroup policyname\n '''\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n try:\n info = conn.get_group_policy(group_name, policy_name)\n log.debug('info for group policy is : %s', info)\n if not info:\n return False\n info = info.get_group_policy_response.get_group_policy_result.policy_document\n info = _unquote(info)\n info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict)\n return info\n except boto.exception.BotoServerError as e:\n log.debug(e)\n log.error('Failed to get IAM group %s info.', group_name)\n return False\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon IAM .. versionadded:: 2014.7.0 :configuration: This module accepts explicit iam 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 iam.keyid: GKTADJGHEIQSXMKKRBJ08H iam.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs iam.region: 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: boto ''' # keep lint from choking on _get_conn and _cache_id #pylint: disable=E0602 # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import salt libs from salt.ext import six import salt.utils.compat import salt.utils.json import salt.utils.odict as odict import salt.utils.versions from salt.exceptions import SaltInvocationError # Import third party libs # pylint: disable=unused-import from salt.ext.six.moves.urllib.parse import unquote as _unquote # pylint: disable=no-name-in-module try: import boto import boto.iam import boto3 import botocore logging.getLogger('boto').setLevel(logging.CRITICAL) logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=unused-import log = logging.getLogger(__name__) def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'iam', pack=__salt__) def instance_profile_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an instance profile exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: # Boto weirdly returns an exception here if an instance profile doesn't # exist. conn.get_instance_profile(name) return True except boto.exception.BotoServerError: return False def create_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Create an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.create_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if instance_profile_exists(name, region, key, keyid, profile): return True try: # This call returns an instance profile if successful and an exception # if not. It's annoying. conn.create_instance_profile(name) log.info('Created %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create %s instance profile.', name) return False return True def delete_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Delete an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not instance_profile_exists(name, region, key, keyid, profile): return True try: conn.delete_instance_profile(name) log.info('Deleted %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s instance profile.', name) return False return True def role_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an IAM role exists. CLI Example: .. code-block:: bash salt myminion boto_iam.role_exists myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_role(name) return True except boto.exception.BotoServerError: return False def describe_role(name, region=None, key=None, keyid=None, profile=None): ''' Get information for a role. CLI Example: .. code-block:: bash salt myminion boto_iam.describe_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_role(name) if not info: return False role = info.get_role_response.get_role_result.role role['assume_role_policy_document'] = salt.utils.json.loads(_unquote( role.assume_role_policy_document )) # If Sid wasn't defined by the user, boto will still return a Sid in # each policy. To properly check idempotently, let's remove the Sid # from the return if it's not actually set. for policy_key, policy in role['assume_role_policy_document'].items(): if policy_key == 'Statement': for val in policy: if 'Sid' in val and not val['Sid']: del val['Sid'] return role except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get %s information.', name) return False def create_user(user_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_user myuser ''' if not path: path = '/' if get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_user(user_name, path) log.info('Created IAM user : %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM user %s.', user_name) return False def get_all_access_keys(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all access keys from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_access_keys myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.get_all_access_keys(user_name, marker, max_items) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get access keys for IAM user %s.', user_name) return six.text_type(e) def create_access_key(user_name, region=None, key=None, keyid=None, profile=None): ''' Create access key id for a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.create_access_key(user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create access key.') return six.text_type(e) def delete_access_key(access_key_id, user_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete access key id from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_access_key(access_key_id, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete access key id %s.', access_key_id) return six.text_type(e) def delete_user(user_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user myuser ''' if not get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.delete_user(user_name) log.info('Deleted IAM user : %s .', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM user %s', user_name) return six.text_type(e) def get_user(user_name=None, region=None, key=None, keyid=None, profile=None): ''' Get user information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user(user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM user %s info.', user_name) return False def create_group(group_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_group group ''' if not path: path = '/' if get_group(group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_group(group_name, path) log.info('Created IAM group : %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM group %s.', group_name) return False def get_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group(group_name, max_items=1) if not info: return False return info['get_group_response']['get_group_result']['group'] except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_group_members(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: marker = None truncated = True users = [] while truncated: info = conn.get_group(group_name, marker=marker, max_items=1000) if not info: return False truncated = bool(info['get_group_response']['get_group_result']['is_truncated']) if truncated and 'marker' in info['get_group_response']['get_group_result']: marker = info['get_group_response']['get_group_result']['marker'] else: marker = None truncated = False users += info['get_group_response']['get_group_result']['users'] return users except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get members for IAM group %s.', group_name) return False def add_user_to_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Add user to group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.add_user_to_group myuser mygroup ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('Username : %s does not exist.', user_name) return False if user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.add_user_to_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add IAM user %s to group %s.', user_name, group_name) return False def user_exists_in_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Check if user exists in group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.user_exists_in_group myuser mygroup ''' # TODO this should probably use boto.iam.get_groups_for_user users = get_group_members( group_name=group_name, region=region, key=key, keyid=keyid, profile=profile ) if users: for _user in users: if user_name == _user['user_name']: log.debug('IAM user %s is already in IAM group %s.', user_name, group_name) return True return False def remove_user_from_group(group_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Remove user from group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.remove_user_from_group mygroup myuser ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist.', user_name) return False if not user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.remove_user_from_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove IAM user %s from group %s', user_name, group_name) return False def put_group_policy(group_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_group_policy mygroup policyname policyrules ''' group = get_group(group_name, region=region, key=key, keyid=keyid, profile=profile) if not group: log.error('Group %s does not exist', group_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_group_policy(group_name, policy_name, policy_json) if created: log.info('Created policy for IAM group %s.', group_name) return True log.error('Could not create policy for IAM group %s', group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy for IAM group %s', group_name) return False def get_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group_policy mygroup policyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group_policy(group_name, policy_name) log.debug('info for group policy is : %s', info) if not info: return False info = info.get_group_policy_response.get_group_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_all_groups(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM group details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_groups ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _groups = conn.get_all_groups(path_prefix=path_prefix) groups = _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) while marker: _groups = conn.get_all_groups(path_prefix=path_prefix, marker=marker) groups = groups + _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) return groups def get_all_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.get_all_instance_profiles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) marker = False profiles = [] while marker is not None: marker = marker if marker else None p = conn.list_instance_profiles(path_prefix=path_prefix, marker=marker) res = p.list_instance_profiles_response.list_instance_profiles_result profiles += res.instance_profiles marker = getattr(res, 'marker', None) return profiles def list_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' List all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.list_instance_profiles ''' p = get_all_instance_profiles(path_prefix, region, key, keyid, profile) return [i['instance_profile_name'] for i in p] def get_all_group_policies(group_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a group. CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_group_policies mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False try: response = conn.get_all_group_policies(group_name) _list = response.list_group_policies_response.list_group_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def delete_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _group = get_group( group_name, region, key, keyid, profile ) if not _group: return True try: conn.delete_group(group_name) log.info('Successfully deleted IAM group %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM group %s.', group_name) return False def create_login_profile(user_name, password, region=None, key=None, keyid=None, profile=None): ''' Creates a login profile for the specified user, give the user the ability to access AWS services and the AWS Management Console. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_login_profile user_name password ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.create_login_profile(user_name, password) log.info('Created profile for IAM user %s.', user_name) return info except boto.exception.BotoServerError as e: log.debug(e) if 'Conflict' in e: log.info('Profile already exists for IAM user %s.', user_name) return 'Conflict' log.error('Failed to update profile for IAM user %s.', user_name) return False def delete_login_profile(user_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a login profile for the specified user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_login_profile user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.delete_login_profile(user_name) log.info('Deleted login profile for IAM user %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Login profile already deleted for IAM user %s.', user_name) return True log.error('Failed to delete login profile for IAM user %s.', user_name) return False def get_all_mfa_devices(user_name, region=None, key=None, keyid=None, profile=None): ''' Get all MFA devices associated with an IAM user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_mfa_devices user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: result = conn.get_all_mfa_devices(user_name) devices = result['list_mfa_devices_response']['list_mfa_devices_result']['mfa_devices'] return devices except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Could not find IAM user %s.', user_name) return [] log.error('Failed to get all MFA devices for IAM user %s.', user_name) return False def deactivate_mfa_device(user_name, serial, region=None, key=None, keyid=None, profile=None): ''' Deactivates the specified MFA device and removes it from association with the user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.deactivate_mfa_device user_name serial_num ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.deactivate_mfa_device(user_name, serial) log.info('Deactivated MFA device %s for IAM user %s.', serial, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('MFA device %s not associated with IAM user %s.', serial, user_name) return True log.error('Failed to deactivate MFA device %s for IAM user %s.', serial, user_name) return False def delete_virtual_mfa_device(serial, region=None, key=None, keyid=None, profile=None): ''' Deletes the specified virtual MFA device. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_virtual_mfa_device serial_num ''' conn = __utils__['boto3.get_connection_func']('iam')() try: conn.delete_virtual_mfa_device(SerialNumber=serial) log.info('Deleted virtual MFA device %s.', serial) return True except botocore.exceptions.ClientError as e: log.debug(e) if 'NoSuchEntity' in six.text_type(e): log.info('Virtual MFA device %s not found.', serial) return True log.error('Failed to delete virtual MFA device %s.', serial) return False def update_account_password_policy(allow_users_to_change_password=None, hard_expiry=None, max_password_age=None, minimum_password_length=None, password_reuse_prevention=None, require_lowercase_characters=None, require_numbers=None, require_symbols=None, require_uppercase_characters=None, region=None, key=None, keyid=None, profile=None): ''' Update the password policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_account_password_policy True ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.update_account_password_policy(allow_users_to_change_password, hard_expiry, max_password_age, minimum_password_length, password_reuse_prevention, require_lowercase_characters, require_numbers, require_symbols, require_uppercase_characters) log.info('The password policy has been updated.') return True except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy' log.error(msg) return False def get_account_policy(region=None, key=None, keyid=None, profile=None): ''' Get account policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_account_password_policy() return info.get_account_password_policy_response.get_account_password_policy_result.password_policy except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy.' log.error(msg) return False def create_role(name, policy_document=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Create an instance role. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if role_exists(name, region, key, keyid, profile): return True if not policy_document: policy_document = None try: conn.create_role(name, assume_role_policy_document=policy_document, path=path) log.info('Created IAM role %s.', name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to create IAM role %s.', name) return False def delete_role(name, region=None, key=None, keyid=None, profile=None): ''' Delete an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(name, region, key, keyid, profile): return True try: conn.delete_role(name) log.info('Deleted %s IAM role.', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s IAM role.', name) return False def profile_associated(role_name, profile_name, region, key, keyid, profile): ''' Check to see if an instance profile is associated with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.profile_associated myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # The IAM module of boto doesn't return objects. Instead you need to grab # values through its properties. Sigh. try: profiles = conn.list_instance_profiles_for_role(role_name) except boto.exception.BotoServerError as e: log.debug(e) return False profiles = profiles.list_instance_profiles_for_role_response profiles = profiles.list_instance_profiles_for_role_result profiles = profiles.instance_profiles for profile in profiles: if profile.instance_profile_name == profile_name: return True return False def associate_profile_to_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Associate an instance profile with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.associate_profile_to_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if associated: return True else: try: conn.add_role_to_instance_profile(profile_name, role_name) log.info('Added %s instance profile to IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add %s instance profile to IAM role %s', profile_name, role_name) return False def disassociate_profile_from_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Disassociate an instance profile from an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.disassociate_profile_from_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if not associated: return True else: try: conn.remove_role_from_instance_profile(profile_name, role_name) log.info('Removed %s instance profile from IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove %s instance profile from IAM role %s.', profile_name, role_name) return False def list_role_policies(role_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_role_policies myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_role_policies(role_name) _list = response.list_role_policies_response.list_role_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def get_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.get_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: _policy = conn.get_role_policy(role_name, policy_name) # I _hate_ you for not giving me an object boto. _policy = _policy.get_role_policy_response.policy_document # Policy is url encoded _policy = _unquote(_policy) _policy = salt.utils.json.loads(_policy, object_pairs_hook=odict.OrderedDict) return _policy except boto.exception.BotoServerError: return {} def create_role_policy(role_name, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Create or modify a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role_policy myirole mypolicy '{"MyPolicy": "Statement": [{"Action": ["sqs:*"], "Effect": "Allow", "Resource": ["arn:aws:sqs:*:*:*"], "Sid": "MyPolicySqs1"}]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) mode = 'create' if _policy: if _policy == policy: return True mode = 'modify' if isinstance(policy, six.string_types): policy = salt.utils.json.loads(policy, object_pairs_hook=odict.OrderedDict) try: _policy = salt.utils.json.dumps(policy) conn.put_role_policy(role_name, policy_name, _policy) if mode == 'create': msg = 'Successfully added policy %s to IAM role %s.' else: msg = 'Successfully modified policy %s for IAM role %s.' log.info(msg, policy_name, role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to %s policy %s for IAM role %s.', mode, policy_name, role_name) return False def delete_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) if not _policy: return True try: conn.delete_role_policy(role_name, policy_name) log.info('Successfully deleted policy %s for IAM role %s.', policy_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM role %s.', policy_name, role_name) return False def update_assume_role_policy(role_name, policy_document, region=None, key=None, keyid=None, profile=None): ''' Update an assume role policy for a role. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_assume_role_policy myrole '{"Statement":"..."}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(policy_document, six.string_types): policy_document = salt.utils.json.loads(policy_document, object_pairs_hook=odict.OrderedDict) try: _policy_document = salt.utils.json.dumps(policy_document) conn.update_assume_role_policy(role_name, _policy_document) log.info('Successfully updated assume role policy for IAM role %s.', role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to update assume role policy for IAM role %s.', role_name) return False def build_policy(region=None, key=None, keyid=None, profile=None): ''' Build a default assume role policy. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.build_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if hasattr(conn, 'build_policy'): policy = salt.utils.json.loads(conn.build_policy()) elif hasattr(conn, '_build_policy'): policy = salt.utils.json.loads(conn._build_policy()) else: return {} # The format we get from build_policy isn't going to be what we get back # from AWS for the exact same policy. AWS converts single item list values # into strings, so let's do the same here. for key, policy_val in policy.items(): for statement in policy_val: if (isinstance(statement['Action'], list) and len(statement['Action']) == 1): statement['Action'] = statement['Action'][0] if (isinstance(statement['Principal']['Service'], list) and len(statement['Principal']['Service']) == 1): statement['Principal']['Service'] = statement['Principal']['Service'][0] # build_policy doesn't add a version field, which AWS is going to set to a # default value, when we get it back, so let's set it. policy['Version'] = '2008-10-17' return policy def get_account_id(region=None, key=None, keyid=None, profile=None): ''' Get a the AWS account id associated with the used credentials. CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_id ''' cache_key = 'boto_iam.account_id' if cache_key not in __context__: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_user() # The get_user call returns an user ARN: # arn:aws:iam::027050522557:user/salt-test arn = ret['get_user_response']['get_user_result']['user']['arn'] account_id = arn.split(':')[4] except boto.exception.BotoServerError: # If call failed, then let's try to get the ARN from the metadata timeout = boto.config.getfloat( 'Boto', 'metadata_service_timeout', 1.0 ) attempts = boto.config.getint( 'Boto', 'metadata_service_num_attempts', 1 ) identity = boto.utils.get_instance_identity( timeout=timeout, num_retries=attempts ) try: account_id = identity['document']['accountId'] except KeyError: log.error('Failed to get account id from instance_identity in' ' boto_iam.get_account_id.') __context__[cache_key] = account_id return __context__[cache_key] def get_all_roles(path_prefix=None, region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM role details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_roles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _roles = conn.list_roles(path_prefix=path_prefix) roles = _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) while marker: _roles = conn.list_roles(path_prefix=path_prefix, marker=marker) roles = roles + _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) return roles def get_all_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM user details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_users ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _users = conn.get_all_users(path_prefix=path_prefix) users = _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) while marker: _users = conn.get_all_users(path_prefix=path_prefix, marker=marker) users = users + _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) return users def get_all_user_policies(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all user policies. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_user_policies myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_all_user_policies(user_name, marker, max_items) if not info: return False _list = info.list_user_policies_response.list_user_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policies for user %s.', user_name) return False def get_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user_policy myuser mypolicyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user_policy(user_name, policy_name) log.debug('Info for IAM user %s policy %s: %s.', user_name, policy_name, info) if not info: return False info = info.get_user_policy_response.get_user_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policy %s for IAM user %s.', policy_name, user_name) return False def put_user_policy(user_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_user_policy myuser policyname policyrules ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_user_policy(user_name, policy_name, policy_json) if created: log.info('Created policy %s for IAM user %s.', policy_name, user_name) return True log.error('Could not create policy %s for IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy %s for IAM user %s.', policy_name, user_name) return False def delete_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user_policy myuser mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_user_policy( user_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_user_policy(user_name, policy_name) log.info('Successfully deleted policy %s for IAM user %s.', policy_name, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM user %s.', policy_name, user_name) return False def upload_server_cert(cert_name, cert_body, private_key, cert_chain=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Upload a certificate to Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.upload_server_cert mycert_name crt priv_key :param cert_name: The name for the server certificate. Do not include the path in this value. :param cert_body: The contents of the public key certificate in PEM-encoded format. :param private_key: The contents of the private key in PEM-encoded format. :param cert_chain: The contents of the certificate chain. This is typically a concatenation of the PEM-encoded public key certificates of the chain. :param path: The path for the server certificate. :param region: The name of the region to connect to. :param key: The key to be used in order to connect :param keyid: The keyid to be used in order to connect :param profile: The profile that contains a dict of region, key, keyid :return: True / False ''' exists = get_server_certificate(cert_name, region, key, keyid, profile) if exists: return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.upload_server_cert(cert_name, cert_body, private_key, cert_chain) log.info('Created certificate %s.', cert_name) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to failed to create certificate %s.', cert_name) return False def list_server_certificates(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Lists the server certificates stored in IAM that have the specified path prefix. .. versionadded:: ??? :param path_prefix: The path prefix for filtering the results. For example: /company/servercerts would get all server certificates for which the path starts with /company/servercerts . This parameter is optional. If it is not included, it defaults to a slash (/), listing all server certificates. This parameter allows (per its regex pattern) a string of characters consisting of either a forward slash (/) by itself or a string that must begin and end with forward slashes. In addition, it can contain any ASCII character from the ! (u0021) through the DEL character (u007F), including most punctuation characters, digits, and upper and lowercased letters. CLI Example: .. code-block:: bash salt myminion boto_iam.list_server_certificates path_prefix=/somepath/ ''' retries = 10 sleep = 6 conn = __utils__['boto3.get_connection']('iam', region=region, key=key, keyid=keyid, profile=profile) Items = [] while retries: try: log.debug('Garnering list of IAM Server Certificates') IsTruncated = True while IsTruncated: kwargs = {'PathPrefix': path_prefix} ret = conn.list_server_certificates(**kwargs) Items += ret.get('ServerCertificateMetadataList', []) IsTruncated = ret.get('IsTruncated') kwargs.update({'Marker': ret.get('Marker')}) return Items except botocore.exceptions.ParamValidationError as err: raise SaltInvocationError(str(err)) except botocore.exceptions.ClientError as err: if retries and jmespath.search('Error.Code', err.response) == 'Throttling': retries -= 1 log.debug('Throttled by AWS API, retrying in %s seconds...', sleep) time.sleep(sleep) continue log.error('Failed to list IAM Server Certificates: %s', err.message) return None def get_server_certificate(cert_name, region=None, key=None, keyid=None, profile=None): ''' Returns certificate information from Amazon .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_server_certificate mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_server_certificate(cert_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get certificate %s information.', cert_name) return False def delete_server_cert(cert_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a certificate from Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_server_cert mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_server_cert(cert_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete certificate %s.', cert_name) return False def export_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM user details. Produces results that can be used to create an sls file. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.export_users --out=txt | sed "s/local: //" > iam_users.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() users = get_all_users(path_prefix, region, key, keyid, profile) for user in users: name = user.user_name _policies = conn.get_all_user_policies(name, max_items=100) _policies = _policies.list_user_policies_response.list_user_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_user_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_user_policy_response.get_user_policy_result.policy_document )) policies[policy_name] = _policy user_sls = [] user_sls.append({"name": name}) user_sls.append({"policies": policies}) user_sls.append({"path": user.path}) results["manage user " + name] = {"boto_iam.user_present": user_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def export_roles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM role details. Produces results that can be used to create an sls file. CLI Example: salt-call boto_iam.export_roles --out=txt | sed "s/local: //" > iam_roles.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() roles = get_all_roles(path_prefix, region, key, keyid, profile) for role in roles: name = role.role_name _policies = conn.list_role_policies(name, max_items=100) _policies = _policies.list_role_policies_response.list_role_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_role_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_role_policy_response.get_role_policy_result.policy_document )) policies[policy_name] = _policy role_sls = [] role_sls.append({"name": name}) role_sls.append({"policies": policies}) role_sls.append({'policy_document': salt.utils.json.loads(_unquote(role.assume_role_policy_document))}) role_sls.append({"path": role.path}) results["manage role " + name] = {"boto_iam_role.present": role_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def _get_policy_arn(name, region=None, key=None, keyid=None, profile=None): if name.startswith('arn:aws:iam:'): return name account_id = get_account_id( region=region, key=key, keyid=keyid, profile=profile ) return 'arn:aws:iam::{0}:policy/{1}'.format(account_id, name) def policy_exists(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return True except boto.exception.BotoServerError: return False def get_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return ret.get('get_policy_response', {}).get('get_policy_result', {}) except boto.exception.BotoServerError: return None def create_policy(policy_name, policy_document, path=None, description=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in 'path', 'description': if locals()[arg] is not None: params[arg] = locals()[arg] if policy_exists(policy_name, region, key, keyid, profile): return True try: conn.create_policy(policy_name, policy_document, **params) log.info('Created IAM policy %s.', policy_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s.', policy_name) return False return True def delete_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_exists(policy_arn, region, key, keyid, profile): return True try: conn.delete_policy(policy_arn) log.info('Deleted %s policy.', policy_name) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete %s policy: %s.', policy_name, aws.get('message')) return False return True def list_policies(region=None, key=None, keyid=None, profile=None): ''' List policies. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policies ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: policies = [] for ret in __utils__['boto.paged_call'](conn.list_policies): policies.append(ret.get('list_policies_response', {}).get('list_policies_result', {}).get('policies')) return policies except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to list policy versions.' log.error(msg) return [] def policy_version_exists(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.get_policy_version(policy_arn, version_id) return True except boto.exception.BotoServerError: return False def get_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy_version(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile), version_id) retval = ret.get('get_policy_version_response', {}).get('get_policy_version_result', {}).get('policy_version', {}) retval['document'] = _unquote(retval.get('document')) return {'policy_version': retval} except boto.exception.BotoServerError: return None def create_policy_version(policy_name, policy_document, set_as_default=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy version. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy_version mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in ('set_as_default',): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.create_policy_version(policy_arn, policy_document, **params) vid = ret.get('create_policy_version_response', {}).get('create_policy_version_result', {}).get('policy_version', {}).get('version_id') log.info('Created IAM policy %s version %s.', policy_name, vid) return {'created': True, 'version_id': vid} except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s version %s.', policy_name, vid) return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Delete a policy version. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_version_exists(policy_arn, version_id, region, key, keyid, profile): return True try: conn.delete_policy_version(policy_arn, version_id) log.info('Deleted IAM policy %s version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete IAM policy %s version %s: %s', policy_name, version_id, aws.get('message')) return False return True def list_policy_versions(policy_name, region=None, key=None, keyid=None, profile=None): ''' List versions of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policy_versions mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.list_policy_versions(policy_arn) return ret.get('list_policy_versions_response', {}).get('list_policy_versions_result', {}).get('versions') except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list versions for IAM policy %s.', policy_name) return [] def set_default_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Set the default version of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.set_default_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.set_default_policy_version(policy_arn, version_id) log.info('Set %s policy to version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to set %s policy to version %s: %s', policy_name, version_id, aws.get('message')) return False return True def attach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_user_policy(policy_arn, user_name) log.info('Attached policy %s to IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach %s policy to IAM user %s.', policy_name, user_name) return False return True def detach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_user_policy(policy_arn, user_name) log.info('Detached %s policy from IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach %s policy from IAM user %s.', policy_name, user_name) return False return True def attach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_group_policy(policy_arn, group_name) log.info('Attached policy %s to IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM group %s.', policy_name, group_name) return False return True def detach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_group_policy(policy_arn, group_name) log.info('Detached policy %s from IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM group %s.', policy_name, group_name) return False return True def attach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_role_policy(policy_arn, role_name) log.info('Attached policy %s to IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM role %s.', policy_name, role_name) return False return True def detach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_role_policy(policy_arn, role_name) log.info('Detached policy %s from IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM role %s.', policy_name, role_name) return False return True def list_entities_for_policy(policy_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities that a policy is attached to. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 params = {} for arg in ('path_prefix', 'entity_filter'): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) while retries: try: allret = { 'policy_groups': [], 'policy_users': [], 'policy_roles': [], } for ret in __utils__['boto.paged_call'](conn.list_entities_for_policy, policy_arn=policy_arn, **params): for k, v in six.iteritems(allret): v.extend(ret.get('list_entities_for_policy_response', {}).get('list_entities_for_policy_result', {}).get(k)) return allret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('Failed to list entities for IAM policy %s: %s', policy_name, e.message) return {} return {} def list_attached_user_policies(user_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given user. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'UserName': user_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedUserPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_user_policies_response', {}).get('list_attached_user_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM user %s.', user_name) return [] def list_attached_group_policies(group_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given group. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'GroupName': group_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedGroupPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_group_policies_response', {}).get('list_attached_group_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM group %s.', group_name) return [] def list_attached_role_policies(role_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'RoleName': role_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedRolePolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_role_policies_response', {}).get('list_attached_role_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM role %s.', role_name) return [] def create_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Create SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.create_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_saml_provider(saml_metadata_document, name) log.info('Successfully created %s SAML provider.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to create SAML provider %s.', name) return False def get_saml_provider_arn(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider_arn my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_saml_providers() for saml_provider in response.list_saml_providers_response.list_saml_providers_result.saml_provider_list: if saml_provider['arn'].endswith(':saml-provider/' + name): return saml_provider['arn'] return False except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to get ARN of SAML provider %s.', name) return False def delete_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Delete SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.delete_saml_provider my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return True conn.delete_saml_provider(saml_provider_arn) log.info('Successfully deleted SAML provider %s.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete SAML provider %s.', name) return False def list_saml_providers(region=None, key=None, keyid=None, profile=None): ''' List SAML providers. CLI Example: .. code-block:: bash salt myminion boto_iam.list_saml_providers ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: providers = [] info = conn.list_saml_providers() for arn in info['list_saml_providers_response']['list_saml_providers_result']['saml_provider_list']: providers.append(arn['arn'].rsplit('/', 1)[1]) return providers except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get list of SAML providers.') return False def get_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider document. CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider arn ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: provider = conn.get_saml_provider(name) return provider['get_saml_provider_response']['get_saml_provider_result']['saml_metadata_document'] except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get SAML provider document %s.', name) return False def update_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Update SAML provider. CLI Example: .. code-block:: bash salt myminion boto_iam.update_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return False if conn.update_saml_provider(name, saml_metadata_document): return True return False except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to update SAML provider %s.', name) return False
saltstack/salt
salt/modules/boto_iam.py
get_group_policy
python
def get_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group_policy mygroup policyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group_policy(group_name, policy_name) log.debug('info for group policy is : %s', info) if not info: return False info = info.get_group_policy_response.get_group_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False
Retrieves the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group_policy mygroup policyname
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iam.py#L596-L622
[ "def loads(s, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.loads and prevents a traceback in the event that a bytestring is\n passed to the function. (Python < 3.6 cannot load bytestrings)\n\n You can pass an alternate json module (loaded via import_json() above)\n using the _json_module argument)\n '''\n json_module = kwargs.pop('_json_module', json)\n try:\n return json_module.loads(s, **kwargs)\n except TypeError as exc:\n # json.loads cannot load bytestrings in Python < 3.6\n if six.PY3 and isinstance(s, bytes):\n return json_module.loads(salt.utils.stringutils.to_unicode(s), **kwargs)\n else:\n raise exc\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon IAM .. versionadded:: 2014.7.0 :configuration: This module accepts explicit iam 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 iam.keyid: GKTADJGHEIQSXMKKRBJ08H iam.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs iam.region: 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: boto ''' # keep lint from choking on _get_conn and _cache_id #pylint: disable=E0602 # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import salt libs from salt.ext import six import salt.utils.compat import salt.utils.json import salt.utils.odict as odict import salt.utils.versions from salt.exceptions import SaltInvocationError # Import third party libs # pylint: disable=unused-import from salt.ext.six.moves.urllib.parse import unquote as _unquote # pylint: disable=no-name-in-module try: import boto import boto.iam import boto3 import botocore logging.getLogger('boto').setLevel(logging.CRITICAL) logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=unused-import log = logging.getLogger(__name__) def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'iam', pack=__salt__) def instance_profile_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an instance profile exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: # Boto weirdly returns an exception here if an instance profile doesn't # exist. conn.get_instance_profile(name) return True except boto.exception.BotoServerError: return False def create_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Create an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.create_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if instance_profile_exists(name, region, key, keyid, profile): return True try: # This call returns an instance profile if successful and an exception # if not. It's annoying. conn.create_instance_profile(name) log.info('Created %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create %s instance profile.', name) return False return True def delete_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Delete an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not instance_profile_exists(name, region, key, keyid, profile): return True try: conn.delete_instance_profile(name) log.info('Deleted %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s instance profile.', name) return False return True def role_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an IAM role exists. CLI Example: .. code-block:: bash salt myminion boto_iam.role_exists myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_role(name) return True except boto.exception.BotoServerError: return False def describe_role(name, region=None, key=None, keyid=None, profile=None): ''' Get information for a role. CLI Example: .. code-block:: bash salt myminion boto_iam.describe_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_role(name) if not info: return False role = info.get_role_response.get_role_result.role role['assume_role_policy_document'] = salt.utils.json.loads(_unquote( role.assume_role_policy_document )) # If Sid wasn't defined by the user, boto will still return a Sid in # each policy. To properly check idempotently, let's remove the Sid # from the return if it's not actually set. for policy_key, policy in role['assume_role_policy_document'].items(): if policy_key == 'Statement': for val in policy: if 'Sid' in val and not val['Sid']: del val['Sid'] return role except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get %s information.', name) return False def create_user(user_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_user myuser ''' if not path: path = '/' if get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_user(user_name, path) log.info('Created IAM user : %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM user %s.', user_name) return False def get_all_access_keys(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all access keys from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_access_keys myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.get_all_access_keys(user_name, marker, max_items) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get access keys for IAM user %s.', user_name) return six.text_type(e) def create_access_key(user_name, region=None, key=None, keyid=None, profile=None): ''' Create access key id for a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.create_access_key(user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create access key.') return six.text_type(e) def delete_access_key(access_key_id, user_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete access key id from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_access_key(access_key_id, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete access key id %s.', access_key_id) return six.text_type(e) def delete_user(user_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user myuser ''' if not get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.delete_user(user_name) log.info('Deleted IAM user : %s .', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM user %s', user_name) return six.text_type(e) def get_user(user_name=None, region=None, key=None, keyid=None, profile=None): ''' Get user information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user(user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM user %s info.', user_name) return False def create_group(group_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_group group ''' if not path: path = '/' if get_group(group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_group(group_name, path) log.info('Created IAM group : %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM group %s.', group_name) return False def get_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group(group_name, max_items=1) if not info: return False return info['get_group_response']['get_group_result']['group'] except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_group_members(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: marker = None truncated = True users = [] while truncated: info = conn.get_group(group_name, marker=marker, max_items=1000) if not info: return False truncated = bool(info['get_group_response']['get_group_result']['is_truncated']) if truncated and 'marker' in info['get_group_response']['get_group_result']: marker = info['get_group_response']['get_group_result']['marker'] else: marker = None truncated = False users += info['get_group_response']['get_group_result']['users'] return users except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get members for IAM group %s.', group_name) return False def add_user_to_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Add user to group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.add_user_to_group myuser mygroup ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('Username : %s does not exist.', user_name) return False if user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.add_user_to_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add IAM user %s to group %s.', user_name, group_name) return False def user_exists_in_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Check if user exists in group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.user_exists_in_group myuser mygroup ''' # TODO this should probably use boto.iam.get_groups_for_user users = get_group_members( group_name=group_name, region=region, key=key, keyid=keyid, profile=profile ) if users: for _user in users: if user_name == _user['user_name']: log.debug('IAM user %s is already in IAM group %s.', user_name, group_name) return True return False def remove_user_from_group(group_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Remove user from group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.remove_user_from_group mygroup myuser ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist.', user_name) return False if not user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.remove_user_from_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove IAM user %s from group %s', user_name, group_name) return False def put_group_policy(group_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_group_policy mygroup policyname policyrules ''' group = get_group(group_name, region=region, key=key, keyid=keyid, profile=profile) if not group: log.error('Group %s does not exist', group_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_group_policy(group_name, policy_name, policy_json) if created: log.info('Created policy for IAM group %s.', group_name) return True log.error('Could not create policy for IAM group %s', group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy for IAM group %s', group_name) return False def delete_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group_policy mygroup mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_group_policy( group_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_group_policy(group_name, policy_name) log.info('Successfully deleted policy %s for IAM group %s.', policy_name, group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM group %s.', policy_name, group_name) return False def get_all_groups(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM group details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_groups ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _groups = conn.get_all_groups(path_prefix=path_prefix) groups = _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) while marker: _groups = conn.get_all_groups(path_prefix=path_prefix, marker=marker) groups = groups + _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) return groups def get_all_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.get_all_instance_profiles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) marker = False profiles = [] while marker is not None: marker = marker if marker else None p = conn.list_instance_profiles(path_prefix=path_prefix, marker=marker) res = p.list_instance_profiles_response.list_instance_profiles_result profiles += res.instance_profiles marker = getattr(res, 'marker', None) return profiles def list_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' List all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.list_instance_profiles ''' p = get_all_instance_profiles(path_prefix, region, key, keyid, profile) return [i['instance_profile_name'] for i in p] def get_all_group_policies(group_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a group. CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_group_policies mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False try: response = conn.get_all_group_policies(group_name) _list = response.list_group_policies_response.list_group_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def delete_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _group = get_group( group_name, region, key, keyid, profile ) if not _group: return True try: conn.delete_group(group_name) log.info('Successfully deleted IAM group %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM group %s.', group_name) return False def create_login_profile(user_name, password, region=None, key=None, keyid=None, profile=None): ''' Creates a login profile for the specified user, give the user the ability to access AWS services and the AWS Management Console. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_login_profile user_name password ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.create_login_profile(user_name, password) log.info('Created profile for IAM user %s.', user_name) return info except boto.exception.BotoServerError as e: log.debug(e) if 'Conflict' in e: log.info('Profile already exists for IAM user %s.', user_name) return 'Conflict' log.error('Failed to update profile for IAM user %s.', user_name) return False def delete_login_profile(user_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a login profile for the specified user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_login_profile user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.delete_login_profile(user_name) log.info('Deleted login profile for IAM user %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Login profile already deleted for IAM user %s.', user_name) return True log.error('Failed to delete login profile for IAM user %s.', user_name) return False def get_all_mfa_devices(user_name, region=None, key=None, keyid=None, profile=None): ''' Get all MFA devices associated with an IAM user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_mfa_devices user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: result = conn.get_all_mfa_devices(user_name) devices = result['list_mfa_devices_response']['list_mfa_devices_result']['mfa_devices'] return devices except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Could not find IAM user %s.', user_name) return [] log.error('Failed to get all MFA devices for IAM user %s.', user_name) return False def deactivate_mfa_device(user_name, serial, region=None, key=None, keyid=None, profile=None): ''' Deactivates the specified MFA device and removes it from association with the user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.deactivate_mfa_device user_name serial_num ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.deactivate_mfa_device(user_name, serial) log.info('Deactivated MFA device %s for IAM user %s.', serial, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('MFA device %s not associated with IAM user %s.', serial, user_name) return True log.error('Failed to deactivate MFA device %s for IAM user %s.', serial, user_name) return False def delete_virtual_mfa_device(serial, region=None, key=None, keyid=None, profile=None): ''' Deletes the specified virtual MFA device. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_virtual_mfa_device serial_num ''' conn = __utils__['boto3.get_connection_func']('iam')() try: conn.delete_virtual_mfa_device(SerialNumber=serial) log.info('Deleted virtual MFA device %s.', serial) return True except botocore.exceptions.ClientError as e: log.debug(e) if 'NoSuchEntity' in six.text_type(e): log.info('Virtual MFA device %s not found.', serial) return True log.error('Failed to delete virtual MFA device %s.', serial) return False def update_account_password_policy(allow_users_to_change_password=None, hard_expiry=None, max_password_age=None, minimum_password_length=None, password_reuse_prevention=None, require_lowercase_characters=None, require_numbers=None, require_symbols=None, require_uppercase_characters=None, region=None, key=None, keyid=None, profile=None): ''' Update the password policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_account_password_policy True ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.update_account_password_policy(allow_users_to_change_password, hard_expiry, max_password_age, minimum_password_length, password_reuse_prevention, require_lowercase_characters, require_numbers, require_symbols, require_uppercase_characters) log.info('The password policy has been updated.') return True except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy' log.error(msg) return False def get_account_policy(region=None, key=None, keyid=None, profile=None): ''' Get account policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_account_password_policy() return info.get_account_password_policy_response.get_account_password_policy_result.password_policy except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy.' log.error(msg) return False def create_role(name, policy_document=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Create an instance role. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if role_exists(name, region, key, keyid, profile): return True if not policy_document: policy_document = None try: conn.create_role(name, assume_role_policy_document=policy_document, path=path) log.info('Created IAM role %s.', name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to create IAM role %s.', name) return False def delete_role(name, region=None, key=None, keyid=None, profile=None): ''' Delete an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(name, region, key, keyid, profile): return True try: conn.delete_role(name) log.info('Deleted %s IAM role.', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s IAM role.', name) return False def profile_associated(role_name, profile_name, region, key, keyid, profile): ''' Check to see if an instance profile is associated with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.profile_associated myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # The IAM module of boto doesn't return objects. Instead you need to grab # values through its properties. Sigh. try: profiles = conn.list_instance_profiles_for_role(role_name) except boto.exception.BotoServerError as e: log.debug(e) return False profiles = profiles.list_instance_profiles_for_role_response profiles = profiles.list_instance_profiles_for_role_result profiles = profiles.instance_profiles for profile in profiles: if profile.instance_profile_name == profile_name: return True return False def associate_profile_to_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Associate an instance profile with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.associate_profile_to_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if associated: return True else: try: conn.add_role_to_instance_profile(profile_name, role_name) log.info('Added %s instance profile to IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add %s instance profile to IAM role %s', profile_name, role_name) return False def disassociate_profile_from_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Disassociate an instance profile from an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.disassociate_profile_from_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if not associated: return True else: try: conn.remove_role_from_instance_profile(profile_name, role_name) log.info('Removed %s instance profile from IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove %s instance profile from IAM role %s.', profile_name, role_name) return False def list_role_policies(role_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_role_policies myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_role_policies(role_name) _list = response.list_role_policies_response.list_role_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def get_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.get_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: _policy = conn.get_role_policy(role_name, policy_name) # I _hate_ you for not giving me an object boto. _policy = _policy.get_role_policy_response.policy_document # Policy is url encoded _policy = _unquote(_policy) _policy = salt.utils.json.loads(_policy, object_pairs_hook=odict.OrderedDict) return _policy except boto.exception.BotoServerError: return {} def create_role_policy(role_name, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Create or modify a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role_policy myirole mypolicy '{"MyPolicy": "Statement": [{"Action": ["sqs:*"], "Effect": "Allow", "Resource": ["arn:aws:sqs:*:*:*"], "Sid": "MyPolicySqs1"}]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) mode = 'create' if _policy: if _policy == policy: return True mode = 'modify' if isinstance(policy, six.string_types): policy = salt.utils.json.loads(policy, object_pairs_hook=odict.OrderedDict) try: _policy = salt.utils.json.dumps(policy) conn.put_role_policy(role_name, policy_name, _policy) if mode == 'create': msg = 'Successfully added policy %s to IAM role %s.' else: msg = 'Successfully modified policy %s for IAM role %s.' log.info(msg, policy_name, role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to %s policy %s for IAM role %s.', mode, policy_name, role_name) return False def delete_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) if not _policy: return True try: conn.delete_role_policy(role_name, policy_name) log.info('Successfully deleted policy %s for IAM role %s.', policy_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM role %s.', policy_name, role_name) return False def update_assume_role_policy(role_name, policy_document, region=None, key=None, keyid=None, profile=None): ''' Update an assume role policy for a role. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_assume_role_policy myrole '{"Statement":"..."}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(policy_document, six.string_types): policy_document = salt.utils.json.loads(policy_document, object_pairs_hook=odict.OrderedDict) try: _policy_document = salt.utils.json.dumps(policy_document) conn.update_assume_role_policy(role_name, _policy_document) log.info('Successfully updated assume role policy for IAM role %s.', role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to update assume role policy for IAM role %s.', role_name) return False def build_policy(region=None, key=None, keyid=None, profile=None): ''' Build a default assume role policy. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.build_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if hasattr(conn, 'build_policy'): policy = salt.utils.json.loads(conn.build_policy()) elif hasattr(conn, '_build_policy'): policy = salt.utils.json.loads(conn._build_policy()) else: return {} # The format we get from build_policy isn't going to be what we get back # from AWS for the exact same policy. AWS converts single item list values # into strings, so let's do the same here. for key, policy_val in policy.items(): for statement in policy_val: if (isinstance(statement['Action'], list) and len(statement['Action']) == 1): statement['Action'] = statement['Action'][0] if (isinstance(statement['Principal']['Service'], list) and len(statement['Principal']['Service']) == 1): statement['Principal']['Service'] = statement['Principal']['Service'][0] # build_policy doesn't add a version field, which AWS is going to set to a # default value, when we get it back, so let's set it. policy['Version'] = '2008-10-17' return policy def get_account_id(region=None, key=None, keyid=None, profile=None): ''' Get a the AWS account id associated with the used credentials. CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_id ''' cache_key = 'boto_iam.account_id' if cache_key not in __context__: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_user() # The get_user call returns an user ARN: # arn:aws:iam::027050522557:user/salt-test arn = ret['get_user_response']['get_user_result']['user']['arn'] account_id = arn.split(':')[4] except boto.exception.BotoServerError: # If call failed, then let's try to get the ARN from the metadata timeout = boto.config.getfloat( 'Boto', 'metadata_service_timeout', 1.0 ) attempts = boto.config.getint( 'Boto', 'metadata_service_num_attempts', 1 ) identity = boto.utils.get_instance_identity( timeout=timeout, num_retries=attempts ) try: account_id = identity['document']['accountId'] except KeyError: log.error('Failed to get account id from instance_identity in' ' boto_iam.get_account_id.') __context__[cache_key] = account_id return __context__[cache_key] def get_all_roles(path_prefix=None, region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM role details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_roles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _roles = conn.list_roles(path_prefix=path_prefix) roles = _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) while marker: _roles = conn.list_roles(path_prefix=path_prefix, marker=marker) roles = roles + _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) return roles def get_all_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM user details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_users ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _users = conn.get_all_users(path_prefix=path_prefix) users = _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) while marker: _users = conn.get_all_users(path_prefix=path_prefix, marker=marker) users = users + _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) return users def get_all_user_policies(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all user policies. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_user_policies myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_all_user_policies(user_name, marker, max_items) if not info: return False _list = info.list_user_policies_response.list_user_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policies for user %s.', user_name) return False def get_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user_policy myuser mypolicyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user_policy(user_name, policy_name) log.debug('Info for IAM user %s policy %s: %s.', user_name, policy_name, info) if not info: return False info = info.get_user_policy_response.get_user_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policy %s for IAM user %s.', policy_name, user_name) return False def put_user_policy(user_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_user_policy myuser policyname policyrules ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_user_policy(user_name, policy_name, policy_json) if created: log.info('Created policy %s for IAM user %s.', policy_name, user_name) return True log.error('Could not create policy %s for IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy %s for IAM user %s.', policy_name, user_name) return False def delete_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user_policy myuser mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_user_policy( user_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_user_policy(user_name, policy_name) log.info('Successfully deleted policy %s for IAM user %s.', policy_name, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM user %s.', policy_name, user_name) return False def upload_server_cert(cert_name, cert_body, private_key, cert_chain=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Upload a certificate to Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.upload_server_cert mycert_name crt priv_key :param cert_name: The name for the server certificate. Do not include the path in this value. :param cert_body: The contents of the public key certificate in PEM-encoded format. :param private_key: The contents of the private key in PEM-encoded format. :param cert_chain: The contents of the certificate chain. This is typically a concatenation of the PEM-encoded public key certificates of the chain. :param path: The path for the server certificate. :param region: The name of the region to connect to. :param key: The key to be used in order to connect :param keyid: The keyid to be used in order to connect :param profile: The profile that contains a dict of region, key, keyid :return: True / False ''' exists = get_server_certificate(cert_name, region, key, keyid, profile) if exists: return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.upload_server_cert(cert_name, cert_body, private_key, cert_chain) log.info('Created certificate %s.', cert_name) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to failed to create certificate %s.', cert_name) return False def list_server_certificates(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Lists the server certificates stored in IAM that have the specified path prefix. .. versionadded:: ??? :param path_prefix: The path prefix for filtering the results. For example: /company/servercerts would get all server certificates for which the path starts with /company/servercerts . This parameter is optional. If it is not included, it defaults to a slash (/), listing all server certificates. This parameter allows (per its regex pattern) a string of characters consisting of either a forward slash (/) by itself or a string that must begin and end with forward slashes. In addition, it can contain any ASCII character from the ! (u0021) through the DEL character (u007F), including most punctuation characters, digits, and upper and lowercased letters. CLI Example: .. code-block:: bash salt myminion boto_iam.list_server_certificates path_prefix=/somepath/ ''' retries = 10 sleep = 6 conn = __utils__['boto3.get_connection']('iam', region=region, key=key, keyid=keyid, profile=profile) Items = [] while retries: try: log.debug('Garnering list of IAM Server Certificates') IsTruncated = True while IsTruncated: kwargs = {'PathPrefix': path_prefix} ret = conn.list_server_certificates(**kwargs) Items += ret.get('ServerCertificateMetadataList', []) IsTruncated = ret.get('IsTruncated') kwargs.update({'Marker': ret.get('Marker')}) return Items except botocore.exceptions.ParamValidationError as err: raise SaltInvocationError(str(err)) except botocore.exceptions.ClientError as err: if retries and jmespath.search('Error.Code', err.response) == 'Throttling': retries -= 1 log.debug('Throttled by AWS API, retrying in %s seconds...', sleep) time.sleep(sleep) continue log.error('Failed to list IAM Server Certificates: %s', err.message) return None def get_server_certificate(cert_name, region=None, key=None, keyid=None, profile=None): ''' Returns certificate information from Amazon .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_server_certificate mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_server_certificate(cert_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get certificate %s information.', cert_name) return False def delete_server_cert(cert_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a certificate from Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_server_cert mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_server_cert(cert_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete certificate %s.', cert_name) return False def export_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM user details. Produces results that can be used to create an sls file. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.export_users --out=txt | sed "s/local: //" > iam_users.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() users = get_all_users(path_prefix, region, key, keyid, profile) for user in users: name = user.user_name _policies = conn.get_all_user_policies(name, max_items=100) _policies = _policies.list_user_policies_response.list_user_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_user_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_user_policy_response.get_user_policy_result.policy_document )) policies[policy_name] = _policy user_sls = [] user_sls.append({"name": name}) user_sls.append({"policies": policies}) user_sls.append({"path": user.path}) results["manage user " + name] = {"boto_iam.user_present": user_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def export_roles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM role details. Produces results that can be used to create an sls file. CLI Example: salt-call boto_iam.export_roles --out=txt | sed "s/local: //" > iam_roles.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() roles = get_all_roles(path_prefix, region, key, keyid, profile) for role in roles: name = role.role_name _policies = conn.list_role_policies(name, max_items=100) _policies = _policies.list_role_policies_response.list_role_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_role_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_role_policy_response.get_role_policy_result.policy_document )) policies[policy_name] = _policy role_sls = [] role_sls.append({"name": name}) role_sls.append({"policies": policies}) role_sls.append({'policy_document': salt.utils.json.loads(_unquote(role.assume_role_policy_document))}) role_sls.append({"path": role.path}) results["manage role " + name] = {"boto_iam_role.present": role_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def _get_policy_arn(name, region=None, key=None, keyid=None, profile=None): if name.startswith('arn:aws:iam:'): return name account_id = get_account_id( region=region, key=key, keyid=keyid, profile=profile ) return 'arn:aws:iam::{0}:policy/{1}'.format(account_id, name) def policy_exists(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return True except boto.exception.BotoServerError: return False def get_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return ret.get('get_policy_response', {}).get('get_policy_result', {}) except boto.exception.BotoServerError: return None def create_policy(policy_name, policy_document, path=None, description=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in 'path', 'description': if locals()[arg] is not None: params[arg] = locals()[arg] if policy_exists(policy_name, region, key, keyid, profile): return True try: conn.create_policy(policy_name, policy_document, **params) log.info('Created IAM policy %s.', policy_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s.', policy_name) return False return True def delete_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_exists(policy_arn, region, key, keyid, profile): return True try: conn.delete_policy(policy_arn) log.info('Deleted %s policy.', policy_name) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete %s policy: %s.', policy_name, aws.get('message')) return False return True def list_policies(region=None, key=None, keyid=None, profile=None): ''' List policies. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policies ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: policies = [] for ret in __utils__['boto.paged_call'](conn.list_policies): policies.append(ret.get('list_policies_response', {}).get('list_policies_result', {}).get('policies')) return policies except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to list policy versions.' log.error(msg) return [] def policy_version_exists(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.get_policy_version(policy_arn, version_id) return True except boto.exception.BotoServerError: return False def get_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy_version(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile), version_id) retval = ret.get('get_policy_version_response', {}).get('get_policy_version_result', {}).get('policy_version', {}) retval['document'] = _unquote(retval.get('document')) return {'policy_version': retval} except boto.exception.BotoServerError: return None def create_policy_version(policy_name, policy_document, set_as_default=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy version. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy_version mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in ('set_as_default',): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.create_policy_version(policy_arn, policy_document, **params) vid = ret.get('create_policy_version_response', {}).get('create_policy_version_result', {}).get('policy_version', {}).get('version_id') log.info('Created IAM policy %s version %s.', policy_name, vid) return {'created': True, 'version_id': vid} except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s version %s.', policy_name, vid) return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Delete a policy version. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_version_exists(policy_arn, version_id, region, key, keyid, profile): return True try: conn.delete_policy_version(policy_arn, version_id) log.info('Deleted IAM policy %s version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete IAM policy %s version %s: %s', policy_name, version_id, aws.get('message')) return False return True def list_policy_versions(policy_name, region=None, key=None, keyid=None, profile=None): ''' List versions of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policy_versions mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.list_policy_versions(policy_arn) return ret.get('list_policy_versions_response', {}).get('list_policy_versions_result', {}).get('versions') except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list versions for IAM policy %s.', policy_name) return [] def set_default_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Set the default version of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.set_default_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.set_default_policy_version(policy_arn, version_id) log.info('Set %s policy to version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to set %s policy to version %s: %s', policy_name, version_id, aws.get('message')) return False return True def attach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_user_policy(policy_arn, user_name) log.info('Attached policy %s to IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach %s policy to IAM user %s.', policy_name, user_name) return False return True def detach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_user_policy(policy_arn, user_name) log.info('Detached %s policy from IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach %s policy from IAM user %s.', policy_name, user_name) return False return True def attach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_group_policy(policy_arn, group_name) log.info('Attached policy %s to IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM group %s.', policy_name, group_name) return False return True def detach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_group_policy(policy_arn, group_name) log.info('Detached policy %s from IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM group %s.', policy_name, group_name) return False return True def attach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_role_policy(policy_arn, role_name) log.info('Attached policy %s to IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM role %s.', policy_name, role_name) return False return True def detach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_role_policy(policy_arn, role_name) log.info('Detached policy %s from IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM role %s.', policy_name, role_name) return False return True def list_entities_for_policy(policy_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities that a policy is attached to. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 params = {} for arg in ('path_prefix', 'entity_filter'): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) while retries: try: allret = { 'policy_groups': [], 'policy_users': [], 'policy_roles': [], } for ret in __utils__['boto.paged_call'](conn.list_entities_for_policy, policy_arn=policy_arn, **params): for k, v in six.iteritems(allret): v.extend(ret.get('list_entities_for_policy_response', {}).get('list_entities_for_policy_result', {}).get(k)) return allret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('Failed to list entities for IAM policy %s: %s', policy_name, e.message) return {} return {} def list_attached_user_policies(user_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given user. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'UserName': user_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedUserPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_user_policies_response', {}).get('list_attached_user_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM user %s.', user_name) return [] def list_attached_group_policies(group_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given group. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'GroupName': group_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedGroupPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_group_policies_response', {}).get('list_attached_group_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM group %s.', group_name) return [] def list_attached_role_policies(role_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'RoleName': role_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedRolePolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_role_policies_response', {}).get('list_attached_role_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM role %s.', role_name) return [] def create_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Create SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.create_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_saml_provider(saml_metadata_document, name) log.info('Successfully created %s SAML provider.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to create SAML provider %s.', name) return False def get_saml_provider_arn(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider_arn my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_saml_providers() for saml_provider in response.list_saml_providers_response.list_saml_providers_result.saml_provider_list: if saml_provider['arn'].endswith(':saml-provider/' + name): return saml_provider['arn'] return False except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to get ARN of SAML provider %s.', name) return False def delete_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Delete SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.delete_saml_provider my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return True conn.delete_saml_provider(saml_provider_arn) log.info('Successfully deleted SAML provider %s.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete SAML provider %s.', name) return False def list_saml_providers(region=None, key=None, keyid=None, profile=None): ''' List SAML providers. CLI Example: .. code-block:: bash salt myminion boto_iam.list_saml_providers ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: providers = [] info = conn.list_saml_providers() for arn in info['list_saml_providers_response']['list_saml_providers_result']['saml_provider_list']: providers.append(arn['arn'].rsplit('/', 1)[1]) return providers except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get list of SAML providers.') return False def get_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider document. CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider arn ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: provider = conn.get_saml_provider(name) return provider['get_saml_provider_response']['get_saml_provider_result']['saml_metadata_document'] except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get SAML provider document %s.', name) return False def update_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Update SAML provider. CLI Example: .. code-block:: bash salt myminion boto_iam.update_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return False if conn.update_saml_provider(name, saml_metadata_document): return True return False except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to update SAML provider %s.', name) return False
saltstack/salt
salt/modules/boto_iam.py
get_all_groups
python
def get_all_groups(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM group details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_groups ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _groups = conn.get_all_groups(path_prefix=path_prefix) groups = _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) while marker: _groups = conn.get_all_groups(path_prefix=path_prefix, marker=marker) groups = groups + _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) return groups
Get and return all IAM group details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_groups
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iam.py#L625-L650
null
# -*- coding: utf-8 -*- ''' Connection module for Amazon IAM .. versionadded:: 2014.7.0 :configuration: This module accepts explicit iam 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 iam.keyid: GKTADJGHEIQSXMKKRBJ08H iam.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs iam.region: 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: boto ''' # keep lint from choking on _get_conn and _cache_id #pylint: disable=E0602 # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import salt libs from salt.ext import six import salt.utils.compat import salt.utils.json import salt.utils.odict as odict import salt.utils.versions from salt.exceptions import SaltInvocationError # Import third party libs # pylint: disable=unused-import from salt.ext.six.moves.urllib.parse import unquote as _unquote # pylint: disable=no-name-in-module try: import boto import boto.iam import boto3 import botocore logging.getLogger('boto').setLevel(logging.CRITICAL) logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=unused-import log = logging.getLogger(__name__) def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'iam', pack=__salt__) def instance_profile_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an instance profile exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: # Boto weirdly returns an exception here if an instance profile doesn't # exist. conn.get_instance_profile(name) return True except boto.exception.BotoServerError: return False def create_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Create an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.create_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if instance_profile_exists(name, region, key, keyid, profile): return True try: # This call returns an instance profile if successful and an exception # if not. It's annoying. conn.create_instance_profile(name) log.info('Created %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create %s instance profile.', name) return False return True def delete_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Delete an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not instance_profile_exists(name, region, key, keyid, profile): return True try: conn.delete_instance_profile(name) log.info('Deleted %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s instance profile.', name) return False return True def role_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an IAM role exists. CLI Example: .. code-block:: bash salt myminion boto_iam.role_exists myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_role(name) return True except boto.exception.BotoServerError: return False def describe_role(name, region=None, key=None, keyid=None, profile=None): ''' Get information for a role. CLI Example: .. code-block:: bash salt myminion boto_iam.describe_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_role(name) if not info: return False role = info.get_role_response.get_role_result.role role['assume_role_policy_document'] = salt.utils.json.loads(_unquote( role.assume_role_policy_document )) # If Sid wasn't defined by the user, boto will still return a Sid in # each policy. To properly check idempotently, let's remove the Sid # from the return if it's not actually set. for policy_key, policy in role['assume_role_policy_document'].items(): if policy_key == 'Statement': for val in policy: if 'Sid' in val and not val['Sid']: del val['Sid'] return role except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get %s information.', name) return False def create_user(user_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_user myuser ''' if not path: path = '/' if get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_user(user_name, path) log.info('Created IAM user : %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM user %s.', user_name) return False def get_all_access_keys(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all access keys from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_access_keys myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.get_all_access_keys(user_name, marker, max_items) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get access keys for IAM user %s.', user_name) return six.text_type(e) def create_access_key(user_name, region=None, key=None, keyid=None, profile=None): ''' Create access key id for a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.create_access_key(user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create access key.') return six.text_type(e) def delete_access_key(access_key_id, user_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete access key id from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_access_key(access_key_id, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete access key id %s.', access_key_id) return six.text_type(e) def delete_user(user_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user myuser ''' if not get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.delete_user(user_name) log.info('Deleted IAM user : %s .', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM user %s', user_name) return six.text_type(e) def get_user(user_name=None, region=None, key=None, keyid=None, profile=None): ''' Get user information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user(user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM user %s info.', user_name) return False def create_group(group_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_group group ''' if not path: path = '/' if get_group(group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_group(group_name, path) log.info('Created IAM group : %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM group %s.', group_name) return False def get_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group(group_name, max_items=1) if not info: return False return info['get_group_response']['get_group_result']['group'] except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_group_members(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: marker = None truncated = True users = [] while truncated: info = conn.get_group(group_name, marker=marker, max_items=1000) if not info: return False truncated = bool(info['get_group_response']['get_group_result']['is_truncated']) if truncated and 'marker' in info['get_group_response']['get_group_result']: marker = info['get_group_response']['get_group_result']['marker'] else: marker = None truncated = False users += info['get_group_response']['get_group_result']['users'] return users except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get members for IAM group %s.', group_name) return False def add_user_to_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Add user to group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.add_user_to_group myuser mygroup ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('Username : %s does not exist.', user_name) return False if user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.add_user_to_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add IAM user %s to group %s.', user_name, group_name) return False def user_exists_in_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Check if user exists in group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.user_exists_in_group myuser mygroup ''' # TODO this should probably use boto.iam.get_groups_for_user users = get_group_members( group_name=group_name, region=region, key=key, keyid=keyid, profile=profile ) if users: for _user in users: if user_name == _user['user_name']: log.debug('IAM user %s is already in IAM group %s.', user_name, group_name) return True return False def remove_user_from_group(group_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Remove user from group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.remove_user_from_group mygroup myuser ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist.', user_name) return False if not user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.remove_user_from_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove IAM user %s from group %s', user_name, group_name) return False def put_group_policy(group_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_group_policy mygroup policyname policyrules ''' group = get_group(group_name, region=region, key=key, keyid=keyid, profile=profile) if not group: log.error('Group %s does not exist', group_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_group_policy(group_name, policy_name, policy_json) if created: log.info('Created policy for IAM group %s.', group_name) return True log.error('Could not create policy for IAM group %s', group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy for IAM group %s', group_name) return False def delete_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group_policy mygroup mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_group_policy( group_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_group_policy(group_name, policy_name) log.info('Successfully deleted policy %s for IAM group %s.', policy_name, group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM group %s.', policy_name, group_name) return False def get_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group_policy mygroup policyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group_policy(group_name, policy_name) log.debug('info for group policy is : %s', info) if not info: return False info = info.get_group_policy_response.get_group_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_all_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.get_all_instance_profiles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) marker = False profiles = [] while marker is not None: marker = marker if marker else None p = conn.list_instance_profiles(path_prefix=path_prefix, marker=marker) res = p.list_instance_profiles_response.list_instance_profiles_result profiles += res.instance_profiles marker = getattr(res, 'marker', None) return profiles def list_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' List all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.list_instance_profiles ''' p = get_all_instance_profiles(path_prefix, region, key, keyid, profile) return [i['instance_profile_name'] for i in p] def get_all_group_policies(group_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a group. CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_group_policies mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False try: response = conn.get_all_group_policies(group_name) _list = response.list_group_policies_response.list_group_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def delete_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _group = get_group( group_name, region, key, keyid, profile ) if not _group: return True try: conn.delete_group(group_name) log.info('Successfully deleted IAM group %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM group %s.', group_name) return False def create_login_profile(user_name, password, region=None, key=None, keyid=None, profile=None): ''' Creates a login profile for the specified user, give the user the ability to access AWS services and the AWS Management Console. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_login_profile user_name password ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.create_login_profile(user_name, password) log.info('Created profile for IAM user %s.', user_name) return info except boto.exception.BotoServerError as e: log.debug(e) if 'Conflict' in e: log.info('Profile already exists for IAM user %s.', user_name) return 'Conflict' log.error('Failed to update profile for IAM user %s.', user_name) return False def delete_login_profile(user_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a login profile for the specified user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_login_profile user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.delete_login_profile(user_name) log.info('Deleted login profile for IAM user %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Login profile already deleted for IAM user %s.', user_name) return True log.error('Failed to delete login profile for IAM user %s.', user_name) return False def get_all_mfa_devices(user_name, region=None, key=None, keyid=None, profile=None): ''' Get all MFA devices associated with an IAM user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_mfa_devices user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: result = conn.get_all_mfa_devices(user_name) devices = result['list_mfa_devices_response']['list_mfa_devices_result']['mfa_devices'] return devices except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Could not find IAM user %s.', user_name) return [] log.error('Failed to get all MFA devices for IAM user %s.', user_name) return False def deactivate_mfa_device(user_name, serial, region=None, key=None, keyid=None, profile=None): ''' Deactivates the specified MFA device and removes it from association with the user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.deactivate_mfa_device user_name serial_num ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.deactivate_mfa_device(user_name, serial) log.info('Deactivated MFA device %s for IAM user %s.', serial, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('MFA device %s not associated with IAM user %s.', serial, user_name) return True log.error('Failed to deactivate MFA device %s for IAM user %s.', serial, user_name) return False def delete_virtual_mfa_device(serial, region=None, key=None, keyid=None, profile=None): ''' Deletes the specified virtual MFA device. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_virtual_mfa_device serial_num ''' conn = __utils__['boto3.get_connection_func']('iam')() try: conn.delete_virtual_mfa_device(SerialNumber=serial) log.info('Deleted virtual MFA device %s.', serial) return True except botocore.exceptions.ClientError as e: log.debug(e) if 'NoSuchEntity' in six.text_type(e): log.info('Virtual MFA device %s not found.', serial) return True log.error('Failed to delete virtual MFA device %s.', serial) return False def update_account_password_policy(allow_users_to_change_password=None, hard_expiry=None, max_password_age=None, minimum_password_length=None, password_reuse_prevention=None, require_lowercase_characters=None, require_numbers=None, require_symbols=None, require_uppercase_characters=None, region=None, key=None, keyid=None, profile=None): ''' Update the password policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_account_password_policy True ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.update_account_password_policy(allow_users_to_change_password, hard_expiry, max_password_age, minimum_password_length, password_reuse_prevention, require_lowercase_characters, require_numbers, require_symbols, require_uppercase_characters) log.info('The password policy has been updated.') return True except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy' log.error(msg) return False def get_account_policy(region=None, key=None, keyid=None, profile=None): ''' Get account policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_account_password_policy() return info.get_account_password_policy_response.get_account_password_policy_result.password_policy except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy.' log.error(msg) return False def create_role(name, policy_document=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Create an instance role. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if role_exists(name, region, key, keyid, profile): return True if not policy_document: policy_document = None try: conn.create_role(name, assume_role_policy_document=policy_document, path=path) log.info('Created IAM role %s.', name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to create IAM role %s.', name) return False def delete_role(name, region=None, key=None, keyid=None, profile=None): ''' Delete an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(name, region, key, keyid, profile): return True try: conn.delete_role(name) log.info('Deleted %s IAM role.', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s IAM role.', name) return False def profile_associated(role_name, profile_name, region, key, keyid, profile): ''' Check to see if an instance profile is associated with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.profile_associated myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # The IAM module of boto doesn't return objects. Instead you need to grab # values through its properties. Sigh. try: profiles = conn.list_instance_profiles_for_role(role_name) except boto.exception.BotoServerError as e: log.debug(e) return False profiles = profiles.list_instance_profiles_for_role_response profiles = profiles.list_instance_profiles_for_role_result profiles = profiles.instance_profiles for profile in profiles: if profile.instance_profile_name == profile_name: return True return False def associate_profile_to_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Associate an instance profile with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.associate_profile_to_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if associated: return True else: try: conn.add_role_to_instance_profile(profile_name, role_name) log.info('Added %s instance profile to IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add %s instance profile to IAM role %s', profile_name, role_name) return False def disassociate_profile_from_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Disassociate an instance profile from an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.disassociate_profile_from_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if not associated: return True else: try: conn.remove_role_from_instance_profile(profile_name, role_name) log.info('Removed %s instance profile from IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove %s instance profile from IAM role %s.', profile_name, role_name) return False def list_role_policies(role_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_role_policies myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_role_policies(role_name) _list = response.list_role_policies_response.list_role_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def get_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.get_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: _policy = conn.get_role_policy(role_name, policy_name) # I _hate_ you for not giving me an object boto. _policy = _policy.get_role_policy_response.policy_document # Policy is url encoded _policy = _unquote(_policy) _policy = salt.utils.json.loads(_policy, object_pairs_hook=odict.OrderedDict) return _policy except boto.exception.BotoServerError: return {} def create_role_policy(role_name, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Create or modify a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role_policy myirole mypolicy '{"MyPolicy": "Statement": [{"Action": ["sqs:*"], "Effect": "Allow", "Resource": ["arn:aws:sqs:*:*:*"], "Sid": "MyPolicySqs1"}]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) mode = 'create' if _policy: if _policy == policy: return True mode = 'modify' if isinstance(policy, six.string_types): policy = salt.utils.json.loads(policy, object_pairs_hook=odict.OrderedDict) try: _policy = salt.utils.json.dumps(policy) conn.put_role_policy(role_name, policy_name, _policy) if mode == 'create': msg = 'Successfully added policy %s to IAM role %s.' else: msg = 'Successfully modified policy %s for IAM role %s.' log.info(msg, policy_name, role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to %s policy %s for IAM role %s.', mode, policy_name, role_name) return False def delete_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) if not _policy: return True try: conn.delete_role_policy(role_name, policy_name) log.info('Successfully deleted policy %s for IAM role %s.', policy_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM role %s.', policy_name, role_name) return False def update_assume_role_policy(role_name, policy_document, region=None, key=None, keyid=None, profile=None): ''' Update an assume role policy for a role. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_assume_role_policy myrole '{"Statement":"..."}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(policy_document, six.string_types): policy_document = salt.utils.json.loads(policy_document, object_pairs_hook=odict.OrderedDict) try: _policy_document = salt.utils.json.dumps(policy_document) conn.update_assume_role_policy(role_name, _policy_document) log.info('Successfully updated assume role policy for IAM role %s.', role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to update assume role policy for IAM role %s.', role_name) return False def build_policy(region=None, key=None, keyid=None, profile=None): ''' Build a default assume role policy. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.build_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if hasattr(conn, 'build_policy'): policy = salt.utils.json.loads(conn.build_policy()) elif hasattr(conn, '_build_policy'): policy = salt.utils.json.loads(conn._build_policy()) else: return {} # The format we get from build_policy isn't going to be what we get back # from AWS for the exact same policy. AWS converts single item list values # into strings, so let's do the same here. for key, policy_val in policy.items(): for statement in policy_val: if (isinstance(statement['Action'], list) and len(statement['Action']) == 1): statement['Action'] = statement['Action'][0] if (isinstance(statement['Principal']['Service'], list) and len(statement['Principal']['Service']) == 1): statement['Principal']['Service'] = statement['Principal']['Service'][0] # build_policy doesn't add a version field, which AWS is going to set to a # default value, when we get it back, so let's set it. policy['Version'] = '2008-10-17' return policy def get_account_id(region=None, key=None, keyid=None, profile=None): ''' Get a the AWS account id associated with the used credentials. CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_id ''' cache_key = 'boto_iam.account_id' if cache_key not in __context__: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_user() # The get_user call returns an user ARN: # arn:aws:iam::027050522557:user/salt-test arn = ret['get_user_response']['get_user_result']['user']['arn'] account_id = arn.split(':')[4] except boto.exception.BotoServerError: # If call failed, then let's try to get the ARN from the metadata timeout = boto.config.getfloat( 'Boto', 'metadata_service_timeout', 1.0 ) attempts = boto.config.getint( 'Boto', 'metadata_service_num_attempts', 1 ) identity = boto.utils.get_instance_identity( timeout=timeout, num_retries=attempts ) try: account_id = identity['document']['accountId'] except KeyError: log.error('Failed to get account id from instance_identity in' ' boto_iam.get_account_id.') __context__[cache_key] = account_id return __context__[cache_key] def get_all_roles(path_prefix=None, region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM role details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_roles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _roles = conn.list_roles(path_prefix=path_prefix) roles = _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) while marker: _roles = conn.list_roles(path_prefix=path_prefix, marker=marker) roles = roles + _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) return roles def get_all_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM user details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_users ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _users = conn.get_all_users(path_prefix=path_prefix) users = _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) while marker: _users = conn.get_all_users(path_prefix=path_prefix, marker=marker) users = users + _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) return users def get_all_user_policies(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all user policies. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_user_policies myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_all_user_policies(user_name, marker, max_items) if not info: return False _list = info.list_user_policies_response.list_user_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policies for user %s.', user_name) return False def get_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user_policy myuser mypolicyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user_policy(user_name, policy_name) log.debug('Info for IAM user %s policy %s: %s.', user_name, policy_name, info) if not info: return False info = info.get_user_policy_response.get_user_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policy %s for IAM user %s.', policy_name, user_name) return False def put_user_policy(user_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_user_policy myuser policyname policyrules ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_user_policy(user_name, policy_name, policy_json) if created: log.info('Created policy %s for IAM user %s.', policy_name, user_name) return True log.error('Could not create policy %s for IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy %s for IAM user %s.', policy_name, user_name) return False def delete_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user_policy myuser mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_user_policy( user_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_user_policy(user_name, policy_name) log.info('Successfully deleted policy %s for IAM user %s.', policy_name, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM user %s.', policy_name, user_name) return False def upload_server_cert(cert_name, cert_body, private_key, cert_chain=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Upload a certificate to Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.upload_server_cert mycert_name crt priv_key :param cert_name: The name for the server certificate. Do not include the path in this value. :param cert_body: The contents of the public key certificate in PEM-encoded format. :param private_key: The contents of the private key in PEM-encoded format. :param cert_chain: The contents of the certificate chain. This is typically a concatenation of the PEM-encoded public key certificates of the chain. :param path: The path for the server certificate. :param region: The name of the region to connect to. :param key: The key to be used in order to connect :param keyid: The keyid to be used in order to connect :param profile: The profile that contains a dict of region, key, keyid :return: True / False ''' exists = get_server_certificate(cert_name, region, key, keyid, profile) if exists: return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.upload_server_cert(cert_name, cert_body, private_key, cert_chain) log.info('Created certificate %s.', cert_name) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to failed to create certificate %s.', cert_name) return False def list_server_certificates(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Lists the server certificates stored in IAM that have the specified path prefix. .. versionadded:: ??? :param path_prefix: The path prefix for filtering the results. For example: /company/servercerts would get all server certificates for which the path starts with /company/servercerts . This parameter is optional. If it is not included, it defaults to a slash (/), listing all server certificates. This parameter allows (per its regex pattern) a string of characters consisting of either a forward slash (/) by itself or a string that must begin and end with forward slashes. In addition, it can contain any ASCII character from the ! (u0021) through the DEL character (u007F), including most punctuation characters, digits, and upper and lowercased letters. CLI Example: .. code-block:: bash salt myminion boto_iam.list_server_certificates path_prefix=/somepath/ ''' retries = 10 sleep = 6 conn = __utils__['boto3.get_connection']('iam', region=region, key=key, keyid=keyid, profile=profile) Items = [] while retries: try: log.debug('Garnering list of IAM Server Certificates') IsTruncated = True while IsTruncated: kwargs = {'PathPrefix': path_prefix} ret = conn.list_server_certificates(**kwargs) Items += ret.get('ServerCertificateMetadataList', []) IsTruncated = ret.get('IsTruncated') kwargs.update({'Marker': ret.get('Marker')}) return Items except botocore.exceptions.ParamValidationError as err: raise SaltInvocationError(str(err)) except botocore.exceptions.ClientError as err: if retries and jmespath.search('Error.Code', err.response) == 'Throttling': retries -= 1 log.debug('Throttled by AWS API, retrying in %s seconds...', sleep) time.sleep(sleep) continue log.error('Failed to list IAM Server Certificates: %s', err.message) return None def get_server_certificate(cert_name, region=None, key=None, keyid=None, profile=None): ''' Returns certificate information from Amazon .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_server_certificate mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_server_certificate(cert_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get certificate %s information.', cert_name) return False def delete_server_cert(cert_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a certificate from Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_server_cert mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_server_cert(cert_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete certificate %s.', cert_name) return False def export_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM user details. Produces results that can be used to create an sls file. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.export_users --out=txt | sed "s/local: //" > iam_users.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() users = get_all_users(path_prefix, region, key, keyid, profile) for user in users: name = user.user_name _policies = conn.get_all_user_policies(name, max_items=100) _policies = _policies.list_user_policies_response.list_user_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_user_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_user_policy_response.get_user_policy_result.policy_document )) policies[policy_name] = _policy user_sls = [] user_sls.append({"name": name}) user_sls.append({"policies": policies}) user_sls.append({"path": user.path}) results["manage user " + name] = {"boto_iam.user_present": user_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def export_roles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM role details. Produces results that can be used to create an sls file. CLI Example: salt-call boto_iam.export_roles --out=txt | sed "s/local: //" > iam_roles.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() roles = get_all_roles(path_prefix, region, key, keyid, profile) for role in roles: name = role.role_name _policies = conn.list_role_policies(name, max_items=100) _policies = _policies.list_role_policies_response.list_role_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_role_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_role_policy_response.get_role_policy_result.policy_document )) policies[policy_name] = _policy role_sls = [] role_sls.append({"name": name}) role_sls.append({"policies": policies}) role_sls.append({'policy_document': salt.utils.json.loads(_unquote(role.assume_role_policy_document))}) role_sls.append({"path": role.path}) results["manage role " + name] = {"boto_iam_role.present": role_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def _get_policy_arn(name, region=None, key=None, keyid=None, profile=None): if name.startswith('arn:aws:iam:'): return name account_id = get_account_id( region=region, key=key, keyid=keyid, profile=profile ) return 'arn:aws:iam::{0}:policy/{1}'.format(account_id, name) def policy_exists(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return True except boto.exception.BotoServerError: return False def get_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return ret.get('get_policy_response', {}).get('get_policy_result', {}) except boto.exception.BotoServerError: return None def create_policy(policy_name, policy_document, path=None, description=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in 'path', 'description': if locals()[arg] is not None: params[arg] = locals()[arg] if policy_exists(policy_name, region, key, keyid, profile): return True try: conn.create_policy(policy_name, policy_document, **params) log.info('Created IAM policy %s.', policy_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s.', policy_name) return False return True def delete_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_exists(policy_arn, region, key, keyid, profile): return True try: conn.delete_policy(policy_arn) log.info('Deleted %s policy.', policy_name) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete %s policy: %s.', policy_name, aws.get('message')) return False return True def list_policies(region=None, key=None, keyid=None, profile=None): ''' List policies. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policies ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: policies = [] for ret in __utils__['boto.paged_call'](conn.list_policies): policies.append(ret.get('list_policies_response', {}).get('list_policies_result', {}).get('policies')) return policies except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to list policy versions.' log.error(msg) return [] def policy_version_exists(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.get_policy_version(policy_arn, version_id) return True except boto.exception.BotoServerError: return False def get_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy_version(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile), version_id) retval = ret.get('get_policy_version_response', {}).get('get_policy_version_result', {}).get('policy_version', {}) retval['document'] = _unquote(retval.get('document')) return {'policy_version': retval} except boto.exception.BotoServerError: return None def create_policy_version(policy_name, policy_document, set_as_default=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy version. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy_version mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in ('set_as_default',): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.create_policy_version(policy_arn, policy_document, **params) vid = ret.get('create_policy_version_response', {}).get('create_policy_version_result', {}).get('policy_version', {}).get('version_id') log.info('Created IAM policy %s version %s.', policy_name, vid) return {'created': True, 'version_id': vid} except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s version %s.', policy_name, vid) return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Delete a policy version. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_version_exists(policy_arn, version_id, region, key, keyid, profile): return True try: conn.delete_policy_version(policy_arn, version_id) log.info('Deleted IAM policy %s version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete IAM policy %s version %s: %s', policy_name, version_id, aws.get('message')) return False return True def list_policy_versions(policy_name, region=None, key=None, keyid=None, profile=None): ''' List versions of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policy_versions mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.list_policy_versions(policy_arn) return ret.get('list_policy_versions_response', {}).get('list_policy_versions_result', {}).get('versions') except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list versions for IAM policy %s.', policy_name) return [] def set_default_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Set the default version of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.set_default_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.set_default_policy_version(policy_arn, version_id) log.info('Set %s policy to version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to set %s policy to version %s: %s', policy_name, version_id, aws.get('message')) return False return True def attach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_user_policy(policy_arn, user_name) log.info('Attached policy %s to IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach %s policy to IAM user %s.', policy_name, user_name) return False return True def detach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_user_policy(policy_arn, user_name) log.info('Detached %s policy from IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach %s policy from IAM user %s.', policy_name, user_name) return False return True def attach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_group_policy(policy_arn, group_name) log.info('Attached policy %s to IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM group %s.', policy_name, group_name) return False return True def detach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_group_policy(policy_arn, group_name) log.info('Detached policy %s from IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM group %s.', policy_name, group_name) return False return True def attach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_role_policy(policy_arn, role_name) log.info('Attached policy %s to IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM role %s.', policy_name, role_name) return False return True def detach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_role_policy(policy_arn, role_name) log.info('Detached policy %s from IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM role %s.', policy_name, role_name) return False return True def list_entities_for_policy(policy_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities that a policy is attached to. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 params = {} for arg in ('path_prefix', 'entity_filter'): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) while retries: try: allret = { 'policy_groups': [], 'policy_users': [], 'policy_roles': [], } for ret in __utils__['boto.paged_call'](conn.list_entities_for_policy, policy_arn=policy_arn, **params): for k, v in six.iteritems(allret): v.extend(ret.get('list_entities_for_policy_response', {}).get('list_entities_for_policy_result', {}).get(k)) return allret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('Failed to list entities for IAM policy %s: %s', policy_name, e.message) return {} return {} def list_attached_user_policies(user_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given user. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'UserName': user_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedUserPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_user_policies_response', {}).get('list_attached_user_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM user %s.', user_name) return [] def list_attached_group_policies(group_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given group. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'GroupName': group_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedGroupPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_group_policies_response', {}).get('list_attached_group_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM group %s.', group_name) return [] def list_attached_role_policies(role_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'RoleName': role_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedRolePolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_role_policies_response', {}).get('list_attached_role_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM role %s.', role_name) return [] def create_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Create SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.create_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_saml_provider(saml_metadata_document, name) log.info('Successfully created %s SAML provider.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to create SAML provider %s.', name) return False def get_saml_provider_arn(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider_arn my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_saml_providers() for saml_provider in response.list_saml_providers_response.list_saml_providers_result.saml_provider_list: if saml_provider['arn'].endswith(':saml-provider/' + name): return saml_provider['arn'] return False except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to get ARN of SAML provider %s.', name) return False def delete_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Delete SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.delete_saml_provider my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return True conn.delete_saml_provider(saml_provider_arn) log.info('Successfully deleted SAML provider %s.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete SAML provider %s.', name) return False def list_saml_providers(region=None, key=None, keyid=None, profile=None): ''' List SAML providers. CLI Example: .. code-block:: bash salt myminion boto_iam.list_saml_providers ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: providers = [] info = conn.list_saml_providers() for arn in info['list_saml_providers_response']['list_saml_providers_result']['saml_provider_list']: providers.append(arn['arn'].rsplit('/', 1)[1]) return providers except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get list of SAML providers.') return False def get_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider document. CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider arn ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: provider = conn.get_saml_provider(name) return provider['get_saml_provider_response']['get_saml_provider_result']['saml_metadata_document'] except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get SAML provider document %s.', name) return False def update_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Update SAML provider. CLI Example: .. code-block:: bash salt myminion boto_iam.update_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return False if conn.update_saml_provider(name, saml_metadata_document): return True return False except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to update SAML provider %s.', name) return False
saltstack/salt
salt/modules/boto_iam.py
get_all_instance_profiles
python
def get_all_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.get_all_instance_profiles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) marker = False profiles = [] while marker is not None: marker = marker if marker else None p = conn.list_instance_profiles(path_prefix=path_prefix, marker=marker) res = p.list_instance_profiles_response.list_instance_profiles_result profiles += res.instance_profiles marker = getattr(res, 'marker', None) return profiles
Get and return all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.get_all_instance_profiles
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iam.py#L653-L674
null
# -*- coding: utf-8 -*- ''' Connection module for Amazon IAM .. versionadded:: 2014.7.0 :configuration: This module accepts explicit iam 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 iam.keyid: GKTADJGHEIQSXMKKRBJ08H iam.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs iam.region: 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: boto ''' # keep lint from choking on _get_conn and _cache_id #pylint: disable=E0602 # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import salt libs from salt.ext import six import salt.utils.compat import salt.utils.json import salt.utils.odict as odict import salt.utils.versions from salt.exceptions import SaltInvocationError # Import third party libs # pylint: disable=unused-import from salt.ext.six.moves.urllib.parse import unquote as _unquote # pylint: disable=no-name-in-module try: import boto import boto.iam import boto3 import botocore logging.getLogger('boto').setLevel(logging.CRITICAL) logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=unused-import log = logging.getLogger(__name__) def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'iam', pack=__salt__) def instance_profile_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an instance profile exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: # Boto weirdly returns an exception here if an instance profile doesn't # exist. conn.get_instance_profile(name) return True except boto.exception.BotoServerError: return False def create_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Create an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.create_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if instance_profile_exists(name, region, key, keyid, profile): return True try: # This call returns an instance profile if successful and an exception # if not. It's annoying. conn.create_instance_profile(name) log.info('Created %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create %s instance profile.', name) return False return True def delete_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Delete an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not instance_profile_exists(name, region, key, keyid, profile): return True try: conn.delete_instance_profile(name) log.info('Deleted %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s instance profile.', name) return False return True def role_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an IAM role exists. CLI Example: .. code-block:: bash salt myminion boto_iam.role_exists myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_role(name) return True except boto.exception.BotoServerError: return False def describe_role(name, region=None, key=None, keyid=None, profile=None): ''' Get information for a role. CLI Example: .. code-block:: bash salt myminion boto_iam.describe_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_role(name) if not info: return False role = info.get_role_response.get_role_result.role role['assume_role_policy_document'] = salt.utils.json.loads(_unquote( role.assume_role_policy_document )) # If Sid wasn't defined by the user, boto will still return a Sid in # each policy. To properly check idempotently, let's remove the Sid # from the return if it's not actually set. for policy_key, policy in role['assume_role_policy_document'].items(): if policy_key == 'Statement': for val in policy: if 'Sid' in val and not val['Sid']: del val['Sid'] return role except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get %s information.', name) return False def create_user(user_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_user myuser ''' if not path: path = '/' if get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_user(user_name, path) log.info('Created IAM user : %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM user %s.', user_name) return False def get_all_access_keys(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all access keys from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_access_keys myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.get_all_access_keys(user_name, marker, max_items) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get access keys for IAM user %s.', user_name) return six.text_type(e) def create_access_key(user_name, region=None, key=None, keyid=None, profile=None): ''' Create access key id for a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.create_access_key(user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create access key.') return six.text_type(e) def delete_access_key(access_key_id, user_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete access key id from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_access_key(access_key_id, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete access key id %s.', access_key_id) return six.text_type(e) def delete_user(user_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user myuser ''' if not get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.delete_user(user_name) log.info('Deleted IAM user : %s .', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM user %s', user_name) return six.text_type(e) def get_user(user_name=None, region=None, key=None, keyid=None, profile=None): ''' Get user information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user(user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM user %s info.', user_name) return False def create_group(group_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_group group ''' if not path: path = '/' if get_group(group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_group(group_name, path) log.info('Created IAM group : %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM group %s.', group_name) return False def get_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group(group_name, max_items=1) if not info: return False return info['get_group_response']['get_group_result']['group'] except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_group_members(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: marker = None truncated = True users = [] while truncated: info = conn.get_group(group_name, marker=marker, max_items=1000) if not info: return False truncated = bool(info['get_group_response']['get_group_result']['is_truncated']) if truncated and 'marker' in info['get_group_response']['get_group_result']: marker = info['get_group_response']['get_group_result']['marker'] else: marker = None truncated = False users += info['get_group_response']['get_group_result']['users'] return users except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get members for IAM group %s.', group_name) return False def add_user_to_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Add user to group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.add_user_to_group myuser mygroup ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('Username : %s does not exist.', user_name) return False if user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.add_user_to_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add IAM user %s to group %s.', user_name, group_name) return False def user_exists_in_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Check if user exists in group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.user_exists_in_group myuser mygroup ''' # TODO this should probably use boto.iam.get_groups_for_user users = get_group_members( group_name=group_name, region=region, key=key, keyid=keyid, profile=profile ) if users: for _user in users: if user_name == _user['user_name']: log.debug('IAM user %s is already in IAM group %s.', user_name, group_name) return True return False def remove_user_from_group(group_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Remove user from group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.remove_user_from_group mygroup myuser ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist.', user_name) return False if not user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.remove_user_from_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove IAM user %s from group %s', user_name, group_name) return False def put_group_policy(group_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_group_policy mygroup policyname policyrules ''' group = get_group(group_name, region=region, key=key, keyid=keyid, profile=profile) if not group: log.error('Group %s does not exist', group_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_group_policy(group_name, policy_name, policy_json) if created: log.info('Created policy for IAM group %s.', group_name) return True log.error('Could not create policy for IAM group %s', group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy for IAM group %s', group_name) return False def delete_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group_policy mygroup mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_group_policy( group_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_group_policy(group_name, policy_name) log.info('Successfully deleted policy %s for IAM group %s.', policy_name, group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM group %s.', policy_name, group_name) return False def get_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group_policy mygroup policyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group_policy(group_name, policy_name) log.debug('info for group policy is : %s', info) if not info: return False info = info.get_group_policy_response.get_group_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_all_groups(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM group details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_groups ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _groups = conn.get_all_groups(path_prefix=path_prefix) groups = _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) while marker: _groups = conn.get_all_groups(path_prefix=path_prefix, marker=marker) groups = groups + _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) return groups def list_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' List all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.list_instance_profiles ''' p = get_all_instance_profiles(path_prefix, region, key, keyid, profile) return [i['instance_profile_name'] for i in p] def get_all_group_policies(group_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a group. CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_group_policies mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False try: response = conn.get_all_group_policies(group_name) _list = response.list_group_policies_response.list_group_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def delete_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _group = get_group( group_name, region, key, keyid, profile ) if not _group: return True try: conn.delete_group(group_name) log.info('Successfully deleted IAM group %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM group %s.', group_name) return False def create_login_profile(user_name, password, region=None, key=None, keyid=None, profile=None): ''' Creates a login profile for the specified user, give the user the ability to access AWS services and the AWS Management Console. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_login_profile user_name password ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.create_login_profile(user_name, password) log.info('Created profile for IAM user %s.', user_name) return info except boto.exception.BotoServerError as e: log.debug(e) if 'Conflict' in e: log.info('Profile already exists for IAM user %s.', user_name) return 'Conflict' log.error('Failed to update profile for IAM user %s.', user_name) return False def delete_login_profile(user_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a login profile for the specified user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_login_profile user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.delete_login_profile(user_name) log.info('Deleted login profile for IAM user %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Login profile already deleted for IAM user %s.', user_name) return True log.error('Failed to delete login profile for IAM user %s.', user_name) return False def get_all_mfa_devices(user_name, region=None, key=None, keyid=None, profile=None): ''' Get all MFA devices associated with an IAM user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_mfa_devices user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: result = conn.get_all_mfa_devices(user_name) devices = result['list_mfa_devices_response']['list_mfa_devices_result']['mfa_devices'] return devices except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Could not find IAM user %s.', user_name) return [] log.error('Failed to get all MFA devices for IAM user %s.', user_name) return False def deactivate_mfa_device(user_name, serial, region=None, key=None, keyid=None, profile=None): ''' Deactivates the specified MFA device and removes it from association with the user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.deactivate_mfa_device user_name serial_num ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.deactivate_mfa_device(user_name, serial) log.info('Deactivated MFA device %s for IAM user %s.', serial, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('MFA device %s not associated with IAM user %s.', serial, user_name) return True log.error('Failed to deactivate MFA device %s for IAM user %s.', serial, user_name) return False def delete_virtual_mfa_device(serial, region=None, key=None, keyid=None, profile=None): ''' Deletes the specified virtual MFA device. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_virtual_mfa_device serial_num ''' conn = __utils__['boto3.get_connection_func']('iam')() try: conn.delete_virtual_mfa_device(SerialNumber=serial) log.info('Deleted virtual MFA device %s.', serial) return True except botocore.exceptions.ClientError as e: log.debug(e) if 'NoSuchEntity' in six.text_type(e): log.info('Virtual MFA device %s not found.', serial) return True log.error('Failed to delete virtual MFA device %s.', serial) return False def update_account_password_policy(allow_users_to_change_password=None, hard_expiry=None, max_password_age=None, minimum_password_length=None, password_reuse_prevention=None, require_lowercase_characters=None, require_numbers=None, require_symbols=None, require_uppercase_characters=None, region=None, key=None, keyid=None, profile=None): ''' Update the password policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_account_password_policy True ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.update_account_password_policy(allow_users_to_change_password, hard_expiry, max_password_age, minimum_password_length, password_reuse_prevention, require_lowercase_characters, require_numbers, require_symbols, require_uppercase_characters) log.info('The password policy has been updated.') return True except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy' log.error(msg) return False def get_account_policy(region=None, key=None, keyid=None, profile=None): ''' Get account policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_account_password_policy() return info.get_account_password_policy_response.get_account_password_policy_result.password_policy except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy.' log.error(msg) return False def create_role(name, policy_document=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Create an instance role. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if role_exists(name, region, key, keyid, profile): return True if not policy_document: policy_document = None try: conn.create_role(name, assume_role_policy_document=policy_document, path=path) log.info('Created IAM role %s.', name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to create IAM role %s.', name) return False def delete_role(name, region=None, key=None, keyid=None, profile=None): ''' Delete an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(name, region, key, keyid, profile): return True try: conn.delete_role(name) log.info('Deleted %s IAM role.', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s IAM role.', name) return False def profile_associated(role_name, profile_name, region, key, keyid, profile): ''' Check to see if an instance profile is associated with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.profile_associated myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # The IAM module of boto doesn't return objects. Instead you need to grab # values through its properties. Sigh. try: profiles = conn.list_instance_profiles_for_role(role_name) except boto.exception.BotoServerError as e: log.debug(e) return False profiles = profiles.list_instance_profiles_for_role_response profiles = profiles.list_instance_profiles_for_role_result profiles = profiles.instance_profiles for profile in profiles: if profile.instance_profile_name == profile_name: return True return False def associate_profile_to_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Associate an instance profile with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.associate_profile_to_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if associated: return True else: try: conn.add_role_to_instance_profile(profile_name, role_name) log.info('Added %s instance profile to IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add %s instance profile to IAM role %s', profile_name, role_name) return False def disassociate_profile_from_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Disassociate an instance profile from an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.disassociate_profile_from_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if not associated: return True else: try: conn.remove_role_from_instance_profile(profile_name, role_name) log.info('Removed %s instance profile from IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove %s instance profile from IAM role %s.', profile_name, role_name) return False def list_role_policies(role_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_role_policies myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_role_policies(role_name) _list = response.list_role_policies_response.list_role_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def get_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.get_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: _policy = conn.get_role_policy(role_name, policy_name) # I _hate_ you for not giving me an object boto. _policy = _policy.get_role_policy_response.policy_document # Policy is url encoded _policy = _unquote(_policy) _policy = salt.utils.json.loads(_policy, object_pairs_hook=odict.OrderedDict) return _policy except boto.exception.BotoServerError: return {} def create_role_policy(role_name, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Create or modify a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role_policy myirole mypolicy '{"MyPolicy": "Statement": [{"Action": ["sqs:*"], "Effect": "Allow", "Resource": ["arn:aws:sqs:*:*:*"], "Sid": "MyPolicySqs1"}]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) mode = 'create' if _policy: if _policy == policy: return True mode = 'modify' if isinstance(policy, six.string_types): policy = salt.utils.json.loads(policy, object_pairs_hook=odict.OrderedDict) try: _policy = salt.utils.json.dumps(policy) conn.put_role_policy(role_name, policy_name, _policy) if mode == 'create': msg = 'Successfully added policy %s to IAM role %s.' else: msg = 'Successfully modified policy %s for IAM role %s.' log.info(msg, policy_name, role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to %s policy %s for IAM role %s.', mode, policy_name, role_name) return False def delete_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) if not _policy: return True try: conn.delete_role_policy(role_name, policy_name) log.info('Successfully deleted policy %s for IAM role %s.', policy_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM role %s.', policy_name, role_name) return False def update_assume_role_policy(role_name, policy_document, region=None, key=None, keyid=None, profile=None): ''' Update an assume role policy for a role. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_assume_role_policy myrole '{"Statement":"..."}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(policy_document, six.string_types): policy_document = salt.utils.json.loads(policy_document, object_pairs_hook=odict.OrderedDict) try: _policy_document = salt.utils.json.dumps(policy_document) conn.update_assume_role_policy(role_name, _policy_document) log.info('Successfully updated assume role policy for IAM role %s.', role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to update assume role policy for IAM role %s.', role_name) return False def build_policy(region=None, key=None, keyid=None, profile=None): ''' Build a default assume role policy. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.build_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if hasattr(conn, 'build_policy'): policy = salt.utils.json.loads(conn.build_policy()) elif hasattr(conn, '_build_policy'): policy = salt.utils.json.loads(conn._build_policy()) else: return {} # The format we get from build_policy isn't going to be what we get back # from AWS for the exact same policy. AWS converts single item list values # into strings, so let's do the same here. for key, policy_val in policy.items(): for statement in policy_val: if (isinstance(statement['Action'], list) and len(statement['Action']) == 1): statement['Action'] = statement['Action'][0] if (isinstance(statement['Principal']['Service'], list) and len(statement['Principal']['Service']) == 1): statement['Principal']['Service'] = statement['Principal']['Service'][0] # build_policy doesn't add a version field, which AWS is going to set to a # default value, when we get it back, so let's set it. policy['Version'] = '2008-10-17' return policy def get_account_id(region=None, key=None, keyid=None, profile=None): ''' Get a the AWS account id associated with the used credentials. CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_id ''' cache_key = 'boto_iam.account_id' if cache_key not in __context__: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_user() # The get_user call returns an user ARN: # arn:aws:iam::027050522557:user/salt-test arn = ret['get_user_response']['get_user_result']['user']['arn'] account_id = arn.split(':')[4] except boto.exception.BotoServerError: # If call failed, then let's try to get the ARN from the metadata timeout = boto.config.getfloat( 'Boto', 'metadata_service_timeout', 1.0 ) attempts = boto.config.getint( 'Boto', 'metadata_service_num_attempts', 1 ) identity = boto.utils.get_instance_identity( timeout=timeout, num_retries=attempts ) try: account_id = identity['document']['accountId'] except KeyError: log.error('Failed to get account id from instance_identity in' ' boto_iam.get_account_id.') __context__[cache_key] = account_id return __context__[cache_key] def get_all_roles(path_prefix=None, region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM role details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_roles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _roles = conn.list_roles(path_prefix=path_prefix) roles = _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) while marker: _roles = conn.list_roles(path_prefix=path_prefix, marker=marker) roles = roles + _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) return roles def get_all_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM user details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_users ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _users = conn.get_all_users(path_prefix=path_prefix) users = _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) while marker: _users = conn.get_all_users(path_prefix=path_prefix, marker=marker) users = users + _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) return users def get_all_user_policies(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all user policies. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_user_policies myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_all_user_policies(user_name, marker, max_items) if not info: return False _list = info.list_user_policies_response.list_user_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policies for user %s.', user_name) return False def get_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user_policy myuser mypolicyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user_policy(user_name, policy_name) log.debug('Info for IAM user %s policy %s: %s.', user_name, policy_name, info) if not info: return False info = info.get_user_policy_response.get_user_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policy %s for IAM user %s.', policy_name, user_name) return False def put_user_policy(user_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_user_policy myuser policyname policyrules ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_user_policy(user_name, policy_name, policy_json) if created: log.info('Created policy %s for IAM user %s.', policy_name, user_name) return True log.error('Could not create policy %s for IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy %s for IAM user %s.', policy_name, user_name) return False def delete_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user_policy myuser mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_user_policy( user_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_user_policy(user_name, policy_name) log.info('Successfully deleted policy %s for IAM user %s.', policy_name, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM user %s.', policy_name, user_name) return False def upload_server_cert(cert_name, cert_body, private_key, cert_chain=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Upload a certificate to Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.upload_server_cert mycert_name crt priv_key :param cert_name: The name for the server certificate. Do not include the path in this value. :param cert_body: The contents of the public key certificate in PEM-encoded format. :param private_key: The contents of the private key in PEM-encoded format. :param cert_chain: The contents of the certificate chain. This is typically a concatenation of the PEM-encoded public key certificates of the chain. :param path: The path for the server certificate. :param region: The name of the region to connect to. :param key: The key to be used in order to connect :param keyid: The keyid to be used in order to connect :param profile: The profile that contains a dict of region, key, keyid :return: True / False ''' exists = get_server_certificate(cert_name, region, key, keyid, profile) if exists: return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.upload_server_cert(cert_name, cert_body, private_key, cert_chain) log.info('Created certificate %s.', cert_name) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to failed to create certificate %s.', cert_name) return False def list_server_certificates(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Lists the server certificates stored in IAM that have the specified path prefix. .. versionadded:: ??? :param path_prefix: The path prefix for filtering the results. For example: /company/servercerts would get all server certificates for which the path starts with /company/servercerts . This parameter is optional. If it is not included, it defaults to a slash (/), listing all server certificates. This parameter allows (per its regex pattern) a string of characters consisting of either a forward slash (/) by itself or a string that must begin and end with forward slashes. In addition, it can contain any ASCII character from the ! (u0021) through the DEL character (u007F), including most punctuation characters, digits, and upper and lowercased letters. CLI Example: .. code-block:: bash salt myminion boto_iam.list_server_certificates path_prefix=/somepath/ ''' retries = 10 sleep = 6 conn = __utils__['boto3.get_connection']('iam', region=region, key=key, keyid=keyid, profile=profile) Items = [] while retries: try: log.debug('Garnering list of IAM Server Certificates') IsTruncated = True while IsTruncated: kwargs = {'PathPrefix': path_prefix} ret = conn.list_server_certificates(**kwargs) Items += ret.get('ServerCertificateMetadataList', []) IsTruncated = ret.get('IsTruncated') kwargs.update({'Marker': ret.get('Marker')}) return Items except botocore.exceptions.ParamValidationError as err: raise SaltInvocationError(str(err)) except botocore.exceptions.ClientError as err: if retries and jmespath.search('Error.Code', err.response) == 'Throttling': retries -= 1 log.debug('Throttled by AWS API, retrying in %s seconds...', sleep) time.sleep(sleep) continue log.error('Failed to list IAM Server Certificates: %s', err.message) return None def get_server_certificate(cert_name, region=None, key=None, keyid=None, profile=None): ''' Returns certificate information from Amazon .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_server_certificate mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_server_certificate(cert_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get certificate %s information.', cert_name) return False def delete_server_cert(cert_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a certificate from Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_server_cert mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_server_cert(cert_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete certificate %s.', cert_name) return False def export_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM user details. Produces results that can be used to create an sls file. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.export_users --out=txt | sed "s/local: //" > iam_users.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() users = get_all_users(path_prefix, region, key, keyid, profile) for user in users: name = user.user_name _policies = conn.get_all_user_policies(name, max_items=100) _policies = _policies.list_user_policies_response.list_user_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_user_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_user_policy_response.get_user_policy_result.policy_document )) policies[policy_name] = _policy user_sls = [] user_sls.append({"name": name}) user_sls.append({"policies": policies}) user_sls.append({"path": user.path}) results["manage user " + name] = {"boto_iam.user_present": user_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def export_roles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM role details. Produces results that can be used to create an sls file. CLI Example: salt-call boto_iam.export_roles --out=txt | sed "s/local: //" > iam_roles.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() roles = get_all_roles(path_prefix, region, key, keyid, profile) for role in roles: name = role.role_name _policies = conn.list_role_policies(name, max_items=100) _policies = _policies.list_role_policies_response.list_role_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_role_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_role_policy_response.get_role_policy_result.policy_document )) policies[policy_name] = _policy role_sls = [] role_sls.append({"name": name}) role_sls.append({"policies": policies}) role_sls.append({'policy_document': salt.utils.json.loads(_unquote(role.assume_role_policy_document))}) role_sls.append({"path": role.path}) results["manage role " + name] = {"boto_iam_role.present": role_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def _get_policy_arn(name, region=None, key=None, keyid=None, profile=None): if name.startswith('arn:aws:iam:'): return name account_id = get_account_id( region=region, key=key, keyid=keyid, profile=profile ) return 'arn:aws:iam::{0}:policy/{1}'.format(account_id, name) def policy_exists(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return True except boto.exception.BotoServerError: return False def get_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return ret.get('get_policy_response', {}).get('get_policy_result', {}) except boto.exception.BotoServerError: return None def create_policy(policy_name, policy_document, path=None, description=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in 'path', 'description': if locals()[arg] is not None: params[arg] = locals()[arg] if policy_exists(policy_name, region, key, keyid, profile): return True try: conn.create_policy(policy_name, policy_document, **params) log.info('Created IAM policy %s.', policy_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s.', policy_name) return False return True def delete_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_exists(policy_arn, region, key, keyid, profile): return True try: conn.delete_policy(policy_arn) log.info('Deleted %s policy.', policy_name) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete %s policy: %s.', policy_name, aws.get('message')) return False return True def list_policies(region=None, key=None, keyid=None, profile=None): ''' List policies. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policies ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: policies = [] for ret in __utils__['boto.paged_call'](conn.list_policies): policies.append(ret.get('list_policies_response', {}).get('list_policies_result', {}).get('policies')) return policies except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to list policy versions.' log.error(msg) return [] def policy_version_exists(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.get_policy_version(policy_arn, version_id) return True except boto.exception.BotoServerError: return False def get_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy_version(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile), version_id) retval = ret.get('get_policy_version_response', {}).get('get_policy_version_result', {}).get('policy_version', {}) retval['document'] = _unquote(retval.get('document')) return {'policy_version': retval} except boto.exception.BotoServerError: return None def create_policy_version(policy_name, policy_document, set_as_default=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy version. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy_version mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in ('set_as_default',): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.create_policy_version(policy_arn, policy_document, **params) vid = ret.get('create_policy_version_response', {}).get('create_policy_version_result', {}).get('policy_version', {}).get('version_id') log.info('Created IAM policy %s version %s.', policy_name, vid) return {'created': True, 'version_id': vid} except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s version %s.', policy_name, vid) return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Delete a policy version. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_version_exists(policy_arn, version_id, region, key, keyid, profile): return True try: conn.delete_policy_version(policy_arn, version_id) log.info('Deleted IAM policy %s version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete IAM policy %s version %s: %s', policy_name, version_id, aws.get('message')) return False return True def list_policy_versions(policy_name, region=None, key=None, keyid=None, profile=None): ''' List versions of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policy_versions mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.list_policy_versions(policy_arn) return ret.get('list_policy_versions_response', {}).get('list_policy_versions_result', {}).get('versions') except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list versions for IAM policy %s.', policy_name) return [] def set_default_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Set the default version of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.set_default_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.set_default_policy_version(policy_arn, version_id) log.info('Set %s policy to version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to set %s policy to version %s: %s', policy_name, version_id, aws.get('message')) return False return True def attach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_user_policy(policy_arn, user_name) log.info('Attached policy %s to IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach %s policy to IAM user %s.', policy_name, user_name) return False return True def detach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_user_policy(policy_arn, user_name) log.info('Detached %s policy from IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach %s policy from IAM user %s.', policy_name, user_name) return False return True def attach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_group_policy(policy_arn, group_name) log.info('Attached policy %s to IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM group %s.', policy_name, group_name) return False return True def detach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_group_policy(policy_arn, group_name) log.info('Detached policy %s from IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM group %s.', policy_name, group_name) return False return True def attach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_role_policy(policy_arn, role_name) log.info('Attached policy %s to IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM role %s.', policy_name, role_name) return False return True def detach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_role_policy(policy_arn, role_name) log.info('Detached policy %s from IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM role %s.', policy_name, role_name) return False return True def list_entities_for_policy(policy_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities that a policy is attached to. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 params = {} for arg in ('path_prefix', 'entity_filter'): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) while retries: try: allret = { 'policy_groups': [], 'policy_users': [], 'policy_roles': [], } for ret in __utils__['boto.paged_call'](conn.list_entities_for_policy, policy_arn=policy_arn, **params): for k, v in six.iteritems(allret): v.extend(ret.get('list_entities_for_policy_response', {}).get('list_entities_for_policy_result', {}).get(k)) return allret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('Failed to list entities for IAM policy %s: %s', policy_name, e.message) return {} return {} def list_attached_user_policies(user_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given user. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'UserName': user_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedUserPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_user_policies_response', {}).get('list_attached_user_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM user %s.', user_name) return [] def list_attached_group_policies(group_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given group. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'GroupName': group_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedGroupPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_group_policies_response', {}).get('list_attached_group_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM group %s.', group_name) return [] def list_attached_role_policies(role_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'RoleName': role_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedRolePolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_role_policies_response', {}).get('list_attached_role_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM role %s.', role_name) return [] def create_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Create SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.create_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_saml_provider(saml_metadata_document, name) log.info('Successfully created %s SAML provider.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to create SAML provider %s.', name) return False def get_saml_provider_arn(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider_arn my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_saml_providers() for saml_provider in response.list_saml_providers_response.list_saml_providers_result.saml_provider_list: if saml_provider['arn'].endswith(':saml-provider/' + name): return saml_provider['arn'] return False except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to get ARN of SAML provider %s.', name) return False def delete_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Delete SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.delete_saml_provider my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return True conn.delete_saml_provider(saml_provider_arn) log.info('Successfully deleted SAML provider %s.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete SAML provider %s.', name) return False def list_saml_providers(region=None, key=None, keyid=None, profile=None): ''' List SAML providers. CLI Example: .. code-block:: bash salt myminion boto_iam.list_saml_providers ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: providers = [] info = conn.list_saml_providers() for arn in info['list_saml_providers_response']['list_saml_providers_result']['saml_provider_list']: providers.append(arn['arn'].rsplit('/', 1)[1]) return providers except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get list of SAML providers.') return False def get_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider document. CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider arn ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: provider = conn.get_saml_provider(name) return provider['get_saml_provider_response']['get_saml_provider_result']['saml_metadata_document'] except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get SAML provider document %s.', name) return False def update_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Update SAML provider. CLI Example: .. code-block:: bash salt myminion boto_iam.update_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return False if conn.update_saml_provider(name, saml_metadata_document): return True return False except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to update SAML provider %s.', name) return False
saltstack/salt
salt/modules/boto_iam.py
list_instance_profiles
python
def list_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' List all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.list_instance_profiles ''' p = get_all_instance_profiles(path_prefix, region, key, keyid, profile) return [i['instance_profile_name'] for i in p]
List all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.list_instance_profiles
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iam.py#L677-L689
[ "def get_all_instance_profiles(path_prefix='/', region=None, key=None,\n keyid=None, profile=None):\n '''\n Get and return all IAM instance profiles, starting at the optional path.\n\n .. versionadded:: 2016.11.0\n\n CLI Example:\n\n salt-call boto_iam.get_all_instance_profiles\n '''\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n marker = False\n profiles = []\n while marker is not None:\n marker = marker if marker else None\n p = conn.list_instance_profiles(path_prefix=path_prefix,\n marker=marker)\n res = p.list_instance_profiles_response.list_instance_profiles_result\n profiles += res.instance_profiles\n marker = getattr(res, 'marker', None)\n return profiles\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon IAM .. versionadded:: 2014.7.0 :configuration: This module accepts explicit iam 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 iam.keyid: GKTADJGHEIQSXMKKRBJ08H iam.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs iam.region: 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: boto ''' # keep lint from choking on _get_conn and _cache_id #pylint: disable=E0602 # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import salt libs from salt.ext import six import salt.utils.compat import salt.utils.json import salt.utils.odict as odict import salt.utils.versions from salt.exceptions import SaltInvocationError # Import third party libs # pylint: disable=unused-import from salt.ext.six.moves.urllib.parse import unquote as _unquote # pylint: disable=no-name-in-module try: import boto import boto.iam import boto3 import botocore logging.getLogger('boto').setLevel(logging.CRITICAL) logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=unused-import log = logging.getLogger(__name__) def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'iam', pack=__salt__) def instance_profile_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an instance profile exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: # Boto weirdly returns an exception here if an instance profile doesn't # exist. conn.get_instance_profile(name) return True except boto.exception.BotoServerError: return False def create_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Create an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.create_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if instance_profile_exists(name, region, key, keyid, profile): return True try: # This call returns an instance profile if successful and an exception # if not. It's annoying. conn.create_instance_profile(name) log.info('Created %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create %s instance profile.', name) return False return True def delete_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Delete an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not instance_profile_exists(name, region, key, keyid, profile): return True try: conn.delete_instance_profile(name) log.info('Deleted %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s instance profile.', name) return False return True def role_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an IAM role exists. CLI Example: .. code-block:: bash salt myminion boto_iam.role_exists myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_role(name) return True except boto.exception.BotoServerError: return False def describe_role(name, region=None, key=None, keyid=None, profile=None): ''' Get information for a role. CLI Example: .. code-block:: bash salt myminion boto_iam.describe_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_role(name) if not info: return False role = info.get_role_response.get_role_result.role role['assume_role_policy_document'] = salt.utils.json.loads(_unquote( role.assume_role_policy_document )) # If Sid wasn't defined by the user, boto will still return a Sid in # each policy. To properly check idempotently, let's remove the Sid # from the return if it's not actually set. for policy_key, policy in role['assume_role_policy_document'].items(): if policy_key == 'Statement': for val in policy: if 'Sid' in val and not val['Sid']: del val['Sid'] return role except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get %s information.', name) return False def create_user(user_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_user myuser ''' if not path: path = '/' if get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_user(user_name, path) log.info('Created IAM user : %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM user %s.', user_name) return False def get_all_access_keys(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all access keys from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_access_keys myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.get_all_access_keys(user_name, marker, max_items) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get access keys for IAM user %s.', user_name) return six.text_type(e) def create_access_key(user_name, region=None, key=None, keyid=None, profile=None): ''' Create access key id for a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.create_access_key(user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create access key.') return six.text_type(e) def delete_access_key(access_key_id, user_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete access key id from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_access_key(access_key_id, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete access key id %s.', access_key_id) return six.text_type(e) def delete_user(user_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user myuser ''' if not get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.delete_user(user_name) log.info('Deleted IAM user : %s .', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM user %s', user_name) return six.text_type(e) def get_user(user_name=None, region=None, key=None, keyid=None, profile=None): ''' Get user information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user(user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM user %s info.', user_name) return False def create_group(group_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_group group ''' if not path: path = '/' if get_group(group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_group(group_name, path) log.info('Created IAM group : %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM group %s.', group_name) return False def get_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group(group_name, max_items=1) if not info: return False return info['get_group_response']['get_group_result']['group'] except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_group_members(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: marker = None truncated = True users = [] while truncated: info = conn.get_group(group_name, marker=marker, max_items=1000) if not info: return False truncated = bool(info['get_group_response']['get_group_result']['is_truncated']) if truncated and 'marker' in info['get_group_response']['get_group_result']: marker = info['get_group_response']['get_group_result']['marker'] else: marker = None truncated = False users += info['get_group_response']['get_group_result']['users'] return users except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get members for IAM group %s.', group_name) return False def add_user_to_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Add user to group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.add_user_to_group myuser mygroup ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('Username : %s does not exist.', user_name) return False if user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.add_user_to_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add IAM user %s to group %s.', user_name, group_name) return False def user_exists_in_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Check if user exists in group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.user_exists_in_group myuser mygroup ''' # TODO this should probably use boto.iam.get_groups_for_user users = get_group_members( group_name=group_name, region=region, key=key, keyid=keyid, profile=profile ) if users: for _user in users: if user_name == _user['user_name']: log.debug('IAM user %s is already in IAM group %s.', user_name, group_name) return True return False def remove_user_from_group(group_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Remove user from group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.remove_user_from_group mygroup myuser ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist.', user_name) return False if not user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.remove_user_from_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove IAM user %s from group %s', user_name, group_name) return False def put_group_policy(group_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_group_policy mygroup policyname policyrules ''' group = get_group(group_name, region=region, key=key, keyid=keyid, profile=profile) if not group: log.error('Group %s does not exist', group_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_group_policy(group_name, policy_name, policy_json) if created: log.info('Created policy for IAM group %s.', group_name) return True log.error('Could not create policy for IAM group %s', group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy for IAM group %s', group_name) return False def delete_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group_policy mygroup mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_group_policy( group_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_group_policy(group_name, policy_name) log.info('Successfully deleted policy %s for IAM group %s.', policy_name, group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM group %s.', policy_name, group_name) return False def get_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group_policy mygroup policyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group_policy(group_name, policy_name) log.debug('info for group policy is : %s', info) if not info: return False info = info.get_group_policy_response.get_group_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_all_groups(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM group details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_groups ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _groups = conn.get_all_groups(path_prefix=path_prefix) groups = _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) while marker: _groups = conn.get_all_groups(path_prefix=path_prefix, marker=marker) groups = groups + _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) return groups def get_all_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.get_all_instance_profiles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) marker = False profiles = [] while marker is not None: marker = marker if marker else None p = conn.list_instance_profiles(path_prefix=path_prefix, marker=marker) res = p.list_instance_profiles_response.list_instance_profiles_result profiles += res.instance_profiles marker = getattr(res, 'marker', None) return profiles def get_all_group_policies(group_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a group. CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_group_policies mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False try: response = conn.get_all_group_policies(group_name) _list = response.list_group_policies_response.list_group_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def delete_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _group = get_group( group_name, region, key, keyid, profile ) if not _group: return True try: conn.delete_group(group_name) log.info('Successfully deleted IAM group %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM group %s.', group_name) return False def create_login_profile(user_name, password, region=None, key=None, keyid=None, profile=None): ''' Creates a login profile for the specified user, give the user the ability to access AWS services and the AWS Management Console. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_login_profile user_name password ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.create_login_profile(user_name, password) log.info('Created profile for IAM user %s.', user_name) return info except boto.exception.BotoServerError as e: log.debug(e) if 'Conflict' in e: log.info('Profile already exists for IAM user %s.', user_name) return 'Conflict' log.error('Failed to update profile for IAM user %s.', user_name) return False def delete_login_profile(user_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a login profile for the specified user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_login_profile user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.delete_login_profile(user_name) log.info('Deleted login profile for IAM user %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Login profile already deleted for IAM user %s.', user_name) return True log.error('Failed to delete login profile for IAM user %s.', user_name) return False def get_all_mfa_devices(user_name, region=None, key=None, keyid=None, profile=None): ''' Get all MFA devices associated with an IAM user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_mfa_devices user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: result = conn.get_all_mfa_devices(user_name) devices = result['list_mfa_devices_response']['list_mfa_devices_result']['mfa_devices'] return devices except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Could not find IAM user %s.', user_name) return [] log.error('Failed to get all MFA devices for IAM user %s.', user_name) return False def deactivate_mfa_device(user_name, serial, region=None, key=None, keyid=None, profile=None): ''' Deactivates the specified MFA device and removes it from association with the user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.deactivate_mfa_device user_name serial_num ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.deactivate_mfa_device(user_name, serial) log.info('Deactivated MFA device %s for IAM user %s.', serial, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('MFA device %s not associated with IAM user %s.', serial, user_name) return True log.error('Failed to deactivate MFA device %s for IAM user %s.', serial, user_name) return False def delete_virtual_mfa_device(serial, region=None, key=None, keyid=None, profile=None): ''' Deletes the specified virtual MFA device. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_virtual_mfa_device serial_num ''' conn = __utils__['boto3.get_connection_func']('iam')() try: conn.delete_virtual_mfa_device(SerialNumber=serial) log.info('Deleted virtual MFA device %s.', serial) return True except botocore.exceptions.ClientError as e: log.debug(e) if 'NoSuchEntity' in six.text_type(e): log.info('Virtual MFA device %s not found.', serial) return True log.error('Failed to delete virtual MFA device %s.', serial) return False def update_account_password_policy(allow_users_to_change_password=None, hard_expiry=None, max_password_age=None, minimum_password_length=None, password_reuse_prevention=None, require_lowercase_characters=None, require_numbers=None, require_symbols=None, require_uppercase_characters=None, region=None, key=None, keyid=None, profile=None): ''' Update the password policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_account_password_policy True ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.update_account_password_policy(allow_users_to_change_password, hard_expiry, max_password_age, minimum_password_length, password_reuse_prevention, require_lowercase_characters, require_numbers, require_symbols, require_uppercase_characters) log.info('The password policy has been updated.') return True except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy' log.error(msg) return False def get_account_policy(region=None, key=None, keyid=None, profile=None): ''' Get account policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_account_password_policy() return info.get_account_password_policy_response.get_account_password_policy_result.password_policy except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy.' log.error(msg) return False def create_role(name, policy_document=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Create an instance role. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if role_exists(name, region, key, keyid, profile): return True if not policy_document: policy_document = None try: conn.create_role(name, assume_role_policy_document=policy_document, path=path) log.info('Created IAM role %s.', name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to create IAM role %s.', name) return False def delete_role(name, region=None, key=None, keyid=None, profile=None): ''' Delete an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(name, region, key, keyid, profile): return True try: conn.delete_role(name) log.info('Deleted %s IAM role.', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s IAM role.', name) return False def profile_associated(role_name, profile_name, region, key, keyid, profile): ''' Check to see if an instance profile is associated with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.profile_associated myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # The IAM module of boto doesn't return objects. Instead you need to grab # values through its properties. Sigh. try: profiles = conn.list_instance_profiles_for_role(role_name) except boto.exception.BotoServerError as e: log.debug(e) return False profiles = profiles.list_instance_profiles_for_role_response profiles = profiles.list_instance_profiles_for_role_result profiles = profiles.instance_profiles for profile in profiles: if profile.instance_profile_name == profile_name: return True return False def associate_profile_to_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Associate an instance profile with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.associate_profile_to_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if associated: return True else: try: conn.add_role_to_instance_profile(profile_name, role_name) log.info('Added %s instance profile to IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add %s instance profile to IAM role %s', profile_name, role_name) return False def disassociate_profile_from_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Disassociate an instance profile from an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.disassociate_profile_from_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if not associated: return True else: try: conn.remove_role_from_instance_profile(profile_name, role_name) log.info('Removed %s instance profile from IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove %s instance profile from IAM role %s.', profile_name, role_name) return False def list_role_policies(role_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_role_policies myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_role_policies(role_name) _list = response.list_role_policies_response.list_role_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def get_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.get_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: _policy = conn.get_role_policy(role_name, policy_name) # I _hate_ you for not giving me an object boto. _policy = _policy.get_role_policy_response.policy_document # Policy is url encoded _policy = _unquote(_policy) _policy = salt.utils.json.loads(_policy, object_pairs_hook=odict.OrderedDict) return _policy except boto.exception.BotoServerError: return {} def create_role_policy(role_name, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Create or modify a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role_policy myirole mypolicy '{"MyPolicy": "Statement": [{"Action": ["sqs:*"], "Effect": "Allow", "Resource": ["arn:aws:sqs:*:*:*"], "Sid": "MyPolicySqs1"}]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) mode = 'create' if _policy: if _policy == policy: return True mode = 'modify' if isinstance(policy, six.string_types): policy = salt.utils.json.loads(policy, object_pairs_hook=odict.OrderedDict) try: _policy = salt.utils.json.dumps(policy) conn.put_role_policy(role_name, policy_name, _policy) if mode == 'create': msg = 'Successfully added policy %s to IAM role %s.' else: msg = 'Successfully modified policy %s for IAM role %s.' log.info(msg, policy_name, role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to %s policy %s for IAM role %s.', mode, policy_name, role_name) return False def delete_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) if not _policy: return True try: conn.delete_role_policy(role_name, policy_name) log.info('Successfully deleted policy %s for IAM role %s.', policy_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM role %s.', policy_name, role_name) return False def update_assume_role_policy(role_name, policy_document, region=None, key=None, keyid=None, profile=None): ''' Update an assume role policy for a role. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_assume_role_policy myrole '{"Statement":"..."}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(policy_document, six.string_types): policy_document = salt.utils.json.loads(policy_document, object_pairs_hook=odict.OrderedDict) try: _policy_document = salt.utils.json.dumps(policy_document) conn.update_assume_role_policy(role_name, _policy_document) log.info('Successfully updated assume role policy for IAM role %s.', role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to update assume role policy for IAM role %s.', role_name) return False def build_policy(region=None, key=None, keyid=None, profile=None): ''' Build a default assume role policy. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.build_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if hasattr(conn, 'build_policy'): policy = salt.utils.json.loads(conn.build_policy()) elif hasattr(conn, '_build_policy'): policy = salt.utils.json.loads(conn._build_policy()) else: return {} # The format we get from build_policy isn't going to be what we get back # from AWS for the exact same policy. AWS converts single item list values # into strings, so let's do the same here. for key, policy_val in policy.items(): for statement in policy_val: if (isinstance(statement['Action'], list) and len(statement['Action']) == 1): statement['Action'] = statement['Action'][0] if (isinstance(statement['Principal']['Service'], list) and len(statement['Principal']['Service']) == 1): statement['Principal']['Service'] = statement['Principal']['Service'][0] # build_policy doesn't add a version field, which AWS is going to set to a # default value, when we get it back, so let's set it. policy['Version'] = '2008-10-17' return policy def get_account_id(region=None, key=None, keyid=None, profile=None): ''' Get a the AWS account id associated with the used credentials. CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_id ''' cache_key = 'boto_iam.account_id' if cache_key not in __context__: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_user() # The get_user call returns an user ARN: # arn:aws:iam::027050522557:user/salt-test arn = ret['get_user_response']['get_user_result']['user']['arn'] account_id = arn.split(':')[4] except boto.exception.BotoServerError: # If call failed, then let's try to get the ARN from the metadata timeout = boto.config.getfloat( 'Boto', 'metadata_service_timeout', 1.0 ) attempts = boto.config.getint( 'Boto', 'metadata_service_num_attempts', 1 ) identity = boto.utils.get_instance_identity( timeout=timeout, num_retries=attempts ) try: account_id = identity['document']['accountId'] except KeyError: log.error('Failed to get account id from instance_identity in' ' boto_iam.get_account_id.') __context__[cache_key] = account_id return __context__[cache_key] def get_all_roles(path_prefix=None, region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM role details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_roles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _roles = conn.list_roles(path_prefix=path_prefix) roles = _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) while marker: _roles = conn.list_roles(path_prefix=path_prefix, marker=marker) roles = roles + _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) return roles def get_all_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM user details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_users ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _users = conn.get_all_users(path_prefix=path_prefix) users = _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) while marker: _users = conn.get_all_users(path_prefix=path_prefix, marker=marker) users = users + _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) return users def get_all_user_policies(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all user policies. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_user_policies myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_all_user_policies(user_name, marker, max_items) if not info: return False _list = info.list_user_policies_response.list_user_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policies for user %s.', user_name) return False def get_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user_policy myuser mypolicyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user_policy(user_name, policy_name) log.debug('Info for IAM user %s policy %s: %s.', user_name, policy_name, info) if not info: return False info = info.get_user_policy_response.get_user_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policy %s for IAM user %s.', policy_name, user_name) return False def put_user_policy(user_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_user_policy myuser policyname policyrules ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_user_policy(user_name, policy_name, policy_json) if created: log.info('Created policy %s for IAM user %s.', policy_name, user_name) return True log.error('Could not create policy %s for IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy %s for IAM user %s.', policy_name, user_name) return False def delete_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user_policy myuser mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_user_policy( user_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_user_policy(user_name, policy_name) log.info('Successfully deleted policy %s for IAM user %s.', policy_name, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM user %s.', policy_name, user_name) return False def upload_server_cert(cert_name, cert_body, private_key, cert_chain=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Upload a certificate to Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.upload_server_cert mycert_name crt priv_key :param cert_name: The name for the server certificate. Do not include the path in this value. :param cert_body: The contents of the public key certificate in PEM-encoded format. :param private_key: The contents of the private key in PEM-encoded format. :param cert_chain: The contents of the certificate chain. This is typically a concatenation of the PEM-encoded public key certificates of the chain. :param path: The path for the server certificate. :param region: The name of the region to connect to. :param key: The key to be used in order to connect :param keyid: The keyid to be used in order to connect :param profile: The profile that contains a dict of region, key, keyid :return: True / False ''' exists = get_server_certificate(cert_name, region, key, keyid, profile) if exists: return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.upload_server_cert(cert_name, cert_body, private_key, cert_chain) log.info('Created certificate %s.', cert_name) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to failed to create certificate %s.', cert_name) return False def list_server_certificates(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Lists the server certificates stored in IAM that have the specified path prefix. .. versionadded:: ??? :param path_prefix: The path prefix for filtering the results. For example: /company/servercerts would get all server certificates for which the path starts with /company/servercerts . This parameter is optional. If it is not included, it defaults to a slash (/), listing all server certificates. This parameter allows (per its regex pattern) a string of characters consisting of either a forward slash (/) by itself or a string that must begin and end with forward slashes. In addition, it can contain any ASCII character from the ! (u0021) through the DEL character (u007F), including most punctuation characters, digits, and upper and lowercased letters. CLI Example: .. code-block:: bash salt myminion boto_iam.list_server_certificates path_prefix=/somepath/ ''' retries = 10 sleep = 6 conn = __utils__['boto3.get_connection']('iam', region=region, key=key, keyid=keyid, profile=profile) Items = [] while retries: try: log.debug('Garnering list of IAM Server Certificates') IsTruncated = True while IsTruncated: kwargs = {'PathPrefix': path_prefix} ret = conn.list_server_certificates(**kwargs) Items += ret.get('ServerCertificateMetadataList', []) IsTruncated = ret.get('IsTruncated') kwargs.update({'Marker': ret.get('Marker')}) return Items except botocore.exceptions.ParamValidationError as err: raise SaltInvocationError(str(err)) except botocore.exceptions.ClientError as err: if retries and jmespath.search('Error.Code', err.response) == 'Throttling': retries -= 1 log.debug('Throttled by AWS API, retrying in %s seconds...', sleep) time.sleep(sleep) continue log.error('Failed to list IAM Server Certificates: %s', err.message) return None def get_server_certificate(cert_name, region=None, key=None, keyid=None, profile=None): ''' Returns certificate information from Amazon .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_server_certificate mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_server_certificate(cert_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get certificate %s information.', cert_name) return False def delete_server_cert(cert_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a certificate from Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_server_cert mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_server_cert(cert_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete certificate %s.', cert_name) return False def export_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM user details. Produces results that can be used to create an sls file. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.export_users --out=txt | sed "s/local: //" > iam_users.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() users = get_all_users(path_prefix, region, key, keyid, profile) for user in users: name = user.user_name _policies = conn.get_all_user_policies(name, max_items=100) _policies = _policies.list_user_policies_response.list_user_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_user_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_user_policy_response.get_user_policy_result.policy_document )) policies[policy_name] = _policy user_sls = [] user_sls.append({"name": name}) user_sls.append({"policies": policies}) user_sls.append({"path": user.path}) results["manage user " + name] = {"boto_iam.user_present": user_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def export_roles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM role details. Produces results that can be used to create an sls file. CLI Example: salt-call boto_iam.export_roles --out=txt | sed "s/local: //" > iam_roles.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() roles = get_all_roles(path_prefix, region, key, keyid, profile) for role in roles: name = role.role_name _policies = conn.list_role_policies(name, max_items=100) _policies = _policies.list_role_policies_response.list_role_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_role_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_role_policy_response.get_role_policy_result.policy_document )) policies[policy_name] = _policy role_sls = [] role_sls.append({"name": name}) role_sls.append({"policies": policies}) role_sls.append({'policy_document': salt.utils.json.loads(_unquote(role.assume_role_policy_document))}) role_sls.append({"path": role.path}) results["manage role " + name] = {"boto_iam_role.present": role_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def _get_policy_arn(name, region=None, key=None, keyid=None, profile=None): if name.startswith('arn:aws:iam:'): return name account_id = get_account_id( region=region, key=key, keyid=keyid, profile=profile ) return 'arn:aws:iam::{0}:policy/{1}'.format(account_id, name) def policy_exists(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return True except boto.exception.BotoServerError: return False def get_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return ret.get('get_policy_response', {}).get('get_policy_result', {}) except boto.exception.BotoServerError: return None def create_policy(policy_name, policy_document, path=None, description=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in 'path', 'description': if locals()[arg] is not None: params[arg] = locals()[arg] if policy_exists(policy_name, region, key, keyid, profile): return True try: conn.create_policy(policy_name, policy_document, **params) log.info('Created IAM policy %s.', policy_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s.', policy_name) return False return True def delete_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_exists(policy_arn, region, key, keyid, profile): return True try: conn.delete_policy(policy_arn) log.info('Deleted %s policy.', policy_name) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete %s policy: %s.', policy_name, aws.get('message')) return False return True def list_policies(region=None, key=None, keyid=None, profile=None): ''' List policies. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policies ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: policies = [] for ret in __utils__['boto.paged_call'](conn.list_policies): policies.append(ret.get('list_policies_response', {}).get('list_policies_result', {}).get('policies')) return policies except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to list policy versions.' log.error(msg) return [] def policy_version_exists(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.get_policy_version(policy_arn, version_id) return True except boto.exception.BotoServerError: return False def get_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy_version(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile), version_id) retval = ret.get('get_policy_version_response', {}).get('get_policy_version_result', {}).get('policy_version', {}) retval['document'] = _unquote(retval.get('document')) return {'policy_version': retval} except boto.exception.BotoServerError: return None def create_policy_version(policy_name, policy_document, set_as_default=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy version. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy_version mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in ('set_as_default',): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.create_policy_version(policy_arn, policy_document, **params) vid = ret.get('create_policy_version_response', {}).get('create_policy_version_result', {}).get('policy_version', {}).get('version_id') log.info('Created IAM policy %s version %s.', policy_name, vid) return {'created': True, 'version_id': vid} except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s version %s.', policy_name, vid) return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Delete a policy version. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_version_exists(policy_arn, version_id, region, key, keyid, profile): return True try: conn.delete_policy_version(policy_arn, version_id) log.info('Deleted IAM policy %s version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete IAM policy %s version %s: %s', policy_name, version_id, aws.get('message')) return False return True def list_policy_versions(policy_name, region=None, key=None, keyid=None, profile=None): ''' List versions of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policy_versions mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.list_policy_versions(policy_arn) return ret.get('list_policy_versions_response', {}).get('list_policy_versions_result', {}).get('versions') except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list versions for IAM policy %s.', policy_name) return [] def set_default_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Set the default version of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.set_default_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.set_default_policy_version(policy_arn, version_id) log.info('Set %s policy to version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to set %s policy to version %s: %s', policy_name, version_id, aws.get('message')) return False return True def attach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_user_policy(policy_arn, user_name) log.info('Attached policy %s to IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach %s policy to IAM user %s.', policy_name, user_name) return False return True def detach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_user_policy(policy_arn, user_name) log.info('Detached %s policy from IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach %s policy from IAM user %s.', policy_name, user_name) return False return True def attach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_group_policy(policy_arn, group_name) log.info('Attached policy %s to IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM group %s.', policy_name, group_name) return False return True def detach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_group_policy(policy_arn, group_name) log.info('Detached policy %s from IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM group %s.', policy_name, group_name) return False return True def attach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_role_policy(policy_arn, role_name) log.info('Attached policy %s to IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM role %s.', policy_name, role_name) return False return True def detach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_role_policy(policy_arn, role_name) log.info('Detached policy %s from IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM role %s.', policy_name, role_name) return False return True def list_entities_for_policy(policy_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities that a policy is attached to. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 params = {} for arg in ('path_prefix', 'entity_filter'): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) while retries: try: allret = { 'policy_groups': [], 'policy_users': [], 'policy_roles': [], } for ret in __utils__['boto.paged_call'](conn.list_entities_for_policy, policy_arn=policy_arn, **params): for k, v in six.iteritems(allret): v.extend(ret.get('list_entities_for_policy_response', {}).get('list_entities_for_policy_result', {}).get(k)) return allret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('Failed to list entities for IAM policy %s: %s', policy_name, e.message) return {} return {} def list_attached_user_policies(user_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given user. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'UserName': user_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedUserPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_user_policies_response', {}).get('list_attached_user_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM user %s.', user_name) return [] def list_attached_group_policies(group_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given group. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'GroupName': group_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedGroupPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_group_policies_response', {}).get('list_attached_group_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM group %s.', group_name) return [] def list_attached_role_policies(role_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'RoleName': role_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedRolePolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_role_policies_response', {}).get('list_attached_role_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM role %s.', role_name) return [] def create_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Create SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.create_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_saml_provider(saml_metadata_document, name) log.info('Successfully created %s SAML provider.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to create SAML provider %s.', name) return False def get_saml_provider_arn(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider_arn my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_saml_providers() for saml_provider in response.list_saml_providers_response.list_saml_providers_result.saml_provider_list: if saml_provider['arn'].endswith(':saml-provider/' + name): return saml_provider['arn'] return False except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to get ARN of SAML provider %s.', name) return False def delete_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Delete SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.delete_saml_provider my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return True conn.delete_saml_provider(saml_provider_arn) log.info('Successfully deleted SAML provider %s.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete SAML provider %s.', name) return False def list_saml_providers(region=None, key=None, keyid=None, profile=None): ''' List SAML providers. CLI Example: .. code-block:: bash salt myminion boto_iam.list_saml_providers ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: providers = [] info = conn.list_saml_providers() for arn in info['list_saml_providers_response']['list_saml_providers_result']['saml_provider_list']: providers.append(arn['arn'].rsplit('/', 1)[1]) return providers except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get list of SAML providers.') return False def get_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider document. CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider arn ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: provider = conn.get_saml_provider(name) return provider['get_saml_provider_response']['get_saml_provider_result']['saml_metadata_document'] except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get SAML provider document %s.', name) return False def update_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Update SAML provider. CLI Example: .. code-block:: bash salt myminion boto_iam.update_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return False if conn.update_saml_provider(name, saml_metadata_document): return True return False except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to update SAML provider %s.', name) return False
saltstack/salt
salt/modules/boto_iam.py
get_all_group_policies
python
def get_all_group_policies(group_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a group. CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_group_policies mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False try: response = conn.get_all_group_policies(group_name) _list = response.list_group_policies_response.list_group_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return []
Get a list of policy names from a group. CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_group_policies mygroup
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iam.py#L692-L712
null
# -*- coding: utf-8 -*- ''' Connection module for Amazon IAM .. versionadded:: 2014.7.0 :configuration: This module accepts explicit iam 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 iam.keyid: GKTADJGHEIQSXMKKRBJ08H iam.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs iam.region: 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: boto ''' # keep lint from choking on _get_conn and _cache_id #pylint: disable=E0602 # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import salt libs from salt.ext import six import salt.utils.compat import salt.utils.json import salt.utils.odict as odict import salt.utils.versions from salt.exceptions import SaltInvocationError # Import third party libs # pylint: disable=unused-import from salt.ext.six.moves.urllib.parse import unquote as _unquote # pylint: disable=no-name-in-module try: import boto import boto.iam import boto3 import botocore logging.getLogger('boto').setLevel(logging.CRITICAL) logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=unused-import log = logging.getLogger(__name__) def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'iam', pack=__salt__) def instance_profile_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an instance profile exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: # Boto weirdly returns an exception here if an instance profile doesn't # exist. conn.get_instance_profile(name) return True except boto.exception.BotoServerError: return False def create_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Create an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.create_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if instance_profile_exists(name, region, key, keyid, profile): return True try: # This call returns an instance profile if successful and an exception # if not. It's annoying. conn.create_instance_profile(name) log.info('Created %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create %s instance profile.', name) return False return True def delete_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Delete an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not instance_profile_exists(name, region, key, keyid, profile): return True try: conn.delete_instance_profile(name) log.info('Deleted %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s instance profile.', name) return False return True def role_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an IAM role exists. CLI Example: .. code-block:: bash salt myminion boto_iam.role_exists myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_role(name) return True except boto.exception.BotoServerError: return False def describe_role(name, region=None, key=None, keyid=None, profile=None): ''' Get information for a role. CLI Example: .. code-block:: bash salt myminion boto_iam.describe_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_role(name) if not info: return False role = info.get_role_response.get_role_result.role role['assume_role_policy_document'] = salt.utils.json.loads(_unquote( role.assume_role_policy_document )) # If Sid wasn't defined by the user, boto will still return a Sid in # each policy. To properly check idempotently, let's remove the Sid # from the return if it's not actually set. for policy_key, policy in role['assume_role_policy_document'].items(): if policy_key == 'Statement': for val in policy: if 'Sid' in val and not val['Sid']: del val['Sid'] return role except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get %s information.', name) return False def create_user(user_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_user myuser ''' if not path: path = '/' if get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_user(user_name, path) log.info('Created IAM user : %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM user %s.', user_name) return False def get_all_access_keys(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all access keys from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_access_keys myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.get_all_access_keys(user_name, marker, max_items) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get access keys for IAM user %s.', user_name) return six.text_type(e) def create_access_key(user_name, region=None, key=None, keyid=None, profile=None): ''' Create access key id for a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.create_access_key(user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create access key.') return six.text_type(e) def delete_access_key(access_key_id, user_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete access key id from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_access_key(access_key_id, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete access key id %s.', access_key_id) return six.text_type(e) def delete_user(user_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user myuser ''' if not get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.delete_user(user_name) log.info('Deleted IAM user : %s .', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM user %s', user_name) return six.text_type(e) def get_user(user_name=None, region=None, key=None, keyid=None, profile=None): ''' Get user information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user(user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM user %s info.', user_name) return False def create_group(group_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_group group ''' if not path: path = '/' if get_group(group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_group(group_name, path) log.info('Created IAM group : %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM group %s.', group_name) return False def get_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group(group_name, max_items=1) if not info: return False return info['get_group_response']['get_group_result']['group'] except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_group_members(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: marker = None truncated = True users = [] while truncated: info = conn.get_group(group_name, marker=marker, max_items=1000) if not info: return False truncated = bool(info['get_group_response']['get_group_result']['is_truncated']) if truncated and 'marker' in info['get_group_response']['get_group_result']: marker = info['get_group_response']['get_group_result']['marker'] else: marker = None truncated = False users += info['get_group_response']['get_group_result']['users'] return users except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get members for IAM group %s.', group_name) return False def add_user_to_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Add user to group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.add_user_to_group myuser mygroup ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('Username : %s does not exist.', user_name) return False if user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.add_user_to_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add IAM user %s to group %s.', user_name, group_name) return False def user_exists_in_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Check if user exists in group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.user_exists_in_group myuser mygroup ''' # TODO this should probably use boto.iam.get_groups_for_user users = get_group_members( group_name=group_name, region=region, key=key, keyid=keyid, profile=profile ) if users: for _user in users: if user_name == _user['user_name']: log.debug('IAM user %s is already in IAM group %s.', user_name, group_name) return True return False def remove_user_from_group(group_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Remove user from group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.remove_user_from_group mygroup myuser ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist.', user_name) return False if not user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.remove_user_from_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove IAM user %s from group %s', user_name, group_name) return False def put_group_policy(group_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_group_policy mygroup policyname policyrules ''' group = get_group(group_name, region=region, key=key, keyid=keyid, profile=profile) if not group: log.error('Group %s does not exist', group_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_group_policy(group_name, policy_name, policy_json) if created: log.info('Created policy for IAM group %s.', group_name) return True log.error('Could not create policy for IAM group %s', group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy for IAM group %s', group_name) return False def delete_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group_policy mygroup mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_group_policy( group_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_group_policy(group_name, policy_name) log.info('Successfully deleted policy %s for IAM group %s.', policy_name, group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM group %s.', policy_name, group_name) return False def get_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group_policy mygroup policyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group_policy(group_name, policy_name) log.debug('info for group policy is : %s', info) if not info: return False info = info.get_group_policy_response.get_group_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_all_groups(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM group details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_groups ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _groups = conn.get_all_groups(path_prefix=path_prefix) groups = _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) while marker: _groups = conn.get_all_groups(path_prefix=path_prefix, marker=marker) groups = groups + _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) return groups def get_all_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.get_all_instance_profiles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) marker = False profiles = [] while marker is not None: marker = marker if marker else None p = conn.list_instance_profiles(path_prefix=path_prefix, marker=marker) res = p.list_instance_profiles_response.list_instance_profiles_result profiles += res.instance_profiles marker = getattr(res, 'marker', None) return profiles def list_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' List all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.list_instance_profiles ''' p = get_all_instance_profiles(path_prefix, region, key, keyid, profile) return [i['instance_profile_name'] for i in p] def delete_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _group = get_group( group_name, region, key, keyid, profile ) if not _group: return True try: conn.delete_group(group_name) log.info('Successfully deleted IAM group %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM group %s.', group_name) return False def create_login_profile(user_name, password, region=None, key=None, keyid=None, profile=None): ''' Creates a login profile for the specified user, give the user the ability to access AWS services and the AWS Management Console. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_login_profile user_name password ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.create_login_profile(user_name, password) log.info('Created profile for IAM user %s.', user_name) return info except boto.exception.BotoServerError as e: log.debug(e) if 'Conflict' in e: log.info('Profile already exists for IAM user %s.', user_name) return 'Conflict' log.error('Failed to update profile for IAM user %s.', user_name) return False def delete_login_profile(user_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a login profile for the specified user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_login_profile user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.delete_login_profile(user_name) log.info('Deleted login profile for IAM user %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Login profile already deleted for IAM user %s.', user_name) return True log.error('Failed to delete login profile for IAM user %s.', user_name) return False def get_all_mfa_devices(user_name, region=None, key=None, keyid=None, profile=None): ''' Get all MFA devices associated with an IAM user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_mfa_devices user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: result = conn.get_all_mfa_devices(user_name) devices = result['list_mfa_devices_response']['list_mfa_devices_result']['mfa_devices'] return devices except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Could not find IAM user %s.', user_name) return [] log.error('Failed to get all MFA devices for IAM user %s.', user_name) return False def deactivate_mfa_device(user_name, serial, region=None, key=None, keyid=None, profile=None): ''' Deactivates the specified MFA device and removes it from association with the user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.deactivate_mfa_device user_name serial_num ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.deactivate_mfa_device(user_name, serial) log.info('Deactivated MFA device %s for IAM user %s.', serial, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('MFA device %s not associated with IAM user %s.', serial, user_name) return True log.error('Failed to deactivate MFA device %s for IAM user %s.', serial, user_name) return False def delete_virtual_mfa_device(serial, region=None, key=None, keyid=None, profile=None): ''' Deletes the specified virtual MFA device. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_virtual_mfa_device serial_num ''' conn = __utils__['boto3.get_connection_func']('iam')() try: conn.delete_virtual_mfa_device(SerialNumber=serial) log.info('Deleted virtual MFA device %s.', serial) return True except botocore.exceptions.ClientError as e: log.debug(e) if 'NoSuchEntity' in six.text_type(e): log.info('Virtual MFA device %s not found.', serial) return True log.error('Failed to delete virtual MFA device %s.', serial) return False def update_account_password_policy(allow_users_to_change_password=None, hard_expiry=None, max_password_age=None, minimum_password_length=None, password_reuse_prevention=None, require_lowercase_characters=None, require_numbers=None, require_symbols=None, require_uppercase_characters=None, region=None, key=None, keyid=None, profile=None): ''' Update the password policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_account_password_policy True ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.update_account_password_policy(allow_users_to_change_password, hard_expiry, max_password_age, minimum_password_length, password_reuse_prevention, require_lowercase_characters, require_numbers, require_symbols, require_uppercase_characters) log.info('The password policy has been updated.') return True except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy' log.error(msg) return False def get_account_policy(region=None, key=None, keyid=None, profile=None): ''' Get account policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_account_password_policy() return info.get_account_password_policy_response.get_account_password_policy_result.password_policy except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy.' log.error(msg) return False def create_role(name, policy_document=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Create an instance role. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if role_exists(name, region, key, keyid, profile): return True if not policy_document: policy_document = None try: conn.create_role(name, assume_role_policy_document=policy_document, path=path) log.info('Created IAM role %s.', name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to create IAM role %s.', name) return False def delete_role(name, region=None, key=None, keyid=None, profile=None): ''' Delete an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(name, region, key, keyid, profile): return True try: conn.delete_role(name) log.info('Deleted %s IAM role.', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s IAM role.', name) return False def profile_associated(role_name, profile_name, region, key, keyid, profile): ''' Check to see if an instance profile is associated with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.profile_associated myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # The IAM module of boto doesn't return objects. Instead you need to grab # values through its properties. Sigh. try: profiles = conn.list_instance_profiles_for_role(role_name) except boto.exception.BotoServerError as e: log.debug(e) return False profiles = profiles.list_instance_profiles_for_role_response profiles = profiles.list_instance_profiles_for_role_result profiles = profiles.instance_profiles for profile in profiles: if profile.instance_profile_name == profile_name: return True return False def associate_profile_to_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Associate an instance profile with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.associate_profile_to_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if associated: return True else: try: conn.add_role_to_instance_profile(profile_name, role_name) log.info('Added %s instance profile to IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add %s instance profile to IAM role %s', profile_name, role_name) return False def disassociate_profile_from_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Disassociate an instance profile from an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.disassociate_profile_from_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if not associated: return True else: try: conn.remove_role_from_instance_profile(profile_name, role_name) log.info('Removed %s instance profile from IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove %s instance profile from IAM role %s.', profile_name, role_name) return False def list_role_policies(role_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_role_policies myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_role_policies(role_name) _list = response.list_role_policies_response.list_role_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def get_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.get_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: _policy = conn.get_role_policy(role_name, policy_name) # I _hate_ you for not giving me an object boto. _policy = _policy.get_role_policy_response.policy_document # Policy is url encoded _policy = _unquote(_policy) _policy = salt.utils.json.loads(_policy, object_pairs_hook=odict.OrderedDict) return _policy except boto.exception.BotoServerError: return {} def create_role_policy(role_name, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Create or modify a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role_policy myirole mypolicy '{"MyPolicy": "Statement": [{"Action": ["sqs:*"], "Effect": "Allow", "Resource": ["arn:aws:sqs:*:*:*"], "Sid": "MyPolicySqs1"}]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) mode = 'create' if _policy: if _policy == policy: return True mode = 'modify' if isinstance(policy, six.string_types): policy = salt.utils.json.loads(policy, object_pairs_hook=odict.OrderedDict) try: _policy = salt.utils.json.dumps(policy) conn.put_role_policy(role_name, policy_name, _policy) if mode == 'create': msg = 'Successfully added policy %s to IAM role %s.' else: msg = 'Successfully modified policy %s for IAM role %s.' log.info(msg, policy_name, role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to %s policy %s for IAM role %s.', mode, policy_name, role_name) return False def delete_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) if not _policy: return True try: conn.delete_role_policy(role_name, policy_name) log.info('Successfully deleted policy %s for IAM role %s.', policy_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM role %s.', policy_name, role_name) return False def update_assume_role_policy(role_name, policy_document, region=None, key=None, keyid=None, profile=None): ''' Update an assume role policy for a role. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_assume_role_policy myrole '{"Statement":"..."}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(policy_document, six.string_types): policy_document = salt.utils.json.loads(policy_document, object_pairs_hook=odict.OrderedDict) try: _policy_document = salt.utils.json.dumps(policy_document) conn.update_assume_role_policy(role_name, _policy_document) log.info('Successfully updated assume role policy for IAM role %s.', role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to update assume role policy for IAM role %s.', role_name) return False def build_policy(region=None, key=None, keyid=None, profile=None): ''' Build a default assume role policy. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.build_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if hasattr(conn, 'build_policy'): policy = salt.utils.json.loads(conn.build_policy()) elif hasattr(conn, '_build_policy'): policy = salt.utils.json.loads(conn._build_policy()) else: return {} # The format we get from build_policy isn't going to be what we get back # from AWS for the exact same policy. AWS converts single item list values # into strings, so let's do the same here. for key, policy_val in policy.items(): for statement in policy_val: if (isinstance(statement['Action'], list) and len(statement['Action']) == 1): statement['Action'] = statement['Action'][0] if (isinstance(statement['Principal']['Service'], list) and len(statement['Principal']['Service']) == 1): statement['Principal']['Service'] = statement['Principal']['Service'][0] # build_policy doesn't add a version field, which AWS is going to set to a # default value, when we get it back, so let's set it. policy['Version'] = '2008-10-17' return policy def get_account_id(region=None, key=None, keyid=None, profile=None): ''' Get a the AWS account id associated with the used credentials. CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_id ''' cache_key = 'boto_iam.account_id' if cache_key not in __context__: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_user() # The get_user call returns an user ARN: # arn:aws:iam::027050522557:user/salt-test arn = ret['get_user_response']['get_user_result']['user']['arn'] account_id = arn.split(':')[4] except boto.exception.BotoServerError: # If call failed, then let's try to get the ARN from the metadata timeout = boto.config.getfloat( 'Boto', 'metadata_service_timeout', 1.0 ) attempts = boto.config.getint( 'Boto', 'metadata_service_num_attempts', 1 ) identity = boto.utils.get_instance_identity( timeout=timeout, num_retries=attempts ) try: account_id = identity['document']['accountId'] except KeyError: log.error('Failed to get account id from instance_identity in' ' boto_iam.get_account_id.') __context__[cache_key] = account_id return __context__[cache_key] def get_all_roles(path_prefix=None, region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM role details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_roles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _roles = conn.list_roles(path_prefix=path_prefix) roles = _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) while marker: _roles = conn.list_roles(path_prefix=path_prefix, marker=marker) roles = roles + _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) return roles def get_all_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM user details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_users ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _users = conn.get_all_users(path_prefix=path_prefix) users = _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) while marker: _users = conn.get_all_users(path_prefix=path_prefix, marker=marker) users = users + _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) return users def get_all_user_policies(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all user policies. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_user_policies myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_all_user_policies(user_name, marker, max_items) if not info: return False _list = info.list_user_policies_response.list_user_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policies for user %s.', user_name) return False def get_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user_policy myuser mypolicyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user_policy(user_name, policy_name) log.debug('Info for IAM user %s policy %s: %s.', user_name, policy_name, info) if not info: return False info = info.get_user_policy_response.get_user_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policy %s for IAM user %s.', policy_name, user_name) return False def put_user_policy(user_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_user_policy myuser policyname policyrules ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_user_policy(user_name, policy_name, policy_json) if created: log.info('Created policy %s for IAM user %s.', policy_name, user_name) return True log.error('Could not create policy %s for IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy %s for IAM user %s.', policy_name, user_name) return False def delete_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user_policy myuser mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_user_policy( user_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_user_policy(user_name, policy_name) log.info('Successfully deleted policy %s for IAM user %s.', policy_name, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM user %s.', policy_name, user_name) return False def upload_server_cert(cert_name, cert_body, private_key, cert_chain=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Upload a certificate to Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.upload_server_cert mycert_name crt priv_key :param cert_name: The name for the server certificate. Do not include the path in this value. :param cert_body: The contents of the public key certificate in PEM-encoded format. :param private_key: The contents of the private key in PEM-encoded format. :param cert_chain: The contents of the certificate chain. This is typically a concatenation of the PEM-encoded public key certificates of the chain. :param path: The path for the server certificate. :param region: The name of the region to connect to. :param key: The key to be used in order to connect :param keyid: The keyid to be used in order to connect :param profile: The profile that contains a dict of region, key, keyid :return: True / False ''' exists = get_server_certificate(cert_name, region, key, keyid, profile) if exists: return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.upload_server_cert(cert_name, cert_body, private_key, cert_chain) log.info('Created certificate %s.', cert_name) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to failed to create certificate %s.', cert_name) return False def list_server_certificates(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Lists the server certificates stored in IAM that have the specified path prefix. .. versionadded:: ??? :param path_prefix: The path prefix for filtering the results. For example: /company/servercerts would get all server certificates for which the path starts with /company/servercerts . This parameter is optional. If it is not included, it defaults to a slash (/), listing all server certificates. This parameter allows (per its regex pattern) a string of characters consisting of either a forward slash (/) by itself or a string that must begin and end with forward slashes. In addition, it can contain any ASCII character from the ! (u0021) through the DEL character (u007F), including most punctuation characters, digits, and upper and lowercased letters. CLI Example: .. code-block:: bash salt myminion boto_iam.list_server_certificates path_prefix=/somepath/ ''' retries = 10 sleep = 6 conn = __utils__['boto3.get_connection']('iam', region=region, key=key, keyid=keyid, profile=profile) Items = [] while retries: try: log.debug('Garnering list of IAM Server Certificates') IsTruncated = True while IsTruncated: kwargs = {'PathPrefix': path_prefix} ret = conn.list_server_certificates(**kwargs) Items += ret.get('ServerCertificateMetadataList', []) IsTruncated = ret.get('IsTruncated') kwargs.update({'Marker': ret.get('Marker')}) return Items except botocore.exceptions.ParamValidationError as err: raise SaltInvocationError(str(err)) except botocore.exceptions.ClientError as err: if retries and jmespath.search('Error.Code', err.response) == 'Throttling': retries -= 1 log.debug('Throttled by AWS API, retrying in %s seconds...', sleep) time.sleep(sleep) continue log.error('Failed to list IAM Server Certificates: %s', err.message) return None def get_server_certificate(cert_name, region=None, key=None, keyid=None, profile=None): ''' Returns certificate information from Amazon .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_server_certificate mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_server_certificate(cert_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get certificate %s information.', cert_name) return False def delete_server_cert(cert_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a certificate from Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_server_cert mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_server_cert(cert_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete certificate %s.', cert_name) return False def export_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM user details. Produces results that can be used to create an sls file. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.export_users --out=txt | sed "s/local: //" > iam_users.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() users = get_all_users(path_prefix, region, key, keyid, profile) for user in users: name = user.user_name _policies = conn.get_all_user_policies(name, max_items=100) _policies = _policies.list_user_policies_response.list_user_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_user_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_user_policy_response.get_user_policy_result.policy_document )) policies[policy_name] = _policy user_sls = [] user_sls.append({"name": name}) user_sls.append({"policies": policies}) user_sls.append({"path": user.path}) results["manage user " + name] = {"boto_iam.user_present": user_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def export_roles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM role details. Produces results that can be used to create an sls file. CLI Example: salt-call boto_iam.export_roles --out=txt | sed "s/local: //" > iam_roles.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() roles = get_all_roles(path_prefix, region, key, keyid, profile) for role in roles: name = role.role_name _policies = conn.list_role_policies(name, max_items=100) _policies = _policies.list_role_policies_response.list_role_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_role_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_role_policy_response.get_role_policy_result.policy_document )) policies[policy_name] = _policy role_sls = [] role_sls.append({"name": name}) role_sls.append({"policies": policies}) role_sls.append({'policy_document': salt.utils.json.loads(_unquote(role.assume_role_policy_document))}) role_sls.append({"path": role.path}) results["manage role " + name] = {"boto_iam_role.present": role_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def _get_policy_arn(name, region=None, key=None, keyid=None, profile=None): if name.startswith('arn:aws:iam:'): return name account_id = get_account_id( region=region, key=key, keyid=keyid, profile=profile ) return 'arn:aws:iam::{0}:policy/{1}'.format(account_id, name) def policy_exists(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return True except boto.exception.BotoServerError: return False def get_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return ret.get('get_policy_response', {}).get('get_policy_result', {}) except boto.exception.BotoServerError: return None def create_policy(policy_name, policy_document, path=None, description=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in 'path', 'description': if locals()[arg] is not None: params[arg] = locals()[arg] if policy_exists(policy_name, region, key, keyid, profile): return True try: conn.create_policy(policy_name, policy_document, **params) log.info('Created IAM policy %s.', policy_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s.', policy_name) return False return True def delete_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_exists(policy_arn, region, key, keyid, profile): return True try: conn.delete_policy(policy_arn) log.info('Deleted %s policy.', policy_name) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete %s policy: %s.', policy_name, aws.get('message')) return False return True def list_policies(region=None, key=None, keyid=None, profile=None): ''' List policies. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policies ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: policies = [] for ret in __utils__['boto.paged_call'](conn.list_policies): policies.append(ret.get('list_policies_response', {}).get('list_policies_result', {}).get('policies')) return policies except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to list policy versions.' log.error(msg) return [] def policy_version_exists(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.get_policy_version(policy_arn, version_id) return True except boto.exception.BotoServerError: return False def get_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy_version(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile), version_id) retval = ret.get('get_policy_version_response', {}).get('get_policy_version_result', {}).get('policy_version', {}) retval['document'] = _unquote(retval.get('document')) return {'policy_version': retval} except boto.exception.BotoServerError: return None def create_policy_version(policy_name, policy_document, set_as_default=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy version. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy_version mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in ('set_as_default',): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.create_policy_version(policy_arn, policy_document, **params) vid = ret.get('create_policy_version_response', {}).get('create_policy_version_result', {}).get('policy_version', {}).get('version_id') log.info('Created IAM policy %s version %s.', policy_name, vid) return {'created': True, 'version_id': vid} except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s version %s.', policy_name, vid) return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Delete a policy version. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_version_exists(policy_arn, version_id, region, key, keyid, profile): return True try: conn.delete_policy_version(policy_arn, version_id) log.info('Deleted IAM policy %s version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete IAM policy %s version %s: %s', policy_name, version_id, aws.get('message')) return False return True def list_policy_versions(policy_name, region=None, key=None, keyid=None, profile=None): ''' List versions of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policy_versions mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.list_policy_versions(policy_arn) return ret.get('list_policy_versions_response', {}).get('list_policy_versions_result', {}).get('versions') except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list versions for IAM policy %s.', policy_name) return [] def set_default_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Set the default version of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.set_default_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.set_default_policy_version(policy_arn, version_id) log.info('Set %s policy to version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to set %s policy to version %s: %s', policy_name, version_id, aws.get('message')) return False return True def attach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_user_policy(policy_arn, user_name) log.info('Attached policy %s to IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach %s policy to IAM user %s.', policy_name, user_name) return False return True def detach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_user_policy(policy_arn, user_name) log.info('Detached %s policy from IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach %s policy from IAM user %s.', policy_name, user_name) return False return True def attach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_group_policy(policy_arn, group_name) log.info('Attached policy %s to IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM group %s.', policy_name, group_name) return False return True def detach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_group_policy(policy_arn, group_name) log.info('Detached policy %s from IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM group %s.', policy_name, group_name) return False return True def attach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_role_policy(policy_arn, role_name) log.info('Attached policy %s to IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM role %s.', policy_name, role_name) return False return True def detach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_role_policy(policy_arn, role_name) log.info('Detached policy %s from IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM role %s.', policy_name, role_name) return False return True def list_entities_for_policy(policy_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities that a policy is attached to. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 params = {} for arg in ('path_prefix', 'entity_filter'): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) while retries: try: allret = { 'policy_groups': [], 'policy_users': [], 'policy_roles': [], } for ret in __utils__['boto.paged_call'](conn.list_entities_for_policy, policy_arn=policy_arn, **params): for k, v in six.iteritems(allret): v.extend(ret.get('list_entities_for_policy_response', {}).get('list_entities_for_policy_result', {}).get(k)) return allret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('Failed to list entities for IAM policy %s: %s', policy_name, e.message) return {} return {} def list_attached_user_policies(user_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given user. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'UserName': user_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedUserPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_user_policies_response', {}).get('list_attached_user_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM user %s.', user_name) return [] def list_attached_group_policies(group_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given group. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'GroupName': group_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedGroupPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_group_policies_response', {}).get('list_attached_group_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM group %s.', group_name) return [] def list_attached_role_policies(role_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'RoleName': role_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedRolePolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_role_policies_response', {}).get('list_attached_role_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM role %s.', role_name) return [] def create_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Create SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.create_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_saml_provider(saml_metadata_document, name) log.info('Successfully created %s SAML provider.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to create SAML provider %s.', name) return False def get_saml_provider_arn(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider_arn my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_saml_providers() for saml_provider in response.list_saml_providers_response.list_saml_providers_result.saml_provider_list: if saml_provider['arn'].endswith(':saml-provider/' + name): return saml_provider['arn'] return False except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to get ARN of SAML provider %s.', name) return False def delete_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Delete SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.delete_saml_provider my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return True conn.delete_saml_provider(saml_provider_arn) log.info('Successfully deleted SAML provider %s.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete SAML provider %s.', name) return False def list_saml_providers(region=None, key=None, keyid=None, profile=None): ''' List SAML providers. CLI Example: .. code-block:: bash salt myminion boto_iam.list_saml_providers ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: providers = [] info = conn.list_saml_providers() for arn in info['list_saml_providers_response']['list_saml_providers_result']['saml_provider_list']: providers.append(arn['arn'].rsplit('/', 1)[1]) return providers except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get list of SAML providers.') return False def get_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider document. CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider arn ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: provider = conn.get_saml_provider(name) return provider['get_saml_provider_response']['get_saml_provider_result']['saml_metadata_document'] except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get SAML provider document %s.', name) return False def update_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Update SAML provider. CLI Example: .. code-block:: bash salt myminion boto_iam.update_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return False if conn.update_saml_provider(name, saml_metadata_document): return True return False except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to update SAML provider %s.', name) return False
saltstack/salt
salt/modules/boto_iam.py
delete_group
python
def delete_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _group = get_group( group_name, region, key, keyid, profile ) if not _group: return True try: conn.delete_group(group_name) log.info('Successfully deleted IAM group %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM group %s.', group_name) return False
Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group mygroup
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iam.py#L715-L741
[ "def get_group(group_name, region=None, key=None, keyid=None, profile=None):\n '''\n Get group information.\n\n .. versionadded:: 2015.8.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_iam.get_group mygroup\n '''\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n try:\n info = conn.get_group(group_name, max_items=1)\n if not info:\n return False\n return info['get_group_response']['get_group_result']['group']\n except boto.exception.BotoServerError as e:\n log.debug(e)\n log.error('Failed to get IAM group %s info.', group_name)\n return False\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon IAM .. versionadded:: 2014.7.0 :configuration: This module accepts explicit iam 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 iam.keyid: GKTADJGHEIQSXMKKRBJ08H iam.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs iam.region: 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: boto ''' # keep lint from choking on _get_conn and _cache_id #pylint: disable=E0602 # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import salt libs from salt.ext import six import salt.utils.compat import salt.utils.json import salt.utils.odict as odict import salt.utils.versions from salt.exceptions import SaltInvocationError # Import third party libs # pylint: disable=unused-import from salt.ext.six.moves.urllib.parse import unquote as _unquote # pylint: disable=no-name-in-module try: import boto import boto.iam import boto3 import botocore logging.getLogger('boto').setLevel(logging.CRITICAL) logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=unused-import log = logging.getLogger(__name__) def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'iam', pack=__salt__) def instance_profile_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an instance profile exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: # Boto weirdly returns an exception here if an instance profile doesn't # exist. conn.get_instance_profile(name) return True except boto.exception.BotoServerError: return False def create_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Create an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.create_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if instance_profile_exists(name, region, key, keyid, profile): return True try: # This call returns an instance profile if successful and an exception # if not. It's annoying. conn.create_instance_profile(name) log.info('Created %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create %s instance profile.', name) return False return True def delete_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Delete an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not instance_profile_exists(name, region, key, keyid, profile): return True try: conn.delete_instance_profile(name) log.info('Deleted %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s instance profile.', name) return False return True def role_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an IAM role exists. CLI Example: .. code-block:: bash salt myminion boto_iam.role_exists myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_role(name) return True except boto.exception.BotoServerError: return False def describe_role(name, region=None, key=None, keyid=None, profile=None): ''' Get information for a role. CLI Example: .. code-block:: bash salt myminion boto_iam.describe_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_role(name) if not info: return False role = info.get_role_response.get_role_result.role role['assume_role_policy_document'] = salt.utils.json.loads(_unquote( role.assume_role_policy_document )) # If Sid wasn't defined by the user, boto will still return a Sid in # each policy. To properly check idempotently, let's remove the Sid # from the return if it's not actually set. for policy_key, policy in role['assume_role_policy_document'].items(): if policy_key == 'Statement': for val in policy: if 'Sid' in val and not val['Sid']: del val['Sid'] return role except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get %s information.', name) return False def create_user(user_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_user myuser ''' if not path: path = '/' if get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_user(user_name, path) log.info('Created IAM user : %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM user %s.', user_name) return False def get_all_access_keys(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all access keys from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_access_keys myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.get_all_access_keys(user_name, marker, max_items) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get access keys for IAM user %s.', user_name) return six.text_type(e) def create_access_key(user_name, region=None, key=None, keyid=None, profile=None): ''' Create access key id for a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.create_access_key(user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create access key.') return six.text_type(e) def delete_access_key(access_key_id, user_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete access key id from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_access_key(access_key_id, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete access key id %s.', access_key_id) return six.text_type(e) def delete_user(user_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user myuser ''' if not get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.delete_user(user_name) log.info('Deleted IAM user : %s .', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM user %s', user_name) return six.text_type(e) def get_user(user_name=None, region=None, key=None, keyid=None, profile=None): ''' Get user information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user(user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM user %s info.', user_name) return False def create_group(group_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_group group ''' if not path: path = '/' if get_group(group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_group(group_name, path) log.info('Created IAM group : %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM group %s.', group_name) return False def get_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group(group_name, max_items=1) if not info: return False return info['get_group_response']['get_group_result']['group'] except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_group_members(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: marker = None truncated = True users = [] while truncated: info = conn.get_group(group_name, marker=marker, max_items=1000) if not info: return False truncated = bool(info['get_group_response']['get_group_result']['is_truncated']) if truncated and 'marker' in info['get_group_response']['get_group_result']: marker = info['get_group_response']['get_group_result']['marker'] else: marker = None truncated = False users += info['get_group_response']['get_group_result']['users'] return users except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get members for IAM group %s.', group_name) return False def add_user_to_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Add user to group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.add_user_to_group myuser mygroup ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('Username : %s does not exist.', user_name) return False if user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.add_user_to_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add IAM user %s to group %s.', user_name, group_name) return False def user_exists_in_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Check if user exists in group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.user_exists_in_group myuser mygroup ''' # TODO this should probably use boto.iam.get_groups_for_user users = get_group_members( group_name=group_name, region=region, key=key, keyid=keyid, profile=profile ) if users: for _user in users: if user_name == _user['user_name']: log.debug('IAM user %s is already in IAM group %s.', user_name, group_name) return True return False def remove_user_from_group(group_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Remove user from group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.remove_user_from_group mygroup myuser ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist.', user_name) return False if not user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.remove_user_from_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove IAM user %s from group %s', user_name, group_name) return False def put_group_policy(group_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_group_policy mygroup policyname policyrules ''' group = get_group(group_name, region=region, key=key, keyid=keyid, profile=profile) if not group: log.error('Group %s does not exist', group_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_group_policy(group_name, policy_name, policy_json) if created: log.info('Created policy for IAM group %s.', group_name) return True log.error('Could not create policy for IAM group %s', group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy for IAM group %s', group_name) return False def delete_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group_policy mygroup mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_group_policy( group_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_group_policy(group_name, policy_name) log.info('Successfully deleted policy %s for IAM group %s.', policy_name, group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM group %s.', policy_name, group_name) return False def get_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group_policy mygroup policyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group_policy(group_name, policy_name) log.debug('info for group policy is : %s', info) if not info: return False info = info.get_group_policy_response.get_group_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_all_groups(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM group details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_groups ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _groups = conn.get_all_groups(path_prefix=path_prefix) groups = _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) while marker: _groups = conn.get_all_groups(path_prefix=path_prefix, marker=marker) groups = groups + _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) return groups def get_all_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.get_all_instance_profiles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) marker = False profiles = [] while marker is not None: marker = marker if marker else None p = conn.list_instance_profiles(path_prefix=path_prefix, marker=marker) res = p.list_instance_profiles_response.list_instance_profiles_result profiles += res.instance_profiles marker = getattr(res, 'marker', None) return profiles def list_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' List all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.list_instance_profiles ''' p = get_all_instance_profiles(path_prefix, region, key, keyid, profile) return [i['instance_profile_name'] for i in p] def get_all_group_policies(group_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a group. CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_group_policies mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False try: response = conn.get_all_group_policies(group_name) _list = response.list_group_policies_response.list_group_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def create_login_profile(user_name, password, region=None, key=None, keyid=None, profile=None): ''' Creates a login profile for the specified user, give the user the ability to access AWS services and the AWS Management Console. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_login_profile user_name password ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.create_login_profile(user_name, password) log.info('Created profile for IAM user %s.', user_name) return info except boto.exception.BotoServerError as e: log.debug(e) if 'Conflict' in e: log.info('Profile already exists for IAM user %s.', user_name) return 'Conflict' log.error('Failed to update profile for IAM user %s.', user_name) return False def delete_login_profile(user_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a login profile for the specified user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_login_profile user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.delete_login_profile(user_name) log.info('Deleted login profile for IAM user %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Login profile already deleted for IAM user %s.', user_name) return True log.error('Failed to delete login profile for IAM user %s.', user_name) return False def get_all_mfa_devices(user_name, region=None, key=None, keyid=None, profile=None): ''' Get all MFA devices associated with an IAM user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_mfa_devices user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: result = conn.get_all_mfa_devices(user_name) devices = result['list_mfa_devices_response']['list_mfa_devices_result']['mfa_devices'] return devices except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Could not find IAM user %s.', user_name) return [] log.error('Failed to get all MFA devices for IAM user %s.', user_name) return False def deactivate_mfa_device(user_name, serial, region=None, key=None, keyid=None, profile=None): ''' Deactivates the specified MFA device and removes it from association with the user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.deactivate_mfa_device user_name serial_num ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.deactivate_mfa_device(user_name, serial) log.info('Deactivated MFA device %s for IAM user %s.', serial, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('MFA device %s not associated with IAM user %s.', serial, user_name) return True log.error('Failed to deactivate MFA device %s for IAM user %s.', serial, user_name) return False def delete_virtual_mfa_device(serial, region=None, key=None, keyid=None, profile=None): ''' Deletes the specified virtual MFA device. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_virtual_mfa_device serial_num ''' conn = __utils__['boto3.get_connection_func']('iam')() try: conn.delete_virtual_mfa_device(SerialNumber=serial) log.info('Deleted virtual MFA device %s.', serial) return True except botocore.exceptions.ClientError as e: log.debug(e) if 'NoSuchEntity' in six.text_type(e): log.info('Virtual MFA device %s not found.', serial) return True log.error('Failed to delete virtual MFA device %s.', serial) return False def update_account_password_policy(allow_users_to_change_password=None, hard_expiry=None, max_password_age=None, minimum_password_length=None, password_reuse_prevention=None, require_lowercase_characters=None, require_numbers=None, require_symbols=None, require_uppercase_characters=None, region=None, key=None, keyid=None, profile=None): ''' Update the password policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_account_password_policy True ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.update_account_password_policy(allow_users_to_change_password, hard_expiry, max_password_age, minimum_password_length, password_reuse_prevention, require_lowercase_characters, require_numbers, require_symbols, require_uppercase_characters) log.info('The password policy has been updated.') return True except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy' log.error(msg) return False def get_account_policy(region=None, key=None, keyid=None, profile=None): ''' Get account policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_account_password_policy() return info.get_account_password_policy_response.get_account_password_policy_result.password_policy except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy.' log.error(msg) return False def create_role(name, policy_document=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Create an instance role. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if role_exists(name, region, key, keyid, profile): return True if not policy_document: policy_document = None try: conn.create_role(name, assume_role_policy_document=policy_document, path=path) log.info('Created IAM role %s.', name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to create IAM role %s.', name) return False def delete_role(name, region=None, key=None, keyid=None, profile=None): ''' Delete an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(name, region, key, keyid, profile): return True try: conn.delete_role(name) log.info('Deleted %s IAM role.', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s IAM role.', name) return False def profile_associated(role_name, profile_name, region, key, keyid, profile): ''' Check to see if an instance profile is associated with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.profile_associated myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # The IAM module of boto doesn't return objects. Instead you need to grab # values through its properties. Sigh. try: profiles = conn.list_instance_profiles_for_role(role_name) except boto.exception.BotoServerError as e: log.debug(e) return False profiles = profiles.list_instance_profiles_for_role_response profiles = profiles.list_instance_profiles_for_role_result profiles = profiles.instance_profiles for profile in profiles: if profile.instance_profile_name == profile_name: return True return False def associate_profile_to_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Associate an instance profile with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.associate_profile_to_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if associated: return True else: try: conn.add_role_to_instance_profile(profile_name, role_name) log.info('Added %s instance profile to IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add %s instance profile to IAM role %s', profile_name, role_name) return False def disassociate_profile_from_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Disassociate an instance profile from an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.disassociate_profile_from_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if not associated: return True else: try: conn.remove_role_from_instance_profile(profile_name, role_name) log.info('Removed %s instance profile from IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove %s instance profile from IAM role %s.', profile_name, role_name) return False def list_role_policies(role_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_role_policies myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_role_policies(role_name) _list = response.list_role_policies_response.list_role_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def get_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.get_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: _policy = conn.get_role_policy(role_name, policy_name) # I _hate_ you for not giving me an object boto. _policy = _policy.get_role_policy_response.policy_document # Policy is url encoded _policy = _unquote(_policy) _policy = salt.utils.json.loads(_policy, object_pairs_hook=odict.OrderedDict) return _policy except boto.exception.BotoServerError: return {} def create_role_policy(role_name, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Create or modify a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role_policy myirole mypolicy '{"MyPolicy": "Statement": [{"Action": ["sqs:*"], "Effect": "Allow", "Resource": ["arn:aws:sqs:*:*:*"], "Sid": "MyPolicySqs1"}]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) mode = 'create' if _policy: if _policy == policy: return True mode = 'modify' if isinstance(policy, six.string_types): policy = salt.utils.json.loads(policy, object_pairs_hook=odict.OrderedDict) try: _policy = salt.utils.json.dumps(policy) conn.put_role_policy(role_name, policy_name, _policy) if mode == 'create': msg = 'Successfully added policy %s to IAM role %s.' else: msg = 'Successfully modified policy %s for IAM role %s.' log.info(msg, policy_name, role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to %s policy %s for IAM role %s.', mode, policy_name, role_name) return False def delete_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) if not _policy: return True try: conn.delete_role_policy(role_name, policy_name) log.info('Successfully deleted policy %s for IAM role %s.', policy_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM role %s.', policy_name, role_name) return False def update_assume_role_policy(role_name, policy_document, region=None, key=None, keyid=None, profile=None): ''' Update an assume role policy for a role. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_assume_role_policy myrole '{"Statement":"..."}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(policy_document, six.string_types): policy_document = salt.utils.json.loads(policy_document, object_pairs_hook=odict.OrderedDict) try: _policy_document = salt.utils.json.dumps(policy_document) conn.update_assume_role_policy(role_name, _policy_document) log.info('Successfully updated assume role policy for IAM role %s.', role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to update assume role policy for IAM role %s.', role_name) return False def build_policy(region=None, key=None, keyid=None, profile=None): ''' Build a default assume role policy. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.build_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if hasattr(conn, 'build_policy'): policy = salt.utils.json.loads(conn.build_policy()) elif hasattr(conn, '_build_policy'): policy = salt.utils.json.loads(conn._build_policy()) else: return {} # The format we get from build_policy isn't going to be what we get back # from AWS for the exact same policy. AWS converts single item list values # into strings, so let's do the same here. for key, policy_val in policy.items(): for statement in policy_val: if (isinstance(statement['Action'], list) and len(statement['Action']) == 1): statement['Action'] = statement['Action'][0] if (isinstance(statement['Principal']['Service'], list) and len(statement['Principal']['Service']) == 1): statement['Principal']['Service'] = statement['Principal']['Service'][0] # build_policy doesn't add a version field, which AWS is going to set to a # default value, when we get it back, so let's set it. policy['Version'] = '2008-10-17' return policy def get_account_id(region=None, key=None, keyid=None, profile=None): ''' Get a the AWS account id associated with the used credentials. CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_id ''' cache_key = 'boto_iam.account_id' if cache_key not in __context__: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_user() # The get_user call returns an user ARN: # arn:aws:iam::027050522557:user/salt-test arn = ret['get_user_response']['get_user_result']['user']['arn'] account_id = arn.split(':')[4] except boto.exception.BotoServerError: # If call failed, then let's try to get the ARN from the metadata timeout = boto.config.getfloat( 'Boto', 'metadata_service_timeout', 1.0 ) attempts = boto.config.getint( 'Boto', 'metadata_service_num_attempts', 1 ) identity = boto.utils.get_instance_identity( timeout=timeout, num_retries=attempts ) try: account_id = identity['document']['accountId'] except KeyError: log.error('Failed to get account id from instance_identity in' ' boto_iam.get_account_id.') __context__[cache_key] = account_id return __context__[cache_key] def get_all_roles(path_prefix=None, region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM role details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_roles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _roles = conn.list_roles(path_prefix=path_prefix) roles = _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) while marker: _roles = conn.list_roles(path_prefix=path_prefix, marker=marker) roles = roles + _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) return roles def get_all_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM user details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_users ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _users = conn.get_all_users(path_prefix=path_prefix) users = _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) while marker: _users = conn.get_all_users(path_prefix=path_prefix, marker=marker) users = users + _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) return users def get_all_user_policies(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all user policies. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_user_policies myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_all_user_policies(user_name, marker, max_items) if not info: return False _list = info.list_user_policies_response.list_user_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policies for user %s.', user_name) return False def get_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user_policy myuser mypolicyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user_policy(user_name, policy_name) log.debug('Info for IAM user %s policy %s: %s.', user_name, policy_name, info) if not info: return False info = info.get_user_policy_response.get_user_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policy %s for IAM user %s.', policy_name, user_name) return False def put_user_policy(user_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_user_policy myuser policyname policyrules ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_user_policy(user_name, policy_name, policy_json) if created: log.info('Created policy %s for IAM user %s.', policy_name, user_name) return True log.error('Could not create policy %s for IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy %s for IAM user %s.', policy_name, user_name) return False def delete_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user_policy myuser mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_user_policy( user_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_user_policy(user_name, policy_name) log.info('Successfully deleted policy %s for IAM user %s.', policy_name, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM user %s.', policy_name, user_name) return False def upload_server_cert(cert_name, cert_body, private_key, cert_chain=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Upload a certificate to Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.upload_server_cert mycert_name crt priv_key :param cert_name: The name for the server certificate. Do not include the path in this value. :param cert_body: The contents of the public key certificate in PEM-encoded format. :param private_key: The contents of the private key in PEM-encoded format. :param cert_chain: The contents of the certificate chain. This is typically a concatenation of the PEM-encoded public key certificates of the chain. :param path: The path for the server certificate. :param region: The name of the region to connect to. :param key: The key to be used in order to connect :param keyid: The keyid to be used in order to connect :param profile: The profile that contains a dict of region, key, keyid :return: True / False ''' exists = get_server_certificate(cert_name, region, key, keyid, profile) if exists: return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.upload_server_cert(cert_name, cert_body, private_key, cert_chain) log.info('Created certificate %s.', cert_name) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to failed to create certificate %s.', cert_name) return False def list_server_certificates(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Lists the server certificates stored in IAM that have the specified path prefix. .. versionadded:: ??? :param path_prefix: The path prefix for filtering the results. For example: /company/servercerts would get all server certificates for which the path starts with /company/servercerts . This parameter is optional. If it is not included, it defaults to a slash (/), listing all server certificates. This parameter allows (per its regex pattern) a string of characters consisting of either a forward slash (/) by itself or a string that must begin and end with forward slashes. In addition, it can contain any ASCII character from the ! (u0021) through the DEL character (u007F), including most punctuation characters, digits, and upper and lowercased letters. CLI Example: .. code-block:: bash salt myminion boto_iam.list_server_certificates path_prefix=/somepath/ ''' retries = 10 sleep = 6 conn = __utils__['boto3.get_connection']('iam', region=region, key=key, keyid=keyid, profile=profile) Items = [] while retries: try: log.debug('Garnering list of IAM Server Certificates') IsTruncated = True while IsTruncated: kwargs = {'PathPrefix': path_prefix} ret = conn.list_server_certificates(**kwargs) Items += ret.get('ServerCertificateMetadataList', []) IsTruncated = ret.get('IsTruncated') kwargs.update({'Marker': ret.get('Marker')}) return Items except botocore.exceptions.ParamValidationError as err: raise SaltInvocationError(str(err)) except botocore.exceptions.ClientError as err: if retries and jmespath.search('Error.Code', err.response) == 'Throttling': retries -= 1 log.debug('Throttled by AWS API, retrying in %s seconds...', sleep) time.sleep(sleep) continue log.error('Failed to list IAM Server Certificates: %s', err.message) return None def get_server_certificate(cert_name, region=None, key=None, keyid=None, profile=None): ''' Returns certificate information from Amazon .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_server_certificate mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_server_certificate(cert_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get certificate %s information.', cert_name) return False def delete_server_cert(cert_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a certificate from Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_server_cert mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_server_cert(cert_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete certificate %s.', cert_name) return False def export_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM user details. Produces results that can be used to create an sls file. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.export_users --out=txt | sed "s/local: //" > iam_users.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() users = get_all_users(path_prefix, region, key, keyid, profile) for user in users: name = user.user_name _policies = conn.get_all_user_policies(name, max_items=100) _policies = _policies.list_user_policies_response.list_user_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_user_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_user_policy_response.get_user_policy_result.policy_document )) policies[policy_name] = _policy user_sls = [] user_sls.append({"name": name}) user_sls.append({"policies": policies}) user_sls.append({"path": user.path}) results["manage user " + name] = {"boto_iam.user_present": user_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def export_roles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM role details. Produces results that can be used to create an sls file. CLI Example: salt-call boto_iam.export_roles --out=txt | sed "s/local: //" > iam_roles.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() roles = get_all_roles(path_prefix, region, key, keyid, profile) for role in roles: name = role.role_name _policies = conn.list_role_policies(name, max_items=100) _policies = _policies.list_role_policies_response.list_role_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_role_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_role_policy_response.get_role_policy_result.policy_document )) policies[policy_name] = _policy role_sls = [] role_sls.append({"name": name}) role_sls.append({"policies": policies}) role_sls.append({'policy_document': salt.utils.json.loads(_unquote(role.assume_role_policy_document))}) role_sls.append({"path": role.path}) results["manage role " + name] = {"boto_iam_role.present": role_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def _get_policy_arn(name, region=None, key=None, keyid=None, profile=None): if name.startswith('arn:aws:iam:'): return name account_id = get_account_id( region=region, key=key, keyid=keyid, profile=profile ) return 'arn:aws:iam::{0}:policy/{1}'.format(account_id, name) def policy_exists(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return True except boto.exception.BotoServerError: return False def get_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return ret.get('get_policy_response', {}).get('get_policy_result', {}) except boto.exception.BotoServerError: return None def create_policy(policy_name, policy_document, path=None, description=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in 'path', 'description': if locals()[arg] is not None: params[arg] = locals()[arg] if policy_exists(policy_name, region, key, keyid, profile): return True try: conn.create_policy(policy_name, policy_document, **params) log.info('Created IAM policy %s.', policy_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s.', policy_name) return False return True def delete_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_exists(policy_arn, region, key, keyid, profile): return True try: conn.delete_policy(policy_arn) log.info('Deleted %s policy.', policy_name) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete %s policy: %s.', policy_name, aws.get('message')) return False return True def list_policies(region=None, key=None, keyid=None, profile=None): ''' List policies. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policies ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: policies = [] for ret in __utils__['boto.paged_call'](conn.list_policies): policies.append(ret.get('list_policies_response', {}).get('list_policies_result', {}).get('policies')) return policies except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to list policy versions.' log.error(msg) return [] def policy_version_exists(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.get_policy_version(policy_arn, version_id) return True except boto.exception.BotoServerError: return False def get_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy_version(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile), version_id) retval = ret.get('get_policy_version_response', {}).get('get_policy_version_result', {}).get('policy_version', {}) retval['document'] = _unquote(retval.get('document')) return {'policy_version': retval} except boto.exception.BotoServerError: return None def create_policy_version(policy_name, policy_document, set_as_default=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy version. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy_version mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in ('set_as_default',): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.create_policy_version(policy_arn, policy_document, **params) vid = ret.get('create_policy_version_response', {}).get('create_policy_version_result', {}).get('policy_version', {}).get('version_id') log.info('Created IAM policy %s version %s.', policy_name, vid) return {'created': True, 'version_id': vid} except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s version %s.', policy_name, vid) return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Delete a policy version. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_version_exists(policy_arn, version_id, region, key, keyid, profile): return True try: conn.delete_policy_version(policy_arn, version_id) log.info('Deleted IAM policy %s version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete IAM policy %s version %s: %s', policy_name, version_id, aws.get('message')) return False return True def list_policy_versions(policy_name, region=None, key=None, keyid=None, profile=None): ''' List versions of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policy_versions mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.list_policy_versions(policy_arn) return ret.get('list_policy_versions_response', {}).get('list_policy_versions_result', {}).get('versions') except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list versions for IAM policy %s.', policy_name) return [] def set_default_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Set the default version of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.set_default_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.set_default_policy_version(policy_arn, version_id) log.info('Set %s policy to version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to set %s policy to version %s: %s', policy_name, version_id, aws.get('message')) return False return True def attach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_user_policy(policy_arn, user_name) log.info('Attached policy %s to IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach %s policy to IAM user %s.', policy_name, user_name) return False return True def detach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_user_policy(policy_arn, user_name) log.info('Detached %s policy from IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach %s policy from IAM user %s.', policy_name, user_name) return False return True def attach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_group_policy(policy_arn, group_name) log.info('Attached policy %s to IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM group %s.', policy_name, group_name) return False return True def detach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_group_policy(policy_arn, group_name) log.info('Detached policy %s from IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM group %s.', policy_name, group_name) return False return True def attach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_role_policy(policy_arn, role_name) log.info('Attached policy %s to IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM role %s.', policy_name, role_name) return False return True def detach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_role_policy(policy_arn, role_name) log.info('Detached policy %s from IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM role %s.', policy_name, role_name) return False return True def list_entities_for_policy(policy_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities that a policy is attached to. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 params = {} for arg in ('path_prefix', 'entity_filter'): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) while retries: try: allret = { 'policy_groups': [], 'policy_users': [], 'policy_roles': [], } for ret in __utils__['boto.paged_call'](conn.list_entities_for_policy, policy_arn=policy_arn, **params): for k, v in six.iteritems(allret): v.extend(ret.get('list_entities_for_policy_response', {}).get('list_entities_for_policy_result', {}).get(k)) return allret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('Failed to list entities for IAM policy %s: %s', policy_name, e.message) return {} return {} def list_attached_user_policies(user_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given user. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'UserName': user_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedUserPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_user_policies_response', {}).get('list_attached_user_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM user %s.', user_name) return [] def list_attached_group_policies(group_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given group. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'GroupName': group_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedGroupPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_group_policies_response', {}).get('list_attached_group_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM group %s.', group_name) return [] def list_attached_role_policies(role_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'RoleName': role_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedRolePolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_role_policies_response', {}).get('list_attached_role_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM role %s.', role_name) return [] def create_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Create SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.create_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_saml_provider(saml_metadata_document, name) log.info('Successfully created %s SAML provider.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to create SAML provider %s.', name) return False def get_saml_provider_arn(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider_arn my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_saml_providers() for saml_provider in response.list_saml_providers_response.list_saml_providers_result.saml_provider_list: if saml_provider['arn'].endswith(':saml-provider/' + name): return saml_provider['arn'] return False except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to get ARN of SAML provider %s.', name) return False def delete_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Delete SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.delete_saml_provider my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return True conn.delete_saml_provider(saml_provider_arn) log.info('Successfully deleted SAML provider %s.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete SAML provider %s.', name) return False def list_saml_providers(region=None, key=None, keyid=None, profile=None): ''' List SAML providers. CLI Example: .. code-block:: bash salt myminion boto_iam.list_saml_providers ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: providers = [] info = conn.list_saml_providers() for arn in info['list_saml_providers_response']['list_saml_providers_result']['saml_provider_list']: providers.append(arn['arn'].rsplit('/', 1)[1]) return providers except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get list of SAML providers.') return False def get_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider document. CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider arn ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: provider = conn.get_saml_provider(name) return provider['get_saml_provider_response']['get_saml_provider_result']['saml_metadata_document'] except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get SAML provider document %s.', name) return False def update_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Update SAML provider. CLI Example: .. code-block:: bash salt myminion boto_iam.update_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return False if conn.update_saml_provider(name, saml_metadata_document): return True return False except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to update SAML provider %s.', name) return False
saltstack/salt
salt/modules/boto_iam.py
create_login_profile
python
def create_login_profile(user_name, password, region=None, key=None, keyid=None, profile=None): ''' Creates a login profile for the specified user, give the user the ability to access AWS services and the AWS Management Console. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_login_profile user_name password ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.create_login_profile(user_name, password) log.info('Created profile for IAM user %s.', user_name) return info except boto.exception.BotoServerError as e: log.debug(e) if 'Conflict' in e: log.info('Profile already exists for IAM user %s.', user_name) return 'Conflict' log.error('Failed to update profile for IAM user %s.', user_name) return False
Creates a login profile for the specified user, give the user the ability to access AWS services and the AWS Management Console. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_login_profile user_name password
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iam.py#L744-L773
[ "def get_user(user_name=None, region=None, key=None, keyid=None, profile=None):\n '''\n Get user information.\n\n .. versionadded:: 2015.8.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_iam.get_user myuser\n '''\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n try:\n info = conn.get_user(user_name)\n if not info:\n return False\n return info\n except boto.exception.BotoServerError as e:\n log.debug(e)\n log.error('Failed to get IAM user %s info.', user_name)\n return False\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon IAM .. versionadded:: 2014.7.0 :configuration: This module accepts explicit iam 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 iam.keyid: GKTADJGHEIQSXMKKRBJ08H iam.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs iam.region: 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: boto ''' # keep lint from choking on _get_conn and _cache_id #pylint: disable=E0602 # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import salt libs from salt.ext import six import salt.utils.compat import salt.utils.json import salt.utils.odict as odict import salt.utils.versions from salt.exceptions import SaltInvocationError # Import third party libs # pylint: disable=unused-import from salt.ext.six.moves.urllib.parse import unquote as _unquote # pylint: disable=no-name-in-module try: import boto import boto.iam import boto3 import botocore logging.getLogger('boto').setLevel(logging.CRITICAL) logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=unused-import log = logging.getLogger(__name__) def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'iam', pack=__salt__) def instance_profile_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an instance profile exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: # Boto weirdly returns an exception here if an instance profile doesn't # exist. conn.get_instance_profile(name) return True except boto.exception.BotoServerError: return False def create_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Create an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.create_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if instance_profile_exists(name, region, key, keyid, profile): return True try: # This call returns an instance profile if successful and an exception # if not. It's annoying. conn.create_instance_profile(name) log.info('Created %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create %s instance profile.', name) return False return True def delete_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Delete an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not instance_profile_exists(name, region, key, keyid, profile): return True try: conn.delete_instance_profile(name) log.info('Deleted %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s instance profile.', name) return False return True def role_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an IAM role exists. CLI Example: .. code-block:: bash salt myminion boto_iam.role_exists myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_role(name) return True except boto.exception.BotoServerError: return False def describe_role(name, region=None, key=None, keyid=None, profile=None): ''' Get information for a role. CLI Example: .. code-block:: bash salt myminion boto_iam.describe_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_role(name) if not info: return False role = info.get_role_response.get_role_result.role role['assume_role_policy_document'] = salt.utils.json.loads(_unquote( role.assume_role_policy_document )) # If Sid wasn't defined by the user, boto will still return a Sid in # each policy. To properly check idempotently, let's remove the Sid # from the return if it's not actually set. for policy_key, policy in role['assume_role_policy_document'].items(): if policy_key == 'Statement': for val in policy: if 'Sid' in val and not val['Sid']: del val['Sid'] return role except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get %s information.', name) return False def create_user(user_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_user myuser ''' if not path: path = '/' if get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_user(user_name, path) log.info('Created IAM user : %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM user %s.', user_name) return False def get_all_access_keys(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all access keys from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_access_keys myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.get_all_access_keys(user_name, marker, max_items) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get access keys for IAM user %s.', user_name) return six.text_type(e) def create_access_key(user_name, region=None, key=None, keyid=None, profile=None): ''' Create access key id for a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.create_access_key(user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create access key.') return six.text_type(e) def delete_access_key(access_key_id, user_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete access key id from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_access_key(access_key_id, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete access key id %s.', access_key_id) return six.text_type(e) def delete_user(user_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user myuser ''' if not get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.delete_user(user_name) log.info('Deleted IAM user : %s .', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM user %s', user_name) return six.text_type(e) def get_user(user_name=None, region=None, key=None, keyid=None, profile=None): ''' Get user information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user(user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM user %s info.', user_name) return False def create_group(group_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_group group ''' if not path: path = '/' if get_group(group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_group(group_name, path) log.info('Created IAM group : %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM group %s.', group_name) return False def get_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group(group_name, max_items=1) if not info: return False return info['get_group_response']['get_group_result']['group'] except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_group_members(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: marker = None truncated = True users = [] while truncated: info = conn.get_group(group_name, marker=marker, max_items=1000) if not info: return False truncated = bool(info['get_group_response']['get_group_result']['is_truncated']) if truncated and 'marker' in info['get_group_response']['get_group_result']: marker = info['get_group_response']['get_group_result']['marker'] else: marker = None truncated = False users += info['get_group_response']['get_group_result']['users'] return users except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get members for IAM group %s.', group_name) return False def add_user_to_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Add user to group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.add_user_to_group myuser mygroup ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('Username : %s does not exist.', user_name) return False if user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.add_user_to_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add IAM user %s to group %s.', user_name, group_name) return False def user_exists_in_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Check if user exists in group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.user_exists_in_group myuser mygroup ''' # TODO this should probably use boto.iam.get_groups_for_user users = get_group_members( group_name=group_name, region=region, key=key, keyid=keyid, profile=profile ) if users: for _user in users: if user_name == _user['user_name']: log.debug('IAM user %s is already in IAM group %s.', user_name, group_name) return True return False def remove_user_from_group(group_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Remove user from group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.remove_user_from_group mygroup myuser ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist.', user_name) return False if not user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.remove_user_from_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove IAM user %s from group %s', user_name, group_name) return False def put_group_policy(group_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_group_policy mygroup policyname policyrules ''' group = get_group(group_name, region=region, key=key, keyid=keyid, profile=profile) if not group: log.error('Group %s does not exist', group_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_group_policy(group_name, policy_name, policy_json) if created: log.info('Created policy for IAM group %s.', group_name) return True log.error('Could not create policy for IAM group %s', group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy for IAM group %s', group_name) return False def delete_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group_policy mygroup mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_group_policy( group_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_group_policy(group_name, policy_name) log.info('Successfully deleted policy %s for IAM group %s.', policy_name, group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM group %s.', policy_name, group_name) return False def get_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group_policy mygroup policyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group_policy(group_name, policy_name) log.debug('info for group policy is : %s', info) if not info: return False info = info.get_group_policy_response.get_group_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_all_groups(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM group details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_groups ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _groups = conn.get_all_groups(path_prefix=path_prefix) groups = _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) while marker: _groups = conn.get_all_groups(path_prefix=path_prefix, marker=marker) groups = groups + _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) return groups def get_all_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.get_all_instance_profiles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) marker = False profiles = [] while marker is not None: marker = marker if marker else None p = conn.list_instance_profiles(path_prefix=path_prefix, marker=marker) res = p.list_instance_profiles_response.list_instance_profiles_result profiles += res.instance_profiles marker = getattr(res, 'marker', None) return profiles def list_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' List all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.list_instance_profiles ''' p = get_all_instance_profiles(path_prefix, region, key, keyid, profile) return [i['instance_profile_name'] for i in p] def get_all_group_policies(group_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a group. CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_group_policies mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False try: response = conn.get_all_group_policies(group_name) _list = response.list_group_policies_response.list_group_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def delete_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _group = get_group( group_name, region, key, keyid, profile ) if not _group: return True try: conn.delete_group(group_name) log.info('Successfully deleted IAM group %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM group %s.', group_name) return False def delete_login_profile(user_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a login profile for the specified user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_login_profile user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.delete_login_profile(user_name) log.info('Deleted login profile for IAM user %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Login profile already deleted for IAM user %s.', user_name) return True log.error('Failed to delete login profile for IAM user %s.', user_name) return False def get_all_mfa_devices(user_name, region=None, key=None, keyid=None, profile=None): ''' Get all MFA devices associated with an IAM user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_mfa_devices user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: result = conn.get_all_mfa_devices(user_name) devices = result['list_mfa_devices_response']['list_mfa_devices_result']['mfa_devices'] return devices except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Could not find IAM user %s.', user_name) return [] log.error('Failed to get all MFA devices for IAM user %s.', user_name) return False def deactivate_mfa_device(user_name, serial, region=None, key=None, keyid=None, profile=None): ''' Deactivates the specified MFA device and removes it from association with the user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.deactivate_mfa_device user_name serial_num ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.deactivate_mfa_device(user_name, serial) log.info('Deactivated MFA device %s for IAM user %s.', serial, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('MFA device %s not associated with IAM user %s.', serial, user_name) return True log.error('Failed to deactivate MFA device %s for IAM user %s.', serial, user_name) return False def delete_virtual_mfa_device(serial, region=None, key=None, keyid=None, profile=None): ''' Deletes the specified virtual MFA device. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_virtual_mfa_device serial_num ''' conn = __utils__['boto3.get_connection_func']('iam')() try: conn.delete_virtual_mfa_device(SerialNumber=serial) log.info('Deleted virtual MFA device %s.', serial) return True except botocore.exceptions.ClientError as e: log.debug(e) if 'NoSuchEntity' in six.text_type(e): log.info('Virtual MFA device %s not found.', serial) return True log.error('Failed to delete virtual MFA device %s.', serial) return False def update_account_password_policy(allow_users_to_change_password=None, hard_expiry=None, max_password_age=None, minimum_password_length=None, password_reuse_prevention=None, require_lowercase_characters=None, require_numbers=None, require_symbols=None, require_uppercase_characters=None, region=None, key=None, keyid=None, profile=None): ''' Update the password policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_account_password_policy True ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.update_account_password_policy(allow_users_to_change_password, hard_expiry, max_password_age, minimum_password_length, password_reuse_prevention, require_lowercase_characters, require_numbers, require_symbols, require_uppercase_characters) log.info('The password policy has been updated.') return True except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy' log.error(msg) return False def get_account_policy(region=None, key=None, keyid=None, profile=None): ''' Get account policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_account_password_policy() return info.get_account_password_policy_response.get_account_password_policy_result.password_policy except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy.' log.error(msg) return False def create_role(name, policy_document=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Create an instance role. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if role_exists(name, region, key, keyid, profile): return True if not policy_document: policy_document = None try: conn.create_role(name, assume_role_policy_document=policy_document, path=path) log.info('Created IAM role %s.', name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to create IAM role %s.', name) return False def delete_role(name, region=None, key=None, keyid=None, profile=None): ''' Delete an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(name, region, key, keyid, profile): return True try: conn.delete_role(name) log.info('Deleted %s IAM role.', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s IAM role.', name) return False def profile_associated(role_name, profile_name, region, key, keyid, profile): ''' Check to see if an instance profile is associated with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.profile_associated myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # The IAM module of boto doesn't return objects. Instead you need to grab # values through its properties. Sigh. try: profiles = conn.list_instance_profiles_for_role(role_name) except boto.exception.BotoServerError as e: log.debug(e) return False profiles = profiles.list_instance_profiles_for_role_response profiles = profiles.list_instance_profiles_for_role_result profiles = profiles.instance_profiles for profile in profiles: if profile.instance_profile_name == profile_name: return True return False def associate_profile_to_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Associate an instance profile with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.associate_profile_to_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if associated: return True else: try: conn.add_role_to_instance_profile(profile_name, role_name) log.info('Added %s instance profile to IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add %s instance profile to IAM role %s', profile_name, role_name) return False def disassociate_profile_from_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Disassociate an instance profile from an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.disassociate_profile_from_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if not associated: return True else: try: conn.remove_role_from_instance_profile(profile_name, role_name) log.info('Removed %s instance profile from IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove %s instance profile from IAM role %s.', profile_name, role_name) return False def list_role_policies(role_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_role_policies myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_role_policies(role_name) _list = response.list_role_policies_response.list_role_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def get_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.get_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: _policy = conn.get_role_policy(role_name, policy_name) # I _hate_ you for not giving me an object boto. _policy = _policy.get_role_policy_response.policy_document # Policy is url encoded _policy = _unquote(_policy) _policy = salt.utils.json.loads(_policy, object_pairs_hook=odict.OrderedDict) return _policy except boto.exception.BotoServerError: return {} def create_role_policy(role_name, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Create or modify a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role_policy myirole mypolicy '{"MyPolicy": "Statement": [{"Action": ["sqs:*"], "Effect": "Allow", "Resource": ["arn:aws:sqs:*:*:*"], "Sid": "MyPolicySqs1"}]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) mode = 'create' if _policy: if _policy == policy: return True mode = 'modify' if isinstance(policy, six.string_types): policy = salt.utils.json.loads(policy, object_pairs_hook=odict.OrderedDict) try: _policy = salt.utils.json.dumps(policy) conn.put_role_policy(role_name, policy_name, _policy) if mode == 'create': msg = 'Successfully added policy %s to IAM role %s.' else: msg = 'Successfully modified policy %s for IAM role %s.' log.info(msg, policy_name, role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to %s policy %s for IAM role %s.', mode, policy_name, role_name) return False def delete_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) if not _policy: return True try: conn.delete_role_policy(role_name, policy_name) log.info('Successfully deleted policy %s for IAM role %s.', policy_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM role %s.', policy_name, role_name) return False def update_assume_role_policy(role_name, policy_document, region=None, key=None, keyid=None, profile=None): ''' Update an assume role policy for a role. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_assume_role_policy myrole '{"Statement":"..."}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(policy_document, six.string_types): policy_document = salt.utils.json.loads(policy_document, object_pairs_hook=odict.OrderedDict) try: _policy_document = salt.utils.json.dumps(policy_document) conn.update_assume_role_policy(role_name, _policy_document) log.info('Successfully updated assume role policy for IAM role %s.', role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to update assume role policy for IAM role %s.', role_name) return False def build_policy(region=None, key=None, keyid=None, profile=None): ''' Build a default assume role policy. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.build_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if hasattr(conn, 'build_policy'): policy = salt.utils.json.loads(conn.build_policy()) elif hasattr(conn, '_build_policy'): policy = salt.utils.json.loads(conn._build_policy()) else: return {} # The format we get from build_policy isn't going to be what we get back # from AWS for the exact same policy. AWS converts single item list values # into strings, so let's do the same here. for key, policy_val in policy.items(): for statement in policy_val: if (isinstance(statement['Action'], list) and len(statement['Action']) == 1): statement['Action'] = statement['Action'][0] if (isinstance(statement['Principal']['Service'], list) and len(statement['Principal']['Service']) == 1): statement['Principal']['Service'] = statement['Principal']['Service'][0] # build_policy doesn't add a version field, which AWS is going to set to a # default value, when we get it back, so let's set it. policy['Version'] = '2008-10-17' return policy def get_account_id(region=None, key=None, keyid=None, profile=None): ''' Get a the AWS account id associated with the used credentials. CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_id ''' cache_key = 'boto_iam.account_id' if cache_key not in __context__: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_user() # The get_user call returns an user ARN: # arn:aws:iam::027050522557:user/salt-test arn = ret['get_user_response']['get_user_result']['user']['arn'] account_id = arn.split(':')[4] except boto.exception.BotoServerError: # If call failed, then let's try to get the ARN from the metadata timeout = boto.config.getfloat( 'Boto', 'metadata_service_timeout', 1.0 ) attempts = boto.config.getint( 'Boto', 'metadata_service_num_attempts', 1 ) identity = boto.utils.get_instance_identity( timeout=timeout, num_retries=attempts ) try: account_id = identity['document']['accountId'] except KeyError: log.error('Failed to get account id from instance_identity in' ' boto_iam.get_account_id.') __context__[cache_key] = account_id return __context__[cache_key] def get_all_roles(path_prefix=None, region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM role details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_roles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _roles = conn.list_roles(path_prefix=path_prefix) roles = _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) while marker: _roles = conn.list_roles(path_prefix=path_prefix, marker=marker) roles = roles + _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) return roles def get_all_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM user details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_users ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _users = conn.get_all_users(path_prefix=path_prefix) users = _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) while marker: _users = conn.get_all_users(path_prefix=path_prefix, marker=marker) users = users + _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) return users def get_all_user_policies(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all user policies. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_user_policies myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_all_user_policies(user_name, marker, max_items) if not info: return False _list = info.list_user_policies_response.list_user_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policies for user %s.', user_name) return False def get_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user_policy myuser mypolicyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user_policy(user_name, policy_name) log.debug('Info for IAM user %s policy %s: %s.', user_name, policy_name, info) if not info: return False info = info.get_user_policy_response.get_user_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policy %s for IAM user %s.', policy_name, user_name) return False def put_user_policy(user_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_user_policy myuser policyname policyrules ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_user_policy(user_name, policy_name, policy_json) if created: log.info('Created policy %s for IAM user %s.', policy_name, user_name) return True log.error('Could not create policy %s for IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy %s for IAM user %s.', policy_name, user_name) return False def delete_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user_policy myuser mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_user_policy( user_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_user_policy(user_name, policy_name) log.info('Successfully deleted policy %s for IAM user %s.', policy_name, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM user %s.', policy_name, user_name) return False def upload_server_cert(cert_name, cert_body, private_key, cert_chain=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Upload a certificate to Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.upload_server_cert mycert_name crt priv_key :param cert_name: The name for the server certificate. Do not include the path in this value. :param cert_body: The contents of the public key certificate in PEM-encoded format. :param private_key: The contents of the private key in PEM-encoded format. :param cert_chain: The contents of the certificate chain. This is typically a concatenation of the PEM-encoded public key certificates of the chain. :param path: The path for the server certificate. :param region: The name of the region to connect to. :param key: The key to be used in order to connect :param keyid: The keyid to be used in order to connect :param profile: The profile that contains a dict of region, key, keyid :return: True / False ''' exists = get_server_certificate(cert_name, region, key, keyid, profile) if exists: return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.upload_server_cert(cert_name, cert_body, private_key, cert_chain) log.info('Created certificate %s.', cert_name) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to failed to create certificate %s.', cert_name) return False def list_server_certificates(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Lists the server certificates stored in IAM that have the specified path prefix. .. versionadded:: ??? :param path_prefix: The path prefix for filtering the results. For example: /company/servercerts would get all server certificates for which the path starts with /company/servercerts . This parameter is optional. If it is not included, it defaults to a slash (/), listing all server certificates. This parameter allows (per its regex pattern) a string of characters consisting of either a forward slash (/) by itself or a string that must begin and end with forward slashes. In addition, it can contain any ASCII character from the ! (u0021) through the DEL character (u007F), including most punctuation characters, digits, and upper and lowercased letters. CLI Example: .. code-block:: bash salt myminion boto_iam.list_server_certificates path_prefix=/somepath/ ''' retries = 10 sleep = 6 conn = __utils__['boto3.get_connection']('iam', region=region, key=key, keyid=keyid, profile=profile) Items = [] while retries: try: log.debug('Garnering list of IAM Server Certificates') IsTruncated = True while IsTruncated: kwargs = {'PathPrefix': path_prefix} ret = conn.list_server_certificates(**kwargs) Items += ret.get('ServerCertificateMetadataList', []) IsTruncated = ret.get('IsTruncated') kwargs.update({'Marker': ret.get('Marker')}) return Items except botocore.exceptions.ParamValidationError as err: raise SaltInvocationError(str(err)) except botocore.exceptions.ClientError as err: if retries and jmespath.search('Error.Code', err.response) == 'Throttling': retries -= 1 log.debug('Throttled by AWS API, retrying in %s seconds...', sleep) time.sleep(sleep) continue log.error('Failed to list IAM Server Certificates: %s', err.message) return None def get_server_certificate(cert_name, region=None, key=None, keyid=None, profile=None): ''' Returns certificate information from Amazon .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_server_certificate mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_server_certificate(cert_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get certificate %s information.', cert_name) return False def delete_server_cert(cert_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a certificate from Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_server_cert mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_server_cert(cert_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete certificate %s.', cert_name) return False def export_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM user details. Produces results that can be used to create an sls file. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.export_users --out=txt | sed "s/local: //" > iam_users.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() users = get_all_users(path_prefix, region, key, keyid, profile) for user in users: name = user.user_name _policies = conn.get_all_user_policies(name, max_items=100) _policies = _policies.list_user_policies_response.list_user_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_user_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_user_policy_response.get_user_policy_result.policy_document )) policies[policy_name] = _policy user_sls = [] user_sls.append({"name": name}) user_sls.append({"policies": policies}) user_sls.append({"path": user.path}) results["manage user " + name] = {"boto_iam.user_present": user_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def export_roles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM role details. Produces results that can be used to create an sls file. CLI Example: salt-call boto_iam.export_roles --out=txt | sed "s/local: //" > iam_roles.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() roles = get_all_roles(path_prefix, region, key, keyid, profile) for role in roles: name = role.role_name _policies = conn.list_role_policies(name, max_items=100) _policies = _policies.list_role_policies_response.list_role_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_role_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_role_policy_response.get_role_policy_result.policy_document )) policies[policy_name] = _policy role_sls = [] role_sls.append({"name": name}) role_sls.append({"policies": policies}) role_sls.append({'policy_document': salt.utils.json.loads(_unquote(role.assume_role_policy_document))}) role_sls.append({"path": role.path}) results["manage role " + name] = {"boto_iam_role.present": role_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def _get_policy_arn(name, region=None, key=None, keyid=None, profile=None): if name.startswith('arn:aws:iam:'): return name account_id = get_account_id( region=region, key=key, keyid=keyid, profile=profile ) return 'arn:aws:iam::{0}:policy/{1}'.format(account_id, name) def policy_exists(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return True except boto.exception.BotoServerError: return False def get_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return ret.get('get_policy_response', {}).get('get_policy_result', {}) except boto.exception.BotoServerError: return None def create_policy(policy_name, policy_document, path=None, description=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in 'path', 'description': if locals()[arg] is not None: params[arg] = locals()[arg] if policy_exists(policy_name, region, key, keyid, profile): return True try: conn.create_policy(policy_name, policy_document, **params) log.info('Created IAM policy %s.', policy_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s.', policy_name) return False return True def delete_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_exists(policy_arn, region, key, keyid, profile): return True try: conn.delete_policy(policy_arn) log.info('Deleted %s policy.', policy_name) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete %s policy: %s.', policy_name, aws.get('message')) return False return True def list_policies(region=None, key=None, keyid=None, profile=None): ''' List policies. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policies ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: policies = [] for ret in __utils__['boto.paged_call'](conn.list_policies): policies.append(ret.get('list_policies_response', {}).get('list_policies_result', {}).get('policies')) return policies except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to list policy versions.' log.error(msg) return [] def policy_version_exists(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.get_policy_version(policy_arn, version_id) return True except boto.exception.BotoServerError: return False def get_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy_version(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile), version_id) retval = ret.get('get_policy_version_response', {}).get('get_policy_version_result', {}).get('policy_version', {}) retval['document'] = _unquote(retval.get('document')) return {'policy_version': retval} except boto.exception.BotoServerError: return None def create_policy_version(policy_name, policy_document, set_as_default=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy version. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy_version mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in ('set_as_default',): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.create_policy_version(policy_arn, policy_document, **params) vid = ret.get('create_policy_version_response', {}).get('create_policy_version_result', {}).get('policy_version', {}).get('version_id') log.info('Created IAM policy %s version %s.', policy_name, vid) return {'created': True, 'version_id': vid} except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s version %s.', policy_name, vid) return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Delete a policy version. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_version_exists(policy_arn, version_id, region, key, keyid, profile): return True try: conn.delete_policy_version(policy_arn, version_id) log.info('Deleted IAM policy %s version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete IAM policy %s version %s: %s', policy_name, version_id, aws.get('message')) return False return True def list_policy_versions(policy_name, region=None, key=None, keyid=None, profile=None): ''' List versions of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policy_versions mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.list_policy_versions(policy_arn) return ret.get('list_policy_versions_response', {}).get('list_policy_versions_result', {}).get('versions') except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list versions for IAM policy %s.', policy_name) return [] def set_default_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Set the default version of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.set_default_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.set_default_policy_version(policy_arn, version_id) log.info('Set %s policy to version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to set %s policy to version %s: %s', policy_name, version_id, aws.get('message')) return False return True def attach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_user_policy(policy_arn, user_name) log.info('Attached policy %s to IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach %s policy to IAM user %s.', policy_name, user_name) return False return True def detach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_user_policy(policy_arn, user_name) log.info('Detached %s policy from IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach %s policy from IAM user %s.', policy_name, user_name) return False return True def attach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_group_policy(policy_arn, group_name) log.info('Attached policy %s to IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM group %s.', policy_name, group_name) return False return True def detach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_group_policy(policy_arn, group_name) log.info('Detached policy %s from IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM group %s.', policy_name, group_name) return False return True def attach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_role_policy(policy_arn, role_name) log.info('Attached policy %s to IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM role %s.', policy_name, role_name) return False return True def detach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_role_policy(policy_arn, role_name) log.info('Detached policy %s from IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM role %s.', policy_name, role_name) return False return True def list_entities_for_policy(policy_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities that a policy is attached to. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 params = {} for arg in ('path_prefix', 'entity_filter'): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) while retries: try: allret = { 'policy_groups': [], 'policy_users': [], 'policy_roles': [], } for ret in __utils__['boto.paged_call'](conn.list_entities_for_policy, policy_arn=policy_arn, **params): for k, v in six.iteritems(allret): v.extend(ret.get('list_entities_for_policy_response', {}).get('list_entities_for_policy_result', {}).get(k)) return allret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('Failed to list entities for IAM policy %s: %s', policy_name, e.message) return {} return {} def list_attached_user_policies(user_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given user. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'UserName': user_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedUserPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_user_policies_response', {}).get('list_attached_user_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM user %s.', user_name) return [] def list_attached_group_policies(group_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given group. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'GroupName': group_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedGroupPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_group_policies_response', {}).get('list_attached_group_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM group %s.', group_name) return [] def list_attached_role_policies(role_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'RoleName': role_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedRolePolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_role_policies_response', {}).get('list_attached_role_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM role %s.', role_name) return [] def create_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Create SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.create_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_saml_provider(saml_metadata_document, name) log.info('Successfully created %s SAML provider.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to create SAML provider %s.', name) return False def get_saml_provider_arn(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider_arn my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_saml_providers() for saml_provider in response.list_saml_providers_response.list_saml_providers_result.saml_provider_list: if saml_provider['arn'].endswith(':saml-provider/' + name): return saml_provider['arn'] return False except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to get ARN of SAML provider %s.', name) return False def delete_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Delete SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.delete_saml_provider my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return True conn.delete_saml_provider(saml_provider_arn) log.info('Successfully deleted SAML provider %s.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete SAML provider %s.', name) return False def list_saml_providers(region=None, key=None, keyid=None, profile=None): ''' List SAML providers. CLI Example: .. code-block:: bash salt myminion boto_iam.list_saml_providers ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: providers = [] info = conn.list_saml_providers() for arn in info['list_saml_providers_response']['list_saml_providers_result']['saml_provider_list']: providers.append(arn['arn'].rsplit('/', 1)[1]) return providers except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get list of SAML providers.') return False def get_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider document. CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider arn ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: provider = conn.get_saml_provider(name) return provider['get_saml_provider_response']['get_saml_provider_result']['saml_metadata_document'] except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get SAML provider document %s.', name) return False def update_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Update SAML provider. CLI Example: .. code-block:: bash salt myminion boto_iam.update_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return False if conn.update_saml_provider(name, saml_metadata_document): return True return False except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to update SAML provider %s.', name) return False
saltstack/salt
salt/modules/boto_iam.py
get_all_mfa_devices
python
def get_all_mfa_devices(user_name, region=None, key=None, keyid=None, profile=None): ''' Get all MFA devices associated with an IAM user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_mfa_devices user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: result = conn.get_all_mfa_devices(user_name) devices = result['list_mfa_devices_response']['list_mfa_devices_result']['mfa_devices'] return devices except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Could not find IAM user %s.', user_name) return [] log.error('Failed to get all MFA devices for IAM user %s.', user_name) return False
Get all MFA devices associated with an IAM user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_mfa_devices user_name
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iam.py#L807-L835
[ "def get_user(user_name=None, region=None, key=None, keyid=None, profile=None):\n '''\n Get user information.\n\n .. versionadded:: 2015.8.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_iam.get_user myuser\n '''\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n try:\n info = conn.get_user(user_name)\n if not info:\n return False\n return info\n except boto.exception.BotoServerError as e:\n log.debug(e)\n log.error('Failed to get IAM user %s info.', user_name)\n return False\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon IAM .. versionadded:: 2014.7.0 :configuration: This module accepts explicit iam 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 iam.keyid: GKTADJGHEIQSXMKKRBJ08H iam.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs iam.region: 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: boto ''' # keep lint from choking on _get_conn and _cache_id #pylint: disable=E0602 # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import salt libs from salt.ext import six import salt.utils.compat import salt.utils.json import salt.utils.odict as odict import salt.utils.versions from salt.exceptions import SaltInvocationError # Import third party libs # pylint: disable=unused-import from salt.ext.six.moves.urllib.parse import unquote as _unquote # pylint: disable=no-name-in-module try: import boto import boto.iam import boto3 import botocore logging.getLogger('boto').setLevel(logging.CRITICAL) logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=unused-import log = logging.getLogger(__name__) def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'iam', pack=__salt__) def instance_profile_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an instance profile exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: # Boto weirdly returns an exception here if an instance profile doesn't # exist. conn.get_instance_profile(name) return True except boto.exception.BotoServerError: return False def create_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Create an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.create_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if instance_profile_exists(name, region, key, keyid, profile): return True try: # This call returns an instance profile if successful and an exception # if not. It's annoying. conn.create_instance_profile(name) log.info('Created %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create %s instance profile.', name) return False return True def delete_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Delete an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not instance_profile_exists(name, region, key, keyid, profile): return True try: conn.delete_instance_profile(name) log.info('Deleted %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s instance profile.', name) return False return True def role_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an IAM role exists. CLI Example: .. code-block:: bash salt myminion boto_iam.role_exists myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_role(name) return True except boto.exception.BotoServerError: return False def describe_role(name, region=None, key=None, keyid=None, profile=None): ''' Get information for a role. CLI Example: .. code-block:: bash salt myminion boto_iam.describe_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_role(name) if not info: return False role = info.get_role_response.get_role_result.role role['assume_role_policy_document'] = salt.utils.json.loads(_unquote( role.assume_role_policy_document )) # If Sid wasn't defined by the user, boto will still return a Sid in # each policy. To properly check idempotently, let's remove the Sid # from the return if it's not actually set. for policy_key, policy in role['assume_role_policy_document'].items(): if policy_key == 'Statement': for val in policy: if 'Sid' in val and not val['Sid']: del val['Sid'] return role except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get %s information.', name) return False def create_user(user_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_user myuser ''' if not path: path = '/' if get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_user(user_name, path) log.info('Created IAM user : %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM user %s.', user_name) return False def get_all_access_keys(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all access keys from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_access_keys myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.get_all_access_keys(user_name, marker, max_items) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get access keys for IAM user %s.', user_name) return six.text_type(e) def create_access_key(user_name, region=None, key=None, keyid=None, profile=None): ''' Create access key id for a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.create_access_key(user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create access key.') return six.text_type(e) def delete_access_key(access_key_id, user_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete access key id from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_access_key(access_key_id, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete access key id %s.', access_key_id) return six.text_type(e) def delete_user(user_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user myuser ''' if not get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.delete_user(user_name) log.info('Deleted IAM user : %s .', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM user %s', user_name) return six.text_type(e) def get_user(user_name=None, region=None, key=None, keyid=None, profile=None): ''' Get user information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user(user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM user %s info.', user_name) return False def create_group(group_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_group group ''' if not path: path = '/' if get_group(group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_group(group_name, path) log.info('Created IAM group : %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM group %s.', group_name) return False def get_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group(group_name, max_items=1) if not info: return False return info['get_group_response']['get_group_result']['group'] except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_group_members(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: marker = None truncated = True users = [] while truncated: info = conn.get_group(group_name, marker=marker, max_items=1000) if not info: return False truncated = bool(info['get_group_response']['get_group_result']['is_truncated']) if truncated and 'marker' in info['get_group_response']['get_group_result']: marker = info['get_group_response']['get_group_result']['marker'] else: marker = None truncated = False users += info['get_group_response']['get_group_result']['users'] return users except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get members for IAM group %s.', group_name) return False def add_user_to_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Add user to group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.add_user_to_group myuser mygroup ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('Username : %s does not exist.', user_name) return False if user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.add_user_to_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add IAM user %s to group %s.', user_name, group_name) return False def user_exists_in_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Check if user exists in group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.user_exists_in_group myuser mygroup ''' # TODO this should probably use boto.iam.get_groups_for_user users = get_group_members( group_name=group_name, region=region, key=key, keyid=keyid, profile=profile ) if users: for _user in users: if user_name == _user['user_name']: log.debug('IAM user %s is already in IAM group %s.', user_name, group_name) return True return False def remove_user_from_group(group_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Remove user from group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.remove_user_from_group mygroup myuser ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist.', user_name) return False if not user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.remove_user_from_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove IAM user %s from group %s', user_name, group_name) return False def put_group_policy(group_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_group_policy mygroup policyname policyrules ''' group = get_group(group_name, region=region, key=key, keyid=keyid, profile=profile) if not group: log.error('Group %s does not exist', group_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_group_policy(group_name, policy_name, policy_json) if created: log.info('Created policy for IAM group %s.', group_name) return True log.error('Could not create policy for IAM group %s', group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy for IAM group %s', group_name) return False def delete_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group_policy mygroup mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_group_policy( group_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_group_policy(group_name, policy_name) log.info('Successfully deleted policy %s for IAM group %s.', policy_name, group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM group %s.', policy_name, group_name) return False def get_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group_policy mygroup policyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group_policy(group_name, policy_name) log.debug('info for group policy is : %s', info) if not info: return False info = info.get_group_policy_response.get_group_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_all_groups(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM group details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_groups ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _groups = conn.get_all_groups(path_prefix=path_prefix) groups = _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) while marker: _groups = conn.get_all_groups(path_prefix=path_prefix, marker=marker) groups = groups + _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) return groups def get_all_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.get_all_instance_profiles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) marker = False profiles = [] while marker is not None: marker = marker if marker else None p = conn.list_instance_profiles(path_prefix=path_prefix, marker=marker) res = p.list_instance_profiles_response.list_instance_profiles_result profiles += res.instance_profiles marker = getattr(res, 'marker', None) return profiles def list_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' List all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.list_instance_profiles ''' p = get_all_instance_profiles(path_prefix, region, key, keyid, profile) return [i['instance_profile_name'] for i in p] def get_all_group_policies(group_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a group. CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_group_policies mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False try: response = conn.get_all_group_policies(group_name) _list = response.list_group_policies_response.list_group_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def delete_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _group = get_group( group_name, region, key, keyid, profile ) if not _group: return True try: conn.delete_group(group_name) log.info('Successfully deleted IAM group %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM group %s.', group_name) return False def create_login_profile(user_name, password, region=None, key=None, keyid=None, profile=None): ''' Creates a login profile for the specified user, give the user the ability to access AWS services and the AWS Management Console. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_login_profile user_name password ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.create_login_profile(user_name, password) log.info('Created profile for IAM user %s.', user_name) return info except boto.exception.BotoServerError as e: log.debug(e) if 'Conflict' in e: log.info('Profile already exists for IAM user %s.', user_name) return 'Conflict' log.error('Failed to update profile for IAM user %s.', user_name) return False def delete_login_profile(user_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a login profile for the specified user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_login_profile user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.delete_login_profile(user_name) log.info('Deleted login profile for IAM user %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Login profile already deleted for IAM user %s.', user_name) return True log.error('Failed to delete login profile for IAM user %s.', user_name) return False def deactivate_mfa_device(user_name, serial, region=None, key=None, keyid=None, profile=None): ''' Deactivates the specified MFA device and removes it from association with the user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.deactivate_mfa_device user_name serial_num ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.deactivate_mfa_device(user_name, serial) log.info('Deactivated MFA device %s for IAM user %s.', serial, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('MFA device %s not associated with IAM user %s.', serial, user_name) return True log.error('Failed to deactivate MFA device %s for IAM user %s.', serial, user_name) return False def delete_virtual_mfa_device(serial, region=None, key=None, keyid=None, profile=None): ''' Deletes the specified virtual MFA device. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_virtual_mfa_device serial_num ''' conn = __utils__['boto3.get_connection_func']('iam')() try: conn.delete_virtual_mfa_device(SerialNumber=serial) log.info('Deleted virtual MFA device %s.', serial) return True except botocore.exceptions.ClientError as e: log.debug(e) if 'NoSuchEntity' in six.text_type(e): log.info('Virtual MFA device %s not found.', serial) return True log.error('Failed to delete virtual MFA device %s.', serial) return False def update_account_password_policy(allow_users_to_change_password=None, hard_expiry=None, max_password_age=None, minimum_password_length=None, password_reuse_prevention=None, require_lowercase_characters=None, require_numbers=None, require_symbols=None, require_uppercase_characters=None, region=None, key=None, keyid=None, profile=None): ''' Update the password policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_account_password_policy True ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.update_account_password_policy(allow_users_to_change_password, hard_expiry, max_password_age, minimum_password_length, password_reuse_prevention, require_lowercase_characters, require_numbers, require_symbols, require_uppercase_characters) log.info('The password policy has been updated.') return True except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy' log.error(msg) return False def get_account_policy(region=None, key=None, keyid=None, profile=None): ''' Get account policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_account_password_policy() return info.get_account_password_policy_response.get_account_password_policy_result.password_policy except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy.' log.error(msg) return False def create_role(name, policy_document=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Create an instance role. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if role_exists(name, region, key, keyid, profile): return True if not policy_document: policy_document = None try: conn.create_role(name, assume_role_policy_document=policy_document, path=path) log.info('Created IAM role %s.', name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to create IAM role %s.', name) return False def delete_role(name, region=None, key=None, keyid=None, profile=None): ''' Delete an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(name, region, key, keyid, profile): return True try: conn.delete_role(name) log.info('Deleted %s IAM role.', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s IAM role.', name) return False def profile_associated(role_name, profile_name, region, key, keyid, profile): ''' Check to see if an instance profile is associated with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.profile_associated myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # The IAM module of boto doesn't return objects. Instead you need to grab # values through its properties. Sigh. try: profiles = conn.list_instance_profiles_for_role(role_name) except boto.exception.BotoServerError as e: log.debug(e) return False profiles = profiles.list_instance_profiles_for_role_response profiles = profiles.list_instance_profiles_for_role_result profiles = profiles.instance_profiles for profile in profiles: if profile.instance_profile_name == profile_name: return True return False def associate_profile_to_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Associate an instance profile with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.associate_profile_to_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if associated: return True else: try: conn.add_role_to_instance_profile(profile_name, role_name) log.info('Added %s instance profile to IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add %s instance profile to IAM role %s', profile_name, role_name) return False def disassociate_profile_from_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Disassociate an instance profile from an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.disassociate_profile_from_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if not associated: return True else: try: conn.remove_role_from_instance_profile(profile_name, role_name) log.info('Removed %s instance profile from IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove %s instance profile from IAM role %s.', profile_name, role_name) return False def list_role_policies(role_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_role_policies myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_role_policies(role_name) _list = response.list_role_policies_response.list_role_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def get_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.get_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: _policy = conn.get_role_policy(role_name, policy_name) # I _hate_ you for not giving me an object boto. _policy = _policy.get_role_policy_response.policy_document # Policy is url encoded _policy = _unquote(_policy) _policy = salt.utils.json.loads(_policy, object_pairs_hook=odict.OrderedDict) return _policy except boto.exception.BotoServerError: return {} def create_role_policy(role_name, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Create or modify a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role_policy myirole mypolicy '{"MyPolicy": "Statement": [{"Action": ["sqs:*"], "Effect": "Allow", "Resource": ["arn:aws:sqs:*:*:*"], "Sid": "MyPolicySqs1"}]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) mode = 'create' if _policy: if _policy == policy: return True mode = 'modify' if isinstance(policy, six.string_types): policy = salt.utils.json.loads(policy, object_pairs_hook=odict.OrderedDict) try: _policy = salt.utils.json.dumps(policy) conn.put_role_policy(role_name, policy_name, _policy) if mode == 'create': msg = 'Successfully added policy %s to IAM role %s.' else: msg = 'Successfully modified policy %s for IAM role %s.' log.info(msg, policy_name, role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to %s policy %s for IAM role %s.', mode, policy_name, role_name) return False def delete_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) if not _policy: return True try: conn.delete_role_policy(role_name, policy_name) log.info('Successfully deleted policy %s for IAM role %s.', policy_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM role %s.', policy_name, role_name) return False def update_assume_role_policy(role_name, policy_document, region=None, key=None, keyid=None, profile=None): ''' Update an assume role policy for a role. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_assume_role_policy myrole '{"Statement":"..."}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(policy_document, six.string_types): policy_document = salt.utils.json.loads(policy_document, object_pairs_hook=odict.OrderedDict) try: _policy_document = salt.utils.json.dumps(policy_document) conn.update_assume_role_policy(role_name, _policy_document) log.info('Successfully updated assume role policy for IAM role %s.', role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to update assume role policy for IAM role %s.', role_name) return False def build_policy(region=None, key=None, keyid=None, profile=None): ''' Build a default assume role policy. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.build_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if hasattr(conn, 'build_policy'): policy = salt.utils.json.loads(conn.build_policy()) elif hasattr(conn, '_build_policy'): policy = salt.utils.json.loads(conn._build_policy()) else: return {} # The format we get from build_policy isn't going to be what we get back # from AWS for the exact same policy. AWS converts single item list values # into strings, so let's do the same here. for key, policy_val in policy.items(): for statement in policy_val: if (isinstance(statement['Action'], list) and len(statement['Action']) == 1): statement['Action'] = statement['Action'][0] if (isinstance(statement['Principal']['Service'], list) and len(statement['Principal']['Service']) == 1): statement['Principal']['Service'] = statement['Principal']['Service'][0] # build_policy doesn't add a version field, which AWS is going to set to a # default value, when we get it back, so let's set it. policy['Version'] = '2008-10-17' return policy def get_account_id(region=None, key=None, keyid=None, profile=None): ''' Get a the AWS account id associated with the used credentials. CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_id ''' cache_key = 'boto_iam.account_id' if cache_key not in __context__: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_user() # The get_user call returns an user ARN: # arn:aws:iam::027050522557:user/salt-test arn = ret['get_user_response']['get_user_result']['user']['arn'] account_id = arn.split(':')[4] except boto.exception.BotoServerError: # If call failed, then let's try to get the ARN from the metadata timeout = boto.config.getfloat( 'Boto', 'metadata_service_timeout', 1.0 ) attempts = boto.config.getint( 'Boto', 'metadata_service_num_attempts', 1 ) identity = boto.utils.get_instance_identity( timeout=timeout, num_retries=attempts ) try: account_id = identity['document']['accountId'] except KeyError: log.error('Failed to get account id from instance_identity in' ' boto_iam.get_account_id.') __context__[cache_key] = account_id return __context__[cache_key] def get_all_roles(path_prefix=None, region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM role details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_roles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _roles = conn.list_roles(path_prefix=path_prefix) roles = _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) while marker: _roles = conn.list_roles(path_prefix=path_prefix, marker=marker) roles = roles + _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) return roles def get_all_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM user details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_users ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _users = conn.get_all_users(path_prefix=path_prefix) users = _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) while marker: _users = conn.get_all_users(path_prefix=path_prefix, marker=marker) users = users + _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) return users def get_all_user_policies(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all user policies. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_user_policies myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_all_user_policies(user_name, marker, max_items) if not info: return False _list = info.list_user_policies_response.list_user_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policies for user %s.', user_name) return False def get_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user_policy myuser mypolicyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user_policy(user_name, policy_name) log.debug('Info for IAM user %s policy %s: %s.', user_name, policy_name, info) if not info: return False info = info.get_user_policy_response.get_user_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policy %s for IAM user %s.', policy_name, user_name) return False def put_user_policy(user_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_user_policy myuser policyname policyrules ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_user_policy(user_name, policy_name, policy_json) if created: log.info('Created policy %s for IAM user %s.', policy_name, user_name) return True log.error('Could not create policy %s for IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy %s for IAM user %s.', policy_name, user_name) return False def delete_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user_policy myuser mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_user_policy( user_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_user_policy(user_name, policy_name) log.info('Successfully deleted policy %s for IAM user %s.', policy_name, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM user %s.', policy_name, user_name) return False def upload_server_cert(cert_name, cert_body, private_key, cert_chain=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Upload a certificate to Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.upload_server_cert mycert_name crt priv_key :param cert_name: The name for the server certificate. Do not include the path in this value. :param cert_body: The contents of the public key certificate in PEM-encoded format. :param private_key: The contents of the private key in PEM-encoded format. :param cert_chain: The contents of the certificate chain. This is typically a concatenation of the PEM-encoded public key certificates of the chain. :param path: The path for the server certificate. :param region: The name of the region to connect to. :param key: The key to be used in order to connect :param keyid: The keyid to be used in order to connect :param profile: The profile that contains a dict of region, key, keyid :return: True / False ''' exists = get_server_certificate(cert_name, region, key, keyid, profile) if exists: return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.upload_server_cert(cert_name, cert_body, private_key, cert_chain) log.info('Created certificate %s.', cert_name) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to failed to create certificate %s.', cert_name) return False def list_server_certificates(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Lists the server certificates stored in IAM that have the specified path prefix. .. versionadded:: ??? :param path_prefix: The path prefix for filtering the results. For example: /company/servercerts would get all server certificates for which the path starts with /company/servercerts . This parameter is optional. If it is not included, it defaults to a slash (/), listing all server certificates. This parameter allows (per its regex pattern) a string of characters consisting of either a forward slash (/) by itself or a string that must begin and end with forward slashes. In addition, it can contain any ASCII character from the ! (u0021) through the DEL character (u007F), including most punctuation characters, digits, and upper and lowercased letters. CLI Example: .. code-block:: bash salt myminion boto_iam.list_server_certificates path_prefix=/somepath/ ''' retries = 10 sleep = 6 conn = __utils__['boto3.get_connection']('iam', region=region, key=key, keyid=keyid, profile=profile) Items = [] while retries: try: log.debug('Garnering list of IAM Server Certificates') IsTruncated = True while IsTruncated: kwargs = {'PathPrefix': path_prefix} ret = conn.list_server_certificates(**kwargs) Items += ret.get('ServerCertificateMetadataList', []) IsTruncated = ret.get('IsTruncated') kwargs.update({'Marker': ret.get('Marker')}) return Items except botocore.exceptions.ParamValidationError as err: raise SaltInvocationError(str(err)) except botocore.exceptions.ClientError as err: if retries and jmespath.search('Error.Code', err.response) == 'Throttling': retries -= 1 log.debug('Throttled by AWS API, retrying in %s seconds...', sleep) time.sleep(sleep) continue log.error('Failed to list IAM Server Certificates: %s', err.message) return None def get_server_certificate(cert_name, region=None, key=None, keyid=None, profile=None): ''' Returns certificate information from Amazon .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_server_certificate mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_server_certificate(cert_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get certificate %s information.', cert_name) return False def delete_server_cert(cert_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a certificate from Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_server_cert mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_server_cert(cert_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete certificate %s.', cert_name) return False def export_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM user details. Produces results that can be used to create an sls file. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.export_users --out=txt | sed "s/local: //" > iam_users.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() users = get_all_users(path_prefix, region, key, keyid, profile) for user in users: name = user.user_name _policies = conn.get_all_user_policies(name, max_items=100) _policies = _policies.list_user_policies_response.list_user_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_user_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_user_policy_response.get_user_policy_result.policy_document )) policies[policy_name] = _policy user_sls = [] user_sls.append({"name": name}) user_sls.append({"policies": policies}) user_sls.append({"path": user.path}) results["manage user " + name] = {"boto_iam.user_present": user_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def export_roles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM role details. Produces results that can be used to create an sls file. CLI Example: salt-call boto_iam.export_roles --out=txt | sed "s/local: //" > iam_roles.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() roles = get_all_roles(path_prefix, region, key, keyid, profile) for role in roles: name = role.role_name _policies = conn.list_role_policies(name, max_items=100) _policies = _policies.list_role_policies_response.list_role_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_role_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_role_policy_response.get_role_policy_result.policy_document )) policies[policy_name] = _policy role_sls = [] role_sls.append({"name": name}) role_sls.append({"policies": policies}) role_sls.append({'policy_document': salt.utils.json.loads(_unquote(role.assume_role_policy_document))}) role_sls.append({"path": role.path}) results["manage role " + name] = {"boto_iam_role.present": role_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def _get_policy_arn(name, region=None, key=None, keyid=None, profile=None): if name.startswith('arn:aws:iam:'): return name account_id = get_account_id( region=region, key=key, keyid=keyid, profile=profile ) return 'arn:aws:iam::{0}:policy/{1}'.format(account_id, name) def policy_exists(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return True except boto.exception.BotoServerError: return False def get_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return ret.get('get_policy_response', {}).get('get_policy_result', {}) except boto.exception.BotoServerError: return None def create_policy(policy_name, policy_document, path=None, description=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in 'path', 'description': if locals()[arg] is not None: params[arg] = locals()[arg] if policy_exists(policy_name, region, key, keyid, profile): return True try: conn.create_policy(policy_name, policy_document, **params) log.info('Created IAM policy %s.', policy_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s.', policy_name) return False return True def delete_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_exists(policy_arn, region, key, keyid, profile): return True try: conn.delete_policy(policy_arn) log.info('Deleted %s policy.', policy_name) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete %s policy: %s.', policy_name, aws.get('message')) return False return True def list_policies(region=None, key=None, keyid=None, profile=None): ''' List policies. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policies ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: policies = [] for ret in __utils__['boto.paged_call'](conn.list_policies): policies.append(ret.get('list_policies_response', {}).get('list_policies_result', {}).get('policies')) return policies except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to list policy versions.' log.error(msg) return [] def policy_version_exists(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.get_policy_version(policy_arn, version_id) return True except boto.exception.BotoServerError: return False def get_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy_version(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile), version_id) retval = ret.get('get_policy_version_response', {}).get('get_policy_version_result', {}).get('policy_version', {}) retval['document'] = _unquote(retval.get('document')) return {'policy_version': retval} except boto.exception.BotoServerError: return None def create_policy_version(policy_name, policy_document, set_as_default=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy version. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy_version mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in ('set_as_default',): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.create_policy_version(policy_arn, policy_document, **params) vid = ret.get('create_policy_version_response', {}).get('create_policy_version_result', {}).get('policy_version', {}).get('version_id') log.info('Created IAM policy %s version %s.', policy_name, vid) return {'created': True, 'version_id': vid} except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s version %s.', policy_name, vid) return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Delete a policy version. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_version_exists(policy_arn, version_id, region, key, keyid, profile): return True try: conn.delete_policy_version(policy_arn, version_id) log.info('Deleted IAM policy %s version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete IAM policy %s version %s: %s', policy_name, version_id, aws.get('message')) return False return True def list_policy_versions(policy_name, region=None, key=None, keyid=None, profile=None): ''' List versions of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policy_versions mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.list_policy_versions(policy_arn) return ret.get('list_policy_versions_response', {}).get('list_policy_versions_result', {}).get('versions') except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list versions for IAM policy %s.', policy_name) return [] def set_default_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Set the default version of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.set_default_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.set_default_policy_version(policy_arn, version_id) log.info('Set %s policy to version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to set %s policy to version %s: %s', policy_name, version_id, aws.get('message')) return False return True def attach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_user_policy(policy_arn, user_name) log.info('Attached policy %s to IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach %s policy to IAM user %s.', policy_name, user_name) return False return True def detach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_user_policy(policy_arn, user_name) log.info('Detached %s policy from IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach %s policy from IAM user %s.', policy_name, user_name) return False return True def attach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_group_policy(policy_arn, group_name) log.info('Attached policy %s to IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM group %s.', policy_name, group_name) return False return True def detach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_group_policy(policy_arn, group_name) log.info('Detached policy %s from IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM group %s.', policy_name, group_name) return False return True def attach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_role_policy(policy_arn, role_name) log.info('Attached policy %s to IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM role %s.', policy_name, role_name) return False return True def detach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_role_policy(policy_arn, role_name) log.info('Detached policy %s from IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM role %s.', policy_name, role_name) return False return True def list_entities_for_policy(policy_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities that a policy is attached to. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 params = {} for arg in ('path_prefix', 'entity_filter'): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) while retries: try: allret = { 'policy_groups': [], 'policy_users': [], 'policy_roles': [], } for ret in __utils__['boto.paged_call'](conn.list_entities_for_policy, policy_arn=policy_arn, **params): for k, v in six.iteritems(allret): v.extend(ret.get('list_entities_for_policy_response', {}).get('list_entities_for_policy_result', {}).get(k)) return allret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('Failed to list entities for IAM policy %s: %s', policy_name, e.message) return {} return {} def list_attached_user_policies(user_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given user. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'UserName': user_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedUserPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_user_policies_response', {}).get('list_attached_user_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM user %s.', user_name) return [] def list_attached_group_policies(group_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given group. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'GroupName': group_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedGroupPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_group_policies_response', {}).get('list_attached_group_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM group %s.', group_name) return [] def list_attached_role_policies(role_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'RoleName': role_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedRolePolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_role_policies_response', {}).get('list_attached_role_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM role %s.', role_name) return [] def create_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Create SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.create_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_saml_provider(saml_metadata_document, name) log.info('Successfully created %s SAML provider.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to create SAML provider %s.', name) return False def get_saml_provider_arn(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider_arn my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_saml_providers() for saml_provider in response.list_saml_providers_response.list_saml_providers_result.saml_provider_list: if saml_provider['arn'].endswith(':saml-provider/' + name): return saml_provider['arn'] return False except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to get ARN of SAML provider %s.', name) return False def delete_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Delete SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.delete_saml_provider my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return True conn.delete_saml_provider(saml_provider_arn) log.info('Successfully deleted SAML provider %s.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete SAML provider %s.', name) return False def list_saml_providers(region=None, key=None, keyid=None, profile=None): ''' List SAML providers. CLI Example: .. code-block:: bash salt myminion boto_iam.list_saml_providers ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: providers = [] info = conn.list_saml_providers() for arn in info['list_saml_providers_response']['list_saml_providers_result']['saml_provider_list']: providers.append(arn['arn'].rsplit('/', 1)[1]) return providers except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get list of SAML providers.') return False def get_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider document. CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider arn ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: provider = conn.get_saml_provider(name) return provider['get_saml_provider_response']['get_saml_provider_result']['saml_metadata_document'] except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get SAML provider document %s.', name) return False def update_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Update SAML provider. CLI Example: .. code-block:: bash salt myminion boto_iam.update_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return False if conn.update_saml_provider(name, saml_metadata_document): return True return False except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to update SAML provider %s.', name) return False
saltstack/salt
salt/modules/boto_iam.py
delete_virtual_mfa_device
python
def delete_virtual_mfa_device(serial, region=None, key=None, keyid=None, profile=None): ''' Deletes the specified virtual MFA device. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_virtual_mfa_device serial_num ''' conn = __utils__['boto3.get_connection_func']('iam')() try: conn.delete_virtual_mfa_device(SerialNumber=serial) log.info('Deleted virtual MFA device %s.', serial) return True except botocore.exceptions.ClientError as e: log.debug(e) if 'NoSuchEntity' in six.text_type(e): log.info('Virtual MFA device %s not found.', serial) return True log.error('Failed to delete virtual MFA device %s.', serial) return False
Deletes the specified virtual MFA device. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_virtual_mfa_device serial_num
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iam.py#L870-L891
null
# -*- coding: utf-8 -*- ''' Connection module for Amazon IAM .. versionadded:: 2014.7.0 :configuration: This module accepts explicit iam 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 iam.keyid: GKTADJGHEIQSXMKKRBJ08H iam.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs iam.region: 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: boto ''' # keep lint from choking on _get_conn and _cache_id #pylint: disable=E0602 # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import salt libs from salt.ext import six import salt.utils.compat import salt.utils.json import salt.utils.odict as odict import salt.utils.versions from salt.exceptions import SaltInvocationError # Import third party libs # pylint: disable=unused-import from salt.ext.six.moves.urllib.parse import unquote as _unquote # pylint: disable=no-name-in-module try: import boto import boto.iam import boto3 import botocore logging.getLogger('boto').setLevel(logging.CRITICAL) logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=unused-import log = logging.getLogger(__name__) def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'iam', pack=__salt__) def instance_profile_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an instance profile exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: # Boto weirdly returns an exception here if an instance profile doesn't # exist. conn.get_instance_profile(name) return True except boto.exception.BotoServerError: return False def create_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Create an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.create_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if instance_profile_exists(name, region, key, keyid, profile): return True try: # This call returns an instance profile if successful and an exception # if not. It's annoying. conn.create_instance_profile(name) log.info('Created %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create %s instance profile.', name) return False return True def delete_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Delete an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not instance_profile_exists(name, region, key, keyid, profile): return True try: conn.delete_instance_profile(name) log.info('Deleted %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s instance profile.', name) return False return True def role_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an IAM role exists. CLI Example: .. code-block:: bash salt myminion boto_iam.role_exists myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_role(name) return True except boto.exception.BotoServerError: return False def describe_role(name, region=None, key=None, keyid=None, profile=None): ''' Get information for a role. CLI Example: .. code-block:: bash salt myminion boto_iam.describe_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_role(name) if not info: return False role = info.get_role_response.get_role_result.role role['assume_role_policy_document'] = salt.utils.json.loads(_unquote( role.assume_role_policy_document )) # If Sid wasn't defined by the user, boto will still return a Sid in # each policy. To properly check idempotently, let's remove the Sid # from the return if it's not actually set. for policy_key, policy in role['assume_role_policy_document'].items(): if policy_key == 'Statement': for val in policy: if 'Sid' in val and not val['Sid']: del val['Sid'] return role except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get %s information.', name) return False def create_user(user_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_user myuser ''' if not path: path = '/' if get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_user(user_name, path) log.info('Created IAM user : %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM user %s.', user_name) return False def get_all_access_keys(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all access keys from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_access_keys myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.get_all_access_keys(user_name, marker, max_items) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get access keys for IAM user %s.', user_name) return six.text_type(e) def create_access_key(user_name, region=None, key=None, keyid=None, profile=None): ''' Create access key id for a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.create_access_key(user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create access key.') return six.text_type(e) def delete_access_key(access_key_id, user_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete access key id from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_access_key(access_key_id, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete access key id %s.', access_key_id) return six.text_type(e) def delete_user(user_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user myuser ''' if not get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.delete_user(user_name) log.info('Deleted IAM user : %s .', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM user %s', user_name) return six.text_type(e) def get_user(user_name=None, region=None, key=None, keyid=None, profile=None): ''' Get user information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user(user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM user %s info.', user_name) return False def create_group(group_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_group group ''' if not path: path = '/' if get_group(group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_group(group_name, path) log.info('Created IAM group : %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM group %s.', group_name) return False def get_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group(group_name, max_items=1) if not info: return False return info['get_group_response']['get_group_result']['group'] except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_group_members(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: marker = None truncated = True users = [] while truncated: info = conn.get_group(group_name, marker=marker, max_items=1000) if not info: return False truncated = bool(info['get_group_response']['get_group_result']['is_truncated']) if truncated and 'marker' in info['get_group_response']['get_group_result']: marker = info['get_group_response']['get_group_result']['marker'] else: marker = None truncated = False users += info['get_group_response']['get_group_result']['users'] return users except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get members for IAM group %s.', group_name) return False def add_user_to_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Add user to group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.add_user_to_group myuser mygroup ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('Username : %s does not exist.', user_name) return False if user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.add_user_to_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add IAM user %s to group %s.', user_name, group_name) return False def user_exists_in_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Check if user exists in group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.user_exists_in_group myuser mygroup ''' # TODO this should probably use boto.iam.get_groups_for_user users = get_group_members( group_name=group_name, region=region, key=key, keyid=keyid, profile=profile ) if users: for _user in users: if user_name == _user['user_name']: log.debug('IAM user %s is already in IAM group %s.', user_name, group_name) return True return False def remove_user_from_group(group_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Remove user from group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.remove_user_from_group mygroup myuser ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist.', user_name) return False if not user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.remove_user_from_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove IAM user %s from group %s', user_name, group_name) return False def put_group_policy(group_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_group_policy mygroup policyname policyrules ''' group = get_group(group_name, region=region, key=key, keyid=keyid, profile=profile) if not group: log.error('Group %s does not exist', group_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_group_policy(group_name, policy_name, policy_json) if created: log.info('Created policy for IAM group %s.', group_name) return True log.error('Could not create policy for IAM group %s', group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy for IAM group %s', group_name) return False def delete_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group_policy mygroup mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_group_policy( group_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_group_policy(group_name, policy_name) log.info('Successfully deleted policy %s for IAM group %s.', policy_name, group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM group %s.', policy_name, group_name) return False def get_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group_policy mygroup policyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group_policy(group_name, policy_name) log.debug('info for group policy is : %s', info) if not info: return False info = info.get_group_policy_response.get_group_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_all_groups(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM group details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_groups ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _groups = conn.get_all_groups(path_prefix=path_prefix) groups = _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) while marker: _groups = conn.get_all_groups(path_prefix=path_prefix, marker=marker) groups = groups + _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) return groups def get_all_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.get_all_instance_profiles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) marker = False profiles = [] while marker is not None: marker = marker if marker else None p = conn.list_instance_profiles(path_prefix=path_prefix, marker=marker) res = p.list_instance_profiles_response.list_instance_profiles_result profiles += res.instance_profiles marker = getattr(res, 'marker', None) return profiles def list_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' List all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.list_instance_profiles ''' p = get_all_instance_profiles(path_prefix, region, key, keyid, profile) return [i['instance_profile_name'] for i in p] def get_all_group_policies(group_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a group. CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_group_policies mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False try: response = conn.get_all_group_policies(group_name) _list = response.list_group_policies_response.list_group_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def delete_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _group = get_group( group_name, region, key, keyid, profile ) if not _group: return True try: conn.delete_group(group_name) log.info('Successfully deleted IAM group %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM group %s.', group_name) return False def create_login_profile(user_name, password, region=None, key=None, keyid=None, profile=None): ''' Creates a login profile for the specified user, give the user the ability to access AWS services and the AWS Management Console. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_login_profile user_name password ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.create_login_profile(user_name, password) log.info('Created profile for IAM user %s.', user_name) return info except boto.exception.BotoServerError as e: log.debug(e) if 'Conflict' in e: log.info('Profile already exists for IAM user %s.', user_name) return 'Conflict' log.error('Failed to update profile for IAM user %s.', user_name) return False def delete_login_profile(user_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a login profile for the specified user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_login_profile user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.delete_login_profile(user_name) log.info('Deleted login profile for IAM user %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Login profile already deleted for IAM user %s.', user_name) return True log.error('Failed to delete login profile for IAM user %s.', user_name) return False def get_all_mfa_devices(user_name, region=None, key=None, keyid=None, profile=None): ''' Get all MFA devices associated with an IAM user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_mfa_devices user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: result = conn.get_all_mfa_devices(user_name) devices = result['list_mfa_devices_response']['list_mfa_devices_result']['mfa_devices'] return devices except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Could not find IAM user %s.', user_name) return [] log.error('Failed to get all MFA devices for IAM user %s.', user_name) return False def deactivate_mfa_device(user_name, serial, region=None, key=None, keyid=None, profile=None): ''' Deactivates the specified MFA device and removes it from association with the user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.deactivate_mfa_device user_name serial_num ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.deactivate_mfa_device(user_name, serial) log.info('Deactivated MFA device %s for IAM user %s.', serial, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('MFA device %s not associated with IAM user %s.', serial, user_name) return True log.error('Failed to deactivate MFA device %s for IAM user %s.', serial, user_name) return False def update_account_password_policy(allow_users_to_change_password=None, hard_expiry=None, max_password_age=None, minimum_password_length=None, password_reuse_prevention=None, require_lowercase_characters=None, require_numbers=None, require_symbols=None, require_uppercase_characters=None, region=None, key=None, keyid=None, profile=None): ''' Update the password policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_account_password_policy True ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.update_account_password_policy(allow_users_to_change_password, hard_expiry, max_password_age, minimum_password_length, password_reuse_prevention, require_lowercase_characters, require_numbers, require_symbols, require_uppercase_characters) log.info('The password policy has been updated.') return True except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy' log.error(msg) return False def get_account_policy(region=None, key=None, keyid=None, profile=None): ''' Get account policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_account_password_policy() return info.get_account_password_policy_response.get_account_password_policy_result.password_policy except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy.' log.error(msg) return False def create_role(name, policy_document=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Create an instance role. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if role_exists(name, region, key, keyid, profile): return True if not policy_document: policy_document = None try: conn.create_role(name, assume_role_policy_document=policy_document, path=path) log.info('Created IAM role %s.', name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to create IAM role %s.', name) return False def delete_role(name, region=None, key=None, keyid=None, profile=None): ''' Delete an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(name, region, key, keyid, profile): return True try: conn.delete_role(name) log.info('Deleted %s IAM role.', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s IAM role.', name) return False def profile_associated(role_name, profile_name, region, key, keyid, profile): ''' Check to see if an instance profile is associated with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.profile_associated myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # The IAM module of boto doesn't return objects. Instead you need to grab # values through its properties. Sigh. try: profiles = conn.list_instance_profiles_for_role(role_name) except boto.exception.BotoServerError as e: log.debug(e) return False profiles = profiles.list_instance_profiles_for_role_response profiles = profiles.list_instance_profiles_for_role_result profiles = profiles.instance_profiles for profile in profiles: if profile.instance_profile_name == profile_name: return True return False def associate_profile_to_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Associate an instance profile with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.associate_profile_to_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if associated: return True else: try: conn.add_role_to_instance_profile(profile_name, role_name) log.info('Added %s instance profile to IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add %s instance profile to IAM role %s', profile_name, role_name) return False def disassociate_profile_from_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Disassociate an instance profile from an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.disassociate_profile_from_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if not associated: return True else: try: conn.remove_role_from_instance_profile(profile_name, role_name) log.info('Removed %s instance profile from IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove %s instance profile from IAM role %s.', profile_name, role_name) return False def list_role_policies(role_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_role_policies myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_role_policies(role_name) _list = response.list_role_policies_response.list_role_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def get_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.get_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: _policy = conn.get_role_policy(role_name, policy_name) # I _hate_ you for not giving me an object boto. _policy = _policy.get_role_policy_response.policy_document # Policy is url encoded _policy = _unquote(_policy) _policy = salt.utils.json.loads(_policy, object_pairs_hook=odict.OrderedDict) return _policy except boto.exception.BotoServerError: return {} def create_role_policy(role_name, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Create or modify a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role_policy myirole mypolicy '{"MyPolicy": "Statement": [{"Action": ["sqs:*"], "Effect": "Allow", "Resource": ["arn:aws:sqs:*:*:*"], "Sid": "MyPolicySqs1"}]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) mode = 'create' if _policy: if _policy == policy: return True mode = 'modify' if isinstance(policy, six.string_types): policy = salt.utils.json.loads(policy, object_pairs_hook=odict.OrderedDict) try: _policy = salt.utils.json.dumps(policy) conn.put_role_policy(role_name, policy_name, _policy) if mode == 'create': msg = 'Successfully added policy %s to IAM role %s.' else: msg = 'Successfully modified policy %s for IAM role %s.' log.info(msg, policy_name, role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to %s policy %s for IAM role %s.', mode, policy_name, role_name) return False def delete_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) if not _policy: return True try: conn.delete_role_policy(role_name, policy_name) log.info('Successfully deleted policy %s for IAM role %s.', policy_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM role %s.', policy_name, role_name) return False def update_assume_role_policy(role_name, policy_document, region=None, key=None, keyid=None, profile=None): ''' Update an assume role policy for a role. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_assume_role_policy myrole '{"Statement":"..."}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(policy_document, six.string_types): policy_document = salt.utils.json.loads(policy_document, object_pairs_hook=odict.OrderedDict) try: _policy_document = salt.utils.json.dumps(policy_document) conn.update_assume_role_policy(role_name, _policy_document) log.info('Successfully updated assume role policy for IAM role %s.', role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to update assume role policy for IAM role %s.', role_name) return False def build_policy(region=None, key=None, keyid=None, profile=None): ''' Build a default assume role policy. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.build_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if hasattr(conn, 'build_policy'): policy = salt.utils.json.loads(conn.build_policy()) elif hasattr(conn, '_build_policy'): policy = salt.utils.json.loads(conn._build_policy()) else: return {} # The format we get from build_policy isn't going to be what we get back # from AWS for the exact same policy. AWS converts single item list values # into strings, so let's do the same here. for key, policy_val in policy.items(): for statement in policy_val: if (isinstance(statement['Action'], list) and len(statement['Action']) == 1): statement['Action'] = statement['Action'][0] if (isinstance(statement['Principal']['Service'], list) and len(statement['Principal']['Service']) == 1): statement['Principal']['Service'] = statement['Principal']['Service'][0] # build_policy doesn't add a version field, which AWS is going to set to a # default value, when we get it back, so let's set it. policy['Version'] = '2008-10-17' return policy def get_account_id(region=None, key=None, keyid=None, profile=None): ''' Get a the AWS account id associated with the used credentials. CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_id ''' cache_key = 'boto_iam.account_id' if cache_key not in __context__: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_user() # The get_user call returns an user ARN: # arn:aws:iam::027050522557:user/salt-test arn = ret['get_user_response']['get_user_result']['user']['arn'] account_id = arn.split(':')[4] except boto.exception.BotoServerError: # If call failed, then let's try to get the ARN from the metadata timeout = boto.config.getfloat( 'Boto', 'metadata_service_timeout', 1.0 ) attempts = boto.config.getint( 'Boto', 'metadata_service_num_attempts', 1 ) identity = boto.utils.get_instance_identity( timeout=timeout, num_retries=attempts ) try: account_id = identity['document']['accountId'] except KeyError: log.error('Failed to get account id from instance_identity in' ' boto_iam.get_account_id.') __context__[cache_key] = account_id return __context__[cache_key] def get_all_roles(path_prefix=None, region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM role details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_roles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _roles = conn.list_roles(path_prefix=path_prefix) roles = _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) while marker: _roles = conn.list_roles(path_prefix=path_prefix, marker=marker) roles = roles + _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) return roles def get_all_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM user details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_users ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _users = conn.get_all_users(path_prefix=path_prefix) users = _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) while marker: _users = conn.get_all_users(path_prefix=path_prefix, marker=marker) users = users + _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) return users def get_all_user_policies(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all user policies. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_user_policies myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_all_user_policies(user_name, marker, max_items) if not info: return False _list = info.list_user_policies_response.list_user_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policies for user %s.', user_name) return False def get_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user_policy myuser mypolicyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user_policy(user_name, policy_name) log.debug('Info for IAM user %s policy %s: %s.', user_name, policy_name, info) if not info: return False info = info.get_user_policy_response.get_user_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policy %s for IAM user %s.', policy_name, user_name) return False def put_user_policy(user_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_user_policy myuser policyname policyrules ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_user_policy(user_name, policy_name, policy_json) if created: log.info('Created policy %s for IAM user %s.', policy_name, user_name) return True log.error('Could not create policy %s for IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy %s for IAM user %s.', policy_name, user_name) return False def delete_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user_policy myuser mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_user_policy( user_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_user_policy(user_name, policy_name) log.info('Successfully deleted policy %s for IAM user %s.', policy_name, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM user %s.', policy_name, user_name) return False def upload_server_cert(cert_name, cert_body, private_key, cert_chain=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Upload a certificate to Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.upload_server_cert mycert_name crt priv_key :param cert_name: The name for the server certificate. Do not include the path in this value. :param cert_body: The contents of the public key certificate in PEM-encoded format. :param private_key: The contents of the private key in PEM-encoded format. :param cert_chain: The contents of the certificate chain. This is typically a concatenation of the PEM-encoded public key certificates of the chain. :param path: The path for the server certificate. :param region: The name of the region to connect to. :param key: The key to be used in order to connect :param keyid: The keyid to be used in order to connect :param profile: The profile that contains a dict of region, key, keyid :return: True / False ''' exists = get_server_certificate(cert_name, region, key, keyid, profile) if exists: return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.upload_server_cert(cert_name, cert_body, private_key, cert_chain) log.info('Created certificate %s.', cert_name) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to failed to create certificate %s.', cert_name) return False def list_server_certificates(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Lists the server certificates stored in IAM that have the specified path prefix. .. versionadded:: ??? :param path_prefix: The path prefix for filtering the results. For example: /company/servercerts would get all server certificates for which the path starts with /company/servercerts . This parameter is optional. If it is not included, it defaults to a slash (/), listing all server certificates. This parameter allows (per its regex pattern) a string of characters consisting of either a forward slash (/) by itself or a string that must begin and end with forward slashes. In addition, it can contain any ASCII character from the ! (u0021) through the DEL character (u007F), including most punctuation characters, digits, and upper and lowercased letters. CLI Example: .. code-block:: bash salt myminion boto_iam.list_server_certificates path_prefix=/somepath/ ''' retries = 10 sleep = 6 conn = __utils__['boto3.get_connection']('iam', region=region, key=key, keyid=keyid, profile=profile) Items = [] while retries: try: log.debug('Garnering list of IAM Server Certificates') IsTruncated = True while IsTruncated: kwargs = {'PathPrefix': path_prefix} ret = conn.list_server_certificates(**kwargs) Items += ret.get('ServerCertificateMetadataList', []) IsTruncated = ret.get('IsTruncated') kwargs.update({'Marker': ret.get('Marker')}) return Items except botocore.exceptions.ParamValidationError as err: raise SaltInvocationError(str(err)) except botocore.exceptions.ClientError as err: if retries and jmespath.search('Error.Code', err.response) == 'Throttling': retries -= 1 log.debug('Throttled by AWS API, retrying in %s seconds...', sleep) time.sleep(sleep) continue log.error('Failed to list IAM Server Certificates: %s', err.message) return None def get_server_certificate(cert_name, region=None, key=None, keyid=None, profile=None): ''' Returns certificate information from Amazon .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_server_certificate mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_server_certificate(cert_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get certificate %s information.', cert_name) return False def delete_server_cert(cert_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a certificate from Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_server_cert mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_server_cert(cert_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete certificate %s.', cert_name) return False def export_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM user details. Produces results that can be used to create an sls file. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.export_users --out=txt | sed "s/local: //" > iam_users.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() users = get_all_users(path_prefix, region, key, keyid, profile) for user in users: name = user.user_name _policies = conn.get_all_user_policies(name, max_items=100) _policies = _policies.list_user_policies_response.list_user_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_user_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_user_policy_response.get_user_policy_result.policy_document )) policies[policy_name] = _policy user_sls = [] user_sls.append({"name": name}) user_sls.append({"policies": policies}) user_sls.append({"path": user.path}) results["manage user " + name] = {"boto_iam.user_present": user_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def export_roles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM role details. Produces results that can be used to create an sls file. CLI Example: salt-call boto_iam.export_roles --out=txt | sed "s/local: //" > iam_roles.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() roles = get_all_roles(path_prefix, region, key, keyid, profile) for role in roles: name = role.role_name _policies = conn.list_role_policies(name, max_items=100) _policies = _policies.list_role_policies_response.list_role_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_role_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_role_policy_response.get_role_policy_result.policy_document )) policies[policy_name] = _policy role_sls = [] role_sls.append({"name": name}) role_sls.append({"policies": policies}) role_sls.append({'policy_document': salt.utils.json.loads(_unquote(role.assume_role_policy_document))}) role_sls.append({"path": role.path}) results["manage role " + name] = {"boto_iam_role.present": role_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def _get_policy_arn(name, region=None, key=None, keyid=None, profile=None): if name.startswith('arn:aws:iam:'): return name account_id = get_account_id( region=region, key=key, keyid=keyid, profile=profile ) return 'arn:aws:iam::{0}:policy/{1}'.format(account_id, name) def policy_exists(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return True except boto.exception.BotoServerError: return False def get_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return ret.get('get_policy_response', {}).get('get_policy_result', {}) except boto.exception.BotoServerError: return None def create_policy(policy_name, policy_document, path=None, description=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in 'path', 'description': if locals()[arg] is not None: params[arg] = locals()[arg] if policy_exists(policy_name, region, key, keyid, profile): return True try: conn.create_policy(policy_name, policy_document, **params) log.info('Created IAM policy %s.', policy_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s.', policy_name) return False return True def delete_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_exists(policy_arn, region, key, keyid, profile): return True try: conn.delete_policy(policy_arn) log.info('Deleted %s policy.', policy_name) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete %s policy: %s.', policy_name, aws.get('message')) return False return True def list_policies(region=None, key=None, keyid=None, profile=None): ''' List policies. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policies ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: policies = [] for ret in __utils__['boto.paged_call'](conn.list_policies): policies.append(ret.get('list_policies_response', {}).get('list_policies_result', {}).get('policies')) return policies except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to list policy versions.' log.error(msg) return [] def policy_version_exists(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.get_policy_version(policy_arn, version_id) return True except boto.exception.BotoServerError: return False def get_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy_version(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile), version_id) retval = ret.get('get_policy_version_response', {}).get('get_policy_version_result', {}).get('policy_version', {}) retval['document'] = _unquote(retval.get('document')) return {'policy_version': retval} except boto.exception.BotoServerError: return None def create_policy_version(policy_name, policy_document, set_as_default=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy version. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy_version mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in ('set_as_default',): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.create_policy_version(policy_arn, policy_document, **params) vid = ret.get('create_policy_version_response', {}).get('create_policy_version_result', {}).get('policy_version', {}).get('version_id') log.info('Created IAM policy %s version %s.', policy_name, vid) return {'created': True, 'version_id': vid} except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s version %s.', policy_name, vid) return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Delete a policy version. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_version_exists(policy_arn, version_id, region, key, keyid, profile): return True try: conn.delete_policy_version(policy_arn, version_id) log.info('Deleted IAM policy %s version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete IAM policy %s version %s: %s', policy_name, version_id, aws.get('message')) return False return True def list_policy_versions(policy_name, region=None, key=None, keyid=None, profile=None): ''' List versions of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policy_versions mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.list_policy_versions(policy_arn) return ret.get('list_policy_versions_response', {}).get('list_policy_versions_result', {}).get('versions') except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list versions for IAM policy %s.', policy_name) return [] def set_default_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Set the default version of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.set_default_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.set_default_policy_version(policy_arn, version_id) log.info('Set %s policy to version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to set %s policy to version %s: %s', policy_name, version_id, aws.get('message')) return False return True def attach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_user_policy(policy_arn, user_name) log.info('Attached policy %s to IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach %s policy to IAM user %s.', policy_name, user_name) return False return True def detach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_user_policy(policy_arn, user_name) log.info('Detached %s policy from IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach %s policy from IAM user %s.', policy_name, user_name) return False return True def attach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_group_policy(policy_arn, group_name) log.info('Attached policy %s to IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM group %s.', policy_name, group_name) return False return True def detach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_group_policy(policy_arn, group_name) log.info('Detached policy %s from IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM group %s.', policy_name, group_name) return False return True def attach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_role_policy(policy_arn, role_name) log.info('Attached policy %s to IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM role %s.', policy_name, role_name) return False return True def detach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_role_policy(policy_arn, role_name) log.info('Detached policy %s from IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM role %s.', policy_name, role_name) return False return True def list_entities_for_policy(policy_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities that a policy is attached to. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 params = {} for arg in ('path_prefix', 'entity_filter'): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) while retries: try: allret = { 'policy_groups': [], 'policy_users': [], 'policy_roles': [], } for ret in __utils__['boto.paged_call'](conn.list_entities_for_policy, policy_arn=policy_arn, **params): for k, v in six.iteritems(allret): v.extend(ret.get('list_entities_for_policy_response', {}).get('list_entities_for_policy_result', {}).get(k)) return allret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('Failed to list entities for IAM policy %s: %s', policy_name, e.message) return {} return {} def list_attached_user_policies(user_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given user. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'UserName': user_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedUserPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_user_policies_response', {}).get('list_attached_user_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM user %s.', user_name) return [] def list_attached_group_policies(group_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given group. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'GroupName': group_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedGroupPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_group_policies_response', {}).get('list_attached_group_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM group %s.', group_name) return [] def list_attached_role_policies(role_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'RoleName': role_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedRolePolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_role_policies_response', {}).get('list_attached_role_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM role %s.', role_name) return [] def create_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Create SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.create_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_saml_provider(saml_metadata_document, name) log.info('Successfully created %s SAML provider.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to create SAML provider %s.', name) return False def get_saml_provider_arn(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider_arn my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_saml_providers() for saml_provider in response.list_saml_providers_response.list_saml_providers_result.saml_provider_list: if saml_provider['arn'].endswith(':saml-provider/' + name): return saml_provider['arn'] return False except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to get ARN of SAML provider %s.', name) return False def delete_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Delete SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.delete_saml_provider my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return True conn.delete_saml_provider(saml_provider_arn) log.info('Successfully deleted SAML provider %s.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete SAML provider %s.', name) return False def list_saml_providers(region=None, key=None, keyid=None, profile=None): ''' List SAML providers. CLI Example: .. code-block:: bash salt myminion boto_iam.list_saml_providers ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: providers = [] info = conn.list_saml_providers() for arn in info['list_saml_providers_response']['list_saml_providers_result']['saml_provider_list']: providers.append(arn['arn'].rsplit('/', 1)[1]) return providers except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get list of SAML providers.') return False def get_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider document. CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider arn ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: provider = conn.get_saml_provider(name) return provider['get_saml_provider_response']['get_saml_provider_result']['saml_metadata_document'] except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get SAML provider document %s.', name) return False def update_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Update SAML provider. CLI Example: .. code-block:: bash salt myminion boto_iam.update_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return False if conn.update_saml_provider(name, saml_metadata_document): return True return False except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to update SAML provider %s.', name) return False
saltstack/salt
salt/modules/boto_iam.py
update_account_password_policy
python
def update_account_password_policy(allow_users_to_change_password=None, hard_expiry=None, max_password_age=None, minimum_password_length=None, password_reuse_prevention=None, require_lowercase_characters=None, require_numbers=None, require_symbols=None, require_uppercase_characters=None, region=None, key=None, keyid=None, profile=None): ''' Update the password policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_account_password_policy True ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.update_account_password_policy(allow_users_to_change_password, hard_expiry, max_password_age, minimum_password_length, password_reuse_prevention, require_lowercase_characters, require_numbers, require_symbols, require_uppercase_characters) log.info('The password policy has been updated.') return True except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy' log.error(msg) return False
Update the password policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_account_password_policy True
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iam.py#L894-L929
null
# -*- coding: utf-8 -*- ''' Connection module for Amazon IAM .. versionadded:: 2014.7.0 :configuration: This module accepts explicit iam 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 iam.keyid: GKTADJGHEIQSXMKKRBJ08H iam.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs iam.region: 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: boto ''' # keep lint from choking on _get_conn and _cache_id #pylint: disable=E0602 # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import salt libs from salt.ext import six import salt.utils.compat import salt.utils.json import salt.utils.odict as odict import salt.utils.versions from salt.exceptions import SaltInvocationError # Import third party libs # pylint: disable=unused-import from salt.ext.six.moves.urllib.parse import unquote as _unquote # pylint: disable=no-name-in-module try: import boto import boto.iam import boto3 import botocore logging.getLogger('boto').setLevel(logging.CRITICAL) logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=unused-import log = logging.getLogger(__name__) def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'iam', pack=__salt__) def instance_profile_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an instance profile exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: # Boto weirdly returns an exception here if an instance profile doesn't # exist. conn.get_instance_profile(name) return True except boto.exception.BotoServerError: return False def create_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Create an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.create_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if instance_profile_exists(name, region, key, keyid, profile): return True try: # This call returns an instance profile if successful and an exception # if not. It's annoying. conn.create_instance_profile(name) log.info('Created %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create %s instance profile.', name) return False return True def delete_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Delete an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not instance_profile_exists(name, region, key, keyid, profile): return True try: conn.delete_instance_profile(name) log.info('Deleted %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s instance profile.', name) return False return True def role_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an IAM role exists. CLI Example: .. code-block:: bash salt myminion boto_iam.role_exists myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_role(name) return True except boto.exception.BotoServerError: return False def describe_role(name, region=None, key=None, keyid=None, profile=None): ''' Get information for a role. CLI Example: .. code-block:: bash salt myminion boto_iam.describe_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_role(name) if not info: return False role = info.get_role_response.get_role_result.role role['assume_role_policy_document'] = salt.utils.json.loads(_unquote( role.assume_role_policy_document )) # If Sid wasn't defined by the user, boto will still return a Sid in # each policy. To properly check idempotently, let's remove the Sid # from the return if it's not actually set. for policy_key, policy in role['assume_role_policy_document'].items(): if policy_key == 'Statement': for val in policy: if 'Sid' in val and not val['Sid']: del val['Sid'] return role except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get %s information.', name) return False def create_user(user_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_user myuser ''' if not path: path = '/' if get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_user(user_name, path) log.info('Created IAM user : %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM user %s.', user_name) return False def get_all_access_keys(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all access keys from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_access_keys myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.get_all_access_keys(user_name, marker, max_items) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get access keys for IAM user %s.', user_name) return six.text_type(e) def create_access_key(user_name, region=None, key=None, keyid=None, profile=None): ''' Create access key id for a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.create_access_key(user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create access key.') return six.text_type(e) def delete_access_key(access_key_id, user_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete access key id from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_access_key(access_key_id, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete access key id %s.', access_key_id) return six.text_type(e) def delete_user(user_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user myuser ''' if not get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.delete_user(user_name) log.info('Deleted IAM user : %s .', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM user %s', user_name) return six.text_type(e) def get_user(user_name=None, region=None, key=None, keyid=None, profile=None): ''' Get user information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user(user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM user %s info.', user_name) return False def create_group(group_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_group group ''' if not path: path = '/' if get_group(group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_group(group_name, path) log.info('Created IAM group : %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM group %s.', group_name) return False def get_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group(group_name, max_items=1) if not info: return False return info['get_group_response']['get_group_result']['group'] except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_group_members(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: marker = None truncated = True users = [] while truncated: info = conn.get_group(group_name, marker=marker, max_items=1000) if not info: return False truncated = bool(info['get_group_response']['get_group_result']['is_truncated']) if truncated and 'marker' in info['get_group_response']['get_group_result']: marker = info['get_group_response']['get_group_result']['marker'] else: marker = None truncated = False users += info['get_group_response']['get_group_result']['users'] return users except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get members for IAM group %s.', group_name) return False def add_user_to_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Add user to group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.add_user_to_group myuser mygroup ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('Username : %s does not exist.', user_name) return False if user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.add_user_to_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add IAM user %s to group %s.', user_name, group_name) return False def user_exists_in_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Check if user exists in group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.user_exists_in_group myuser mygroup ''' # TODO this should probably use boto.iam.get_groups_for_user users = get_group_members( group_name=group_name, region=region, key=key, keyid=keyid, profile=profile ) if users: for _user in users: if user_name == _user['user_name']: log.debug('IAM user %s is already in IAM group %s.', user_name, group_name) return True return False def remove_user_from_group(group_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Remove user from group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.remove_user_from_group mygroup myuser ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist.', user_name) return False if not user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.remove_user_from_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove IAM user %s from group %s', user_name, group_name) return False def put_group_policy(group_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_group_policy mygroup policyname policyrules ''' group = get_group(group_name, region=region, key=key, keyid=keyid, profile=profile) if not group: log.error('Group %s does not exist', group_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_group_policy(group_name, policy_name, policy_json) if created: log.info('Created policy for IAM group %s.', group_name) return True log.error('Could not create policy for IAM group %s', group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy for IAM group %s', group_name) return False def delete_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group_policy mygroup mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_group_policy( group_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_group_policy(group_name, policy_name) log.info('Successfully deleted policy %s for IAM group %s.', policy_name, group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM group %s.', policy_name, group_name) return False def get_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group_policy mygroup policyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group_policy(group_name, policy_name) log.debug('info for group policy is : %s', info) if not info: return False info = info.get_group_policy_response.get_group_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_all_groups(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM group details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_groups ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _groups = conn.get_all_groups(path_prefix=path_prefix) groups = _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) while marker: _groups = conn.get_all_groups(path_prefix=path_prefix, marker=marker) groups = groups + _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) return groups def get_all_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.get_all_instance_profiles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) marker = False profiles = [] while marker is not None: marker = marker if marker else None p = conn.list_instance_profiles(path_prefix=path_prefix, marker=marker) res = p.list_instance_profiles_response.list_instance_profiles_result profiles += res.instance_profiles marker = getattr(res, 'marker', None) return profiles def list_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' List all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.list_instance_profiles ''' p = get_all_instance_profiles(path_prefix, region, key, keyid, profile) return [i['instance_profile_name'] for i in p] def get_all_group_policies(group_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a group. CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_group_policies mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False try: response = conn.get_all_group_policies(group_name) _list = response.list_group_policies_response.list_group_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def delete_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _group = get_group( group_name, region, key, keyid, profile ) if not _group: return True try: conn.delete_group(group_name) log.info('Successfully deleted IAM group %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM group %s.', group_name) return False def create_login_profile(user_name, password, region=None, key=None, keyid=None, profile=None): ''' Creates a login profile for the specified user, give the user the ability to access AWS services and the AWS Management Console. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_login_profile user_name password ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.create_login_profile(user_name, password) log.info('Created profile for IAM user %s.', user_name) return info except boto.exception.BotoServerError as e: log.debug(e) if 'Conflict' in e: log.info('Profile already exists for IAM user %s.', user_name) return 'Conflict' log.error('Failed to update profile for IAM user %s.', user_name) return False def delete_login_profile(user_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a login profile for the specified user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_login_profile user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.delete_login_profile(user_name) log.info('Deleted login profile for IAM user %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Login profile already deleted for IAM user %s.', user_name) return True log.error('Failed to delete login profile for IAM user %s.', user_name) return False def get_all_mfa_devices(user_name, region=None, key=None, keyid=None, profile=None): ''' Get all MFA devices associated with an IAM user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_mfa_devices user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: result = conn.get_all_mfa_devices(user_name) devices = result['list_mfa_devices_response']['list_mfa_devices_result']['mfa_devices'] return devices except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Could not find IAM user %s.', user_name) return [] log.error('Failed to get all MFA devices for IAM user %s.', user_name) return False def deactivate_mfa_device(user_name, serial, region=None, key=None, keyid=None, profile=None): ''' Deactivates the specified MFA device and removes it from association with the user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.deactivate_mfa_device user_name serial_num ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.deactivate_mfa_device(user_name, serial) log.info('Deactivated MFA device %s for IAM user %s.', serial, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('MFA device %s not associated with IAM user %s.', serial, user_name) return True log.error('Failed to deactivate MFA device %s for IAM user %s.', serial, user_name) return False def delete_virtual_mfa_device(serial, region=None, key=None, keyid=None, profile=None): ''' Deletes the specified virtual MFA device. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_virtual_mfa_device serial_num ''' conn = __utils__['boto3.get_connection_func']('iam')() try: conn.delete_virtual_mfa_device(SerialNumber=serial) log.info('Deleted virtual MFA device %s.', serial) return True except botocore.exceptions.ClientError as e: log.debug(e) if 'NoSuchEntity' in six.text_type(e): log.info('Virtual MFA device %s not found.', serial) return True log.error('Failed to delete virtual MFA device %s.', serial) return False def get_account_policy(region=None, key=None, keyid=None, profile=None): ''' Get account policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_account_password_policy() return info.get_account_password_policy_response.get_account_password_policy_result.password_policy except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy.' log.error(msg) return False def create_role(name, policy_document=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Create an instance role. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if role_exists(name, region, key, keyid, profile): return True if not policy_document: policy_document = None try: conn.create_role(name, assume_role_policy_document=policy_document, path=path) log.info('Created IAM role %s.', name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to create IAM role %s.', name) return False def delete_role(name, region=None, key=None, keyid=None, profile=None): ''' Delete an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(name, region, key, keyid, profile): return True try: conn.delete_role(name) log.info('Deleted %s IAM role.', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s IAM role.', name) return False def profile_associated(role_name, profile_name, region, key, keyid, profile): ''' Check to see if an instance profile is associated with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.profile_associated myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # The IAM module of boto doesn't return objects. Instead you need to grab # values through its properties. Sigh. try: profiles = conn.list_instance_profiles_for_role(role_name) except boto.exception.BotoServerError as e: log.debug(e) return False profiles = profiles.list_instance_profiles_for_role_response profiles = profiles.list_instance_profiles_for_role_result profiles = profiles.instance_profiles for profile in profiles: if profile.instance_profile_name == profile_name: return True return False def associate_profile_to_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Associate an instance profile with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.associate_profile_to_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if associated: return True else: try: conn.add_role_to_instance_profile(profile_name, role_name) log.info('Added %s instance profile to IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add %s instance profile to IAM role %s', profile_name, role_name) return False def disassociate_profile_from_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Disassociate an instance profile from an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.disassociate_profile_from_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if not associated: return True else: try: conn.remove_role_from_instance_profile(profile_name, role_name) log.info('Removed %s instance profile from IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove %s instance profile from IAM role %s.', profile_name, role_name) return False def list_role_policies(role_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_role_policies myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_role_policies(role_name) _list = response.list_role_policies_response.list_role_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def get_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.get_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: _policy = conn.get_role_policy(role_name, policy_name) # I _hate_ you for not giving me an object boto. _policy = _policy.get_role_policy_response.policy_document # Policy is url encoded _policy = _unquote(_policy) _policy = salt.utils.json.loads(_policy, object_pairs_hook=odict.OrderedDict) return _policy except boto.exception.BotoServerError: return {} def create_role_policy(role_name, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Create or modify a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role_policy myirole mypolicy '{"MyPolicy": "Statement": [{"Action": ["sqs:*"], "Effect": "Allow", "Resource": ["arn:aws:sqs:*:*:*"], "Sid": "MyPolicySqs1"}]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) mode = 'create' if _policy: if _policy == policy: return True mode = 'modify' if isinstance(policy, six.string_types): policy = salt.utils.json.loads(policy, object_pairs_hook=odict.OrderedDict) try: _policy = salt.utils.json.dumps(policy) conn.put_role_policy(role_name, policy_name, _policy) if mode == 'create': msg = 'Successfully added policy %s to IAM role %s.' else: msg = 'Successfully modified policy %s for IAM role %s.' log.info(msg, policy_name, role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to %s policy %s for IAM role %s.', mode, policy_name, role_name) return False def delete_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) if not _policy: return True try: conn.delete_role_policy(role_name, policy_name) log.info('Successfully deleted policy %s for IAM role %s.', policy_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM role %s.', policy_name, role_name) return False def update_assume_role_policy(role_name, policy_document, region=None, key=None, keyid=None, profile=None): ''' Update an assume role policy for a role. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_assume_role_policy myrole '{"Statement":"..."}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(policy_document, six.string_types): policy_document = salt.utils.json.loads(policy_document, object_pairs_hook=odict.OrderedDict) try: _policy_document = salt.utils.json.dumps(policy_document) conn.update_assume_role_policy(role_name, _policy_document) log.info('Successfully updated assume role policy for IAM role %s.', role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to update assume role policy for IAM role %s.', role_name) return False def build_policy(region=None, key=None, keyid=None, profile=None): ''' Build a default assume role policy. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.build_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if hasattr(conn, 'build_policy'): policy = salt.utils.json.loads(conn.build_policy()) elif hasattr(conn, '_build_policy'): policy = salt.utils.json.loads(conn._build_policy()) else: return {} # The format we get from build_policy isn't going to be what we get back # from AWS for the exact same policy. AWS converts single item list values # into strings, so let's do the same here. for key, policy_val in policy.items(): for statement in policy_val: if (isinstance(statement['Action'], list) and len(statement['Action']) == 1): statement['Action'] = statement['Action'][0] if (isinstance(statement['Principal']['Service'], list) and len(statement['Principal']['Service']) == 1): statement['Principal']['Service'] = statement['Principal']['Service'][0] # build_policy doesn't add a version field, which AWS is going to set to a # default value, when we get it back, so let's set it. policy['Version'] = '2008-10-17' return policy def get_account_id(region=None, key=None, keyid=None, profile=None): ''' Get a the AWS account id associated with the used credentials. CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_id ''' cache_key = 'boto_iam.account_id' if cache_key not in __context__: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_user() # The get_user call returns an user ARN: # arn:aws:iam::027050522557:user/salt-test arn = ret['get_user_response']['get_user_result']['user']['arn'] account_id = arn.split(':')[4] except boto.exception.BotoServerError: # If call failed, then let's try to get the ARN from the metadata timeout = boto.config.getfloat( 'Boto', 'metadata_service_timeout', 1.0 ) attempts = boto.config.getint( 'Boto', 'metadata_service_num_attempts', 1 ) identity = boto.utils.get_instance_identity( timeout=timeout, num_retries=attempts ) try: account_id = identity['document']['accountId'] except KeyError: log.error('Failed to get account id from instance_identity in' ' boto_iam.get_account_id.') __context__[cache_key] = account_id return __context__[cache_key] def get_all_roles(path_prefix=None, region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM role details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_roles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _roles = conn.list_roles(path_prefix=path_prefix) roles = _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) while marker: _roles = conn.list_roles(path_prefix=path_prefix, marker=marker) roles = roles + _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) return roles def get_all_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM user details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_users ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _users = conn.get_all_users(path_prefix=path_prefix) users = _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) while marker: _users = conn.get_all_users(path_prefix=path_prefix, marker=marker) users = users + _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) return users def get_all_user_policies(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all user policies. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_user_policies myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_all_user_policies(user_name, marker, max_items) if not info: return False _list = info.list_user_policies_response.list_user_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policies for user %s.', user_name) return False def get_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user_policy myuser mypolicyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user_policy(user_name, policy_name) log.debug('Info for IAM user %s policy %s: %s.', user_name, policy_name, info) if not info: return False info = info.get_user_policy_response.get_user_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policy %s for IAM user %s.', policy_name, user_name) return False def put_user_policy(user_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_user_policy myuser policyname policyrules ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_user_policy(user_name, policy_name, policy_json) if created: log.info('Created policy %s for IAM user %s.', policy_name, user_name) return True log.error('Could not create policy %s for IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy %s for IAM user %s.', policy_name, user_name) return False def delete_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user_policy myuser mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_user_policy( user_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_user_policy(user_name, policy_name) log.info('Successfully deleted policy %s for IAM user %s.', policy_name, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM user %s.', policy_name, user_name) return False def upload_server_cert(cert_name, cert_body, private_key, cert_chain=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Upload a certificate to Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.upload_server_cert mycert_name crt priv_key :param cert_name: The name for the server certificate. Do not include the path in this value. :param cert_body: The contents of the public key certificate in PEM-encoded format. :param private_key: The contents of the private key in PEM-encoded format. :param cert_chain: The contents of the certificate chain. This is typically a concatenation of the PEM-encoded public key certificates of the chain. :param path: The path for the server certificate. :param region: The name of the region to connect to. :param key: The key to be used in order to connect :param keyid: The keyid to be used in order to connect :param profile: The profile that contains a dict of region, key, keyid :return: True / False ''' exists = get_server_certificate(cert_name, region, key, keyid, profile) if exists: return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.upload_server_cert(cert_name, cert_body, private_key, cert_chain) log.info('Created certificate %s.', cert_name) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to failed to create certificate %s.', cert_name) return False def list_server_certificates(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Lists the server certificates stored in IAM that have the specified path prefix. .. versionadded:: ??? :param path_prefix: The path prefix for filtering the results. For example: /company/servercerts would get all server certificates for which the path starts with /company/servercerts . This parameter is optional. If it is not included, it defaults to a slash (/), listing all server certificates. This parameter allows (per its regex pattern) a string of characters consisting of either a forward slash (/) by itself or a string that must begin and end with forward slashes. In addition, it can contain any ASCII character from the ! (u0021) through the DEL character (u007F), including most punctuation characters, digits, and upper and lowercased letters. CLI Example: .. code-block:: bash salt myminion boto_iam.list_server_certificates path_prefix=/somepath/ ''' retries = 10 sleep = 6 conn = __utils__['boto3.get_connection']('iam', region=region, key=key, keyid=keyid, profile=profile) Items = [] while retries: try: log.debug('Garnering list of IAM Server Certificates') IsTruncated = True while IsTruncated: kwargs = {'PathPrefix': path_prefix} ret = conn.list_server_certificates(**kwargs) Items += ret.get('ServerCertificateMetadataList', []) IsTruncated = ret.get('IsTruncated') kwargs.update({'Marker': ret.get('Marker')}) return Items except botocore.exceptions.ParamValidationError as err: raise SaltInvocationError(str(err)) except botocore.exceptions.ClientError as err: if retries and jmespath.search('Error.Code', err.response) == 'Throttling': retries -= 1 log.debug('Throttled by AWS API, retrying in %s seconds...', sleep) time.sleep(sleep) continue log.error('Failed to list IAM Server Certificates: %s', err.message) return None def get_server_certificate(cert_name, region=None, key=None, keyid=None, profile=None): ''' Returns certificate information from Amazon .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_server_certificate mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_server_certificate(cert_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get certificate %s information.', cert_name) return False def delete_server_cert(cert_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a certificate from Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_server_cert mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_server_cert(cert_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete certificate %s.', cert_name) return False def export_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM user details. Produces results that can be used to create an sls file. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.export_users --out=txt | sed "s/local: //" > iam_users.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() users = get_all_users(path_prefix, region, key, keyid, profile) for user in users: name = user.user_name _policies = conn.get_all_user_policies(name, max_items=100) _policies = _policies.list_user_policies_response.list_user_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_user_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_user_policy_response.get_user_policy_result.policy_document )) policies[policy_name] = _policy user_sls = [] user_sls.append({"name": name}) user_sls.append({"policies": policies}) user_sls.append({"path": user.path}) results["manage user " + name] = {"boto_iam.user_present": user_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def export_roles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM role details. Produces results that can be used to create an sls file. CLI Example: salt-call boto_iam.export_roles --out=txt | sed "s/local: //" > iam_roles.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() roles = get_all_roles(path_prefix, region, key, keyid, profile) for role in roles: name = role.role_name _policies = conn.list_role_policies(name, max_items=100) _policies = _policies.list_role_policies_response.list_role_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_role_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_role_policy_response.get_role_policy_result.policy_document )) policies[policy_name] = _policy role_sls = [] role_sls.append({"name": name}) role_sls.append({"policies": policies}) role_sls.append({'policy_document': salt.utils.json.loads(_unquote(role.assume_role_policy_document))}) role_sls.append({"path": role.path}) results["manage role " + name] = {"boto_iam_role.present": role_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def _get_policy_arn(name, region=None, key=None, keyid=None, profile=None): if name.startswith('arn:aws:iam:'): return name account_id = get_account_id( region=region, key=key, keyid=keyid, profile=profile ) return 'arn:aws:iam::{0}:policy/{1}'.format(account_id, name) def policy_exists(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return True except boto.exception.BotoServerError: return False def get_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return ret.get('get_policy_response', {}).get('get_policy_result', {}) except boto.exception.BotoServerError: return None def create_policy(policy_name, policy_document, path=None, description=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in 'path', 'description': if locals()[arg] is not None: params[arg] = locals()[arg] if policy_exists(policy_name, region, key, keyid, profile): return True try: conn.create_policy(policy_name, policy_document, **params) log.info('Created IAM policy %s.', policy_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s.', policy_name) return False return True def delete_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_exists(policy_arn, region, key, keyid, profile): return True try: conn.delete_policy(policy_arn) log.info('Deleted %s policy.', policy_name) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete %s policy: %s.', policy_name, aws.get('message')) return False return True def list_policies(region=None, key=None, keyid=None, profile=None): ''' List policies. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policies ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: policies = [] for ret in __utils__['boto.paged_call'](conn.list_policies): policies.append(ret.get('list_policies_response', {}).get('list_policies_result', {}).get('policies')) return policies except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to list policy versions.' log.error(msg) return [] def policy_version_exists(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.get_policy_version(policy_arn, version_id) return True except boto.exception.BotoServerError: return False def get_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy_version(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile), version_id) retval = ret.get('get_policy_version_response', {}).get('get_policy_version_result', {}).get('policy_version', {}) retval['document'] = _unquote(retval.get('document')) return {'policy_version': retval} except boto.exception.BotoServerError: return None def create_policy_version(policy_name, policy_document, set_as_default=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy version. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy_version mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in ('set_as_default',): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.create_policy_version(policy_arn, policy_document, **params) vid = ret.get('create_policy_version_response', {}).get('create_policy_version_result', {}).get('policy_version', {}).get('version_id') log.info('Created IAM policy %s version %s.', policy_name, vid) return {'created': True, 'version_id': vid} except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s version %s.', policy_name, vid) return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Delete a policy version. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_version_exists(policy_arn, version_id, region, key, keyid, profile): return True try: conn.delete_policy_version(policy_arn, version_id) log.info('Deleted IAM policy %s version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete IAM policy %s version %s: %s', policy_name, version_id, aws.get('message')) return False return True def list_policy_versions(policy_name, region=None, key=None, keyid=None, profile=None): ''' List versions of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policy_versions mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.list_policy_versions(policy_arn) return ret.get('list_policy_versions_response', {}).get('list_policy_versions_result', {}).get('versions') except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list versions for IAM policy %s.', policy_name) return [] def set_default_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Set the default version of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.set_default_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.set_default_policy_version(policy_arn, version_id) log.info('Set %s policy to version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to set %s policy to version %s: %s', policy_name, version_id, aws.get('message')) return False return True def attach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_user_policy(policy_arn, user_name) log.info('Attached policy %s to IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach %s policy to IAM user %s.', policy_name, user_name) return False return True def detach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_user_policy(policy_arn, user_name) log.info('Detached %s policy from IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach %s policy from IAM user %s.', policy_name, user_name) return False return True def attach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_group_policy(policy_arn, group_name) log.info('Attached policy %s to IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM group %s.', policy_name, group_name) return False return True def detach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_group_policy(policy_arn, group_name) log.info('Detached policy %s from IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM group %s.', policy_name, group_name) return False return True def attach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_role_policy(policy_arn, role_name) log.info('Attached policy %s to IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM role %s.', policy_name, role_name) return False return True def detach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_role_policy(policy_arn, role_name) log.info('Detached policy %s from IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM role %s.', policy_name, role_name) return False return True def list_entities_for_policy(policy_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities that a policy is attached to. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 params = {} for arg in ('path_prefix', 'entity_filter'): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) while retries: try: allret = { 'policy_groups': [], 'policy_users': [], 'policy_roles': [], } for ret in __utils__['boto.paged_call'](conn.list_entities_for_policy, policy_arn=policy_arn, **params): for k, v in six.iteritems(allret): v.extend(ret.get('list_entities_for_policy_response', {}).get('list_entities_for_policy_result', {}).get(k)) return allret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('Failed to list entities for IAM policy %s: %s', policy_name, e.message) return {} return {} def list_attached_user_policies(user_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given user. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'UserName': user_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedUserPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_user_policies_response', {}).get('list_attached_user_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM user %s.', user_name) return [] def list_attached_group_policies(group_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given group. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'GroupName': group_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedGroupPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_group_policies_response', {}).get('list_attached_group_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM group %s.', group_name) return [] def list_attached_role_policies(role_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'RoleName': role_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedRolePolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_role_policies_response', {}).get('list_attached_role_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM role %s.', role_name) return [] def create_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Create SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.create_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_saml_provider(saml_metadata_document, name) log.info('Successfully created %s SAML provider.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to create SAML provider %s.', name) return False def get_saml_provider_arn(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider_arn my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_saml_providers() for saml_provider in response.list_saml_providers_response.list_saml_providers_result.saml_provider_list: if saml_provider['arn'].endswith(':saml-provider/' + name): return saml_provider['arn'] return False except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to get ARN of SAML provider %s.', name) return False def delete_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Delete SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.delete_saml_provider my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return True conn.delete_saml_provider(saml_provider_arn) log.info('Successfully deleted SAML provider %s.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete SAML provider %s.', name) return False def list_saml_providers(region=None, key=None, keyid=None, profile=None): ''' List SAML providers. CLI Example: .. code-block:: bash salt myminion boto_iam.list_saml_providers ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: providers = [] info = conn.list_saml_providers() for arn in info['list_saml_providers_response']['list_saml_providers_result']['saml_provider_list']: providers.append(arn['arn'].rsplit('/', 1)[1]) return providers except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get list of SAML providers.') return False def get_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider document. CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider arn ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: provider = conn.get_saml_provider(name) return provider['get_saml_provider_response']['get_saml_provider_result']['saml_metadata_document'] except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get SAML provider document %s.', name) return False def update_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Update SAML provider. CLI Example: .. code-block:: bash salt myminion boto_iam.update_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return False if conn.update_saml_provider(name, saml_metadata_document): return True return False except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to update SAML provider %s.', name) return False
saltstack/salt
salt/modules/boto_iam.py
get_account_policy
python
def get_account_policy(region=None, key=None, keyid=None, profile=None): ''' Get account policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_account_password_policy() return info.get_account_password_policy_response.get_account_password_policy_result.password_policy except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy.' log.error(msg) return False
Get account policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_policy
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iam.py#L932-L952
null
# -*- coding: utf-8 -*- ''' Connection module for Amazon IAM .. versionadded:: 2014.7.0 :configuration: This module accepts explicit iam 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 iam.keyid: GKTADJGHEIQSXMKKRBJ08H iam.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs iam.region: 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: boto ''' # keep lint from choking on _get_conn and _cache_id #pylint: disable=E0602 # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import salt libs from salt.ext import six import salt.utils.compat import salt.utils.json import salt.utils.odict as odict import salt.utils.versions from salt.exceptions import SaltInvocationError # Import third party libs # pylint: disable=unused-import from salt.ext.six.moves.urllib.parse import unquote as _unquote # pylint: disable=no-name-in-module try: import boto import boto.iam import boto3 import botocore logging.getLogger('boto').setLevel(logging.CRITICAL) logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=unused-import log = logging.getLogger(__name__) def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'iam', pack=__salt__) def instance_profile_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an instance profile exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: # Boto weirdly returns an exception here if an instance profile doesn't # exist. conn.get_instance_profile(name) return True except boto.exception.BotoServerError: return False def create_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Create an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.create_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if instance_profile_exists(name, region, key, keyid, profile): return True try: # This call returns an instance profile if successful and an exception # if not. It's annoying. conn.create_instance_profile(name) log.info('Created %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create %s instance profile.', name) return False return True def delete_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Delete an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not instance_profile_exists(name, region, key, keyid, profile): return True try: conn.delete_instance_profile(name) log.info('Deleted %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s instance profile.', name) return False return True def role_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an IAM role exists. CLI Example: .. code-block:: bash salt myminion boto_iam.role_exists myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_role(name) return True except boto.exception.BotoServerError: return False def describe_role(name, region=None, key=None, keyid=None, profile=None): ''' Get information for a role. CLI Example: .. code-block:: bash salt myminion boto_iam.describe_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_role(name) if not info: return False role = info.get_role_response.get_role_result.role role['assume_role_policy_document'] = salt.utils.json.loads(_unquote( role.assume_role_policy_document )) # If Sid wasn't defined by the user, boto will still return a Sid in # each policy. To properly check idempotently, let's remove the Sid # from the return if it's not actually set. for policy_key, policy in role['assume_role_policy_document'].items(): if policy_key == 'Statement': for val in policy: if 'Sid' in val and not val['Sid']: del val['Sid'] return role except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get %s information.', name) return False def create_user(user_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_user myuser ''' if not path: path = '/' if get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_user(user_name, path) log.info('Created IAM user : %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM user %s.', user_name) return False def get_all_access_keys(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all access keys from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_access_keys myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.get_all_access_keys(user_name, marker, max_items) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get access keys for IAM user %s.', user_name) return six.text_type(e) def create_access_key(user_name, region=None, key=None, keyid=None, profile=None): ''' Create access key id for a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.create_access_key(user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create access key.') return six.text_type(e) def delete_access_key(access_key_id, user_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete access key id from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_access_key(access_key_id, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete access key id %s.', access_key_id) return six.text_type(e) def delete_user(user_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user myuser ''' if not get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.delete_user(user_name) log.info('Deleted IAM user : %s .', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM user %s', user_name) return six.text_type(e) def get_user(user_name=None, region=None, key=None, keyid=None, profile=None): ''' Get user information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user(user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM user %s info.', user_name) return False def create_group(group_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_group group ''' if not path: path = '/' if get_group(group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_group(group_name, path) log.info('Created IAM group : %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM group %s.', group_name) return False def get_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group(group_name, max_items=1) if not info: return False return info['get_group_response']['get_group_result']['group'] except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_group_members(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: marker = None truncated = True users = [] while truncated: info = conn.get_group(group_name, marker=marker, max_items=1000) if not info: return False truncated = bool(info['get_group_response']['get_group_result']['is_truncated']) if truncated and 'marker' in info['get_group_response']['get_group_result']: marker = info['get_group_response']['get_group_result']['marker'] else: marker = None truncated = False users += info['get_group_response']['get_group_result']['users'] return users except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get members for IAM group %s.', group_name) return False def add_user_to_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Add user to group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.add_user_to_group myuser mygroup ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('Username : %s does not exist.', user_name) return False if user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.add_user_to_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add IAM user %s to group %s.', user_name, group_name) return False def user_exists_in_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Check if user exists in group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.user_exists_in_group myuser mygroup ''' # TODO this should probably use boto.iam.get_groups_for_user users = get_group_members( group_name=group_name, region=region, key=key, keyid=keyid, profile=profile ) if users: for _user in users: if user_name == _user['user_name']: log.debug('IAM user %s is already in IAM group %s.', user_name, group_name) return True return False def remove_user_from_group(group_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Remove user from group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.remove_user_from_group mygroup myuser ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist.', user_name) return False if not user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.remove_user_from_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove IAM user %s from group %s', user_name, group_name) return False def put_group_policy(group_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_group_policy mygroup policyname policyrules ''' group = get_group(group_name, region=region, key=key, keyid=keyid, profile=profile) if not group: log.error('Group %s does not exist', group_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_group_policy(group_name, policy_name, policy_json) if created: log.info('Created policy for IAM group %s.', group_name) return True log.error('Could not create policy for IAM group %s', group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy for IAM group %s', group_name) return False def delete_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group_policy mygroup mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_group_policy( group_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_group_policy(group_name, policy_name) log.info('Successfully deleted policy %s for IAM group %s.', policy_name, group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM group %s.', policy_name, group_name) return False def get_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group_policy mygroup policyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group_policy(group_name, policy_name) log.debug('info for group policy is : %s', info) if not info: return False info = info.get_group_policy_response.get_group_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_all_groups(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM group details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_groups ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _groups = conn.get_all_groups(path_prefix=path_prefix) groups = _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) while marker: _groups = conn.get_all_groups(path_prefix=path_prefix, marker=marker) groups = groups + _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) return groups def get_all_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.get_all_instance_profiles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) marker = False profiles = [] while marker is not None: marker = marker if marker else None p = conn.list_instance_profiles(path_prefix=path_prefix, marker=marker) res = p.list_instance_profiles_response.list_instance_profiles_result profiles += res.instance_profiles marker = getattr(res, 'marker', None) return profiles def list_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' List all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.list_instance_profiles ''' p = get_all_instance_profiles(path_prefix, region, key, keyid, profile) return [i['instance_profile_name'] for i in p] def get_all_group_policies(group_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a group. CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_group_policies mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False try: response = conn.get_all_group_policies(group_name) _list = response.list_group_policies_response.list_group_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def delete_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _group = get_group( group_name, region, key, keyid, profile ) if not _group: return True try: conn.delete_group(group_name) log.info('Successfully deleted IAM group %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM group %s.', group_name) return False def create_login_profile(user_name, password, region=None, key=None, keyid=None, profile=None): ''' Creates a login profile for the specified user, give the user the ability to access AWS services and the AWS Management Console. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_login_profile user_name password ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.create_login_profile(user_name, password) log.info('Created profile for IAM user %s.', user_name) return info except boto.exception.BotoServerError as e: log.debug(e) if 'Conflict' in e: log.info('Profile already exists for IAM user %s.', user_name) return 'Conflict' log.error('Failed to update profile for IAM user %s.', user_name) return False def delete_login_profile(user_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a login profile for the specified user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_login_profile user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.delete_login_profile(user_name) log.info('Deleted login profile for IAM user %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Login profile already deleted for IAM user %s.', user_name) return True log.error('Failed to delete login profile for IAM user %s.', user_name) return False def get_all_mfa_devices(user_name, region=None, key=None, keyid=None, profile=None): ''' Get all MFA devices associated with an IAM user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_mfa_devices user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: result = conn.get_all_mfa_devices(user_name) devices = result['list_mfa_devices_response']['list_mfa_devices_result']['mfa_devices'] return devices except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Could not find IAM user %s.', user_name) return [] log.error('Failed to get all MFA devices for IAM user %s.', user_name) return False def deactivate_mfa_device(user_name, serial, region=None, key=None, keyid=None, profile=None): ''' Deactivates the specified MFA device and removes it from association with the user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.deactivate_mfa_device user_name serial_num ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.deactivate_mfa_device(user_name, serial) log.info('Deactivated MFA device %s for IAM user %s.', serial, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('MFA device %s not associated with IAM user %s.', serial, user_name) return True log.error('Failed to deactivate MFA device %s for IAM user %s.', serial, user_name) return False def delete_virtual_mfa_device(serial, region=None, key=None, keyid=None, profile=None): ''' Deletes the specified virtual MFA device. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_virtual_mfa_device serial_num ''' conn = __utils__['boto3.get_connection_func']('iam')() try: conn.delete_virtual_mfa_device(SerialNumber=serial) log.info('Deleted virtual MFA device %s.', serial) return True except botocore.exceptions.ClientError as e: log.debug(e) if 'NoSuchEntity' in six.text_type(e): log.info('Virtual MFA device %s not found.', serial) return True log.error('Failed to delete virtual MFA device %s.', serial) return False def update_account_password_policy(allow_users_to_change_password=None, hard_expiry=None, max_password_age=None, minimum_password_length=None, password_reuse_prevention=None, require_lowercase_characters=None, require_numbers=None, require_symbols=None, require_uppercase_characters=None, region=None, key=None, keyid=None, profile=None): ''' Update the password policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_account_password_policy True ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.update_account_password_policy(allow_users_to_change_password, hard_expiry, max_password_age, minimum_password_length, password_reuse_prevention, require_lowercase_characters, require_numbers, require_symbols, require_uppercase_characters) log.info('The password policy has been updated.') return True except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy' log.error(msg) return False def create_role(name, policy_document=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Create an instance role. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if role_exists(name, region, key, keyid, profile): return True if not policy_document: policy_document = None try: conn.create_role(name, assume_role_policy_document=policy_document, path=path) log.info('Created IAM role %s.', name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to create IAM role %s.', name) return False def delete_role(name, region=None, key=None, keyid=None, profile=None): ''' Delete an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(name, region, key, keyid, profile): return True try: conn.delete_role(name) log.info('Deleted %s IAM role.', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s IAM role.', name) return False def profile_associated(role_name, profile_name, region, key, keyid, profile): ''' Check to see if an instance profile is associated with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.profile_associated myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # The IAM module of boto doesn't return objects. Instead you need to grab # values through its properties. Sigh. try: profiles = conn.list_instance_profiles_for_role(role_name) except boto.exception.BotoServerError as e: log.debug(e) return False profiles = profiles.list_instance_profiles_for_role_response profiles = profiles.list_instance_profiles_for_role_result profiles = profiles.instance_profiles for profile in profiles: if profile.instance_profile_name == profile_name: return True return False def associate_profile_to_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Associate an instance profile with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.associate_profile_to_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if associated: return True else: try: conn.add_role_to_instance_profile(profile_name, role_name) log.info('Added %s instance profile to IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add %s instance profile to IAM role %s', profile_name, role_name) return False def disassociate_profile_from_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Disassociate an instance profile from an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.disassociate_profile_from_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if not associated: return True else: try: conn.remove_role_from_instance_profile(profile_name, role_name) log.info('Removed %s instance profile from IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove %s instance profile from IAM role %s.', profile_name, role_name) return False def list_role_policies(role_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_role_policies myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_role_policies(role_name) _list = response.list_role_policies_response.list_role_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def get_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.get_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: _policy = conn.get_role_policy(role_name, policy_name) # I _hate_ you for not giving me an object boto. _policy = _policy.get_role_policy_response.policy_document # Policy is url encoded _policy = _unquote(_policy) _policy = salt.utils.json.loads(_policy, object_pairs_hook=odict.OrderedDict) return _policy except boto.exception.BotoServerError: return {} def create_role_policy(role_name, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Create or modify a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role_policy myirole mypolicy '{"MyPolicy": "Statement": [{"Action": ["sqs:*"], "Effect": "Allow", "Resource": ["arn:aws:sqs:*:*:*"], "Sid": "MyPolicySqs1"}]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) mode = 'create' if _policy: if _policy == policy: return True mode = 'modify' if isinstance(policy, six.string_types): policy = salt.utils.json.loads(policy, object_pairs_hook=odict.OrderedDict) try: _policy = salt.utils.json.dumps(policy) conn.put_role_policy(role_name, policy_name, _policy) if mode == 'create': msg = 'Successfully added policy %s to IAM role %s.' else: msg = 'Successfully modified policy %s for IAM role %s.' log.info(msg, policy_name, role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to %s policy %s for IAM role %s.', mode, policy_name, role_name) return False def delete_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) if not _policy: return True try: conn.delete_role_policy(role_name, policy_name) log.info('Successfully deleted policy %s for IAM role %s.', policy_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM role %s.', policy_name, role_name) return False def update_assume_role_policy(role_name, policy_document, region=None, key=None, keyid=None, profile=None): ''' Update an assume role policy for a role. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_assume_role_policy myrole '{"Statement":"..."}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(policy_document, six.string_types): policy_document = salt.utils.json.loads(policy_document, object_pairs_hook=odict.OrderedDict) try: _policy_document = salt.utils.json.dumps(policy_document) conn.update_assume_role_policy(role_name, _policy_document) log.info('Successfully updated assume role policy for IAM role %s.', role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to update assume role policy for IAM role %s.', role_name) return False def build_policy(region=None, key=None, keyid=None, profile=None): ''' Build a default assume role policy. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.build_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if hasattr(conn, 'build_policy'): policy = salt.utils.json.loads(conn.build_policy()) elif hasattr(conn, '_build_policy'): policy = salt.utils.json.loads(conn._build_policy()) else: return {} # The format we get from build_policy isn't going to be what we get back # from AWS for the exact same policy. AWS converts single item list values # into strings, so let's do the same here. for key, policy_val in policy.items(): for statement in policy_val: if (isinstance(statement['Action'], list) and len(statement['Action']) == 1): statement['Action'] = statement['Action'][0] if (isinstance(statement['Principal']['Service'], list) and len(statement['Principal']['Service']) == 1): statement['Principal']['Service'] = statement['Principal']['Service'][0] # build_policy doesn't add a version field, which AWS is going to set to a # default value, when we get it back, so let's set it. policy['Version'] = '2008-10-17' return policy def get_account_id(region=None, key=None, keyid=None, profile=None): ''' Get a the AWS account id associated with the used credentials. CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_id ''' cache_key = 'boto_iam.account_id' if cache_key not in __context__: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_user() # The get_user call returns an user ARN: # arn:aws:iam::027050522557:user/salt-test arn = ret['get_user_response']['get_user_result']['user']['arn'] account_id = arn.split(':')[4] except boto.exception.BotoServerError: # If call failed, then let's try to get the ARN from the metadata timeout = boto.config.getfloat( 'Boto', 'metadata_service_timeout', 1.0 ) attempts = boto.config.getint( 'Boto', 'metadata_service_num_attempts', 1 ) identity = boto.utils.get_instance_identity( timeout=timeout, num_retries=attempts ) try: account_id = identity['document']['accountId'] except KeyError: log.error('Failed to get account id from instance_identity in' ' boto_iam.get_account_id.') __context__[cache_key] = account_id return __context__[cache_key] def get_all_roles(path_prefix=None, region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM role details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_roles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _roles = conn.list_roles(path_prefix=path_prefix) roles = _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) while marker: _roles = conn.list_roles(path_prefix=path_prefix, marker=marker) roles = roles + _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) return roles def get_all_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM user details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_users ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _users = conn.get_all_users(path_prefix=path_prefix) users = _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) while marker: _users = conn.get_all_users(path_prefix=path_prefix, marker=marker) users = users + _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) return users def get_all_user_policies(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all user policies. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_user_policies myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_all_user_policies(user_name, marker, max_items) if not info: return False _list = info.list_user_policies_response.list_user_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policies for user %s.', user_name) return False def get_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user_policy myuser mypolicyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user_policy(user_name, policy_name) log.debug('Info for IAM user %s policy %s: %s.', user_name, policy_name, info) if not info: return False info = info.get_user_policy_response.get_user_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policy %s for IAM user %s.', policy_name, user_name) return False def put_user_policy(user_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_user_policy myuser policyname policyrules ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_user_policy(user_name, policy_name, policy_json) if created: log.info('Created policy %s for IAM user %s.', policy_name, user_name) return True log.error('Could not create policy %s for IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy %s for IAM user %s.', policy_name, user_name) return False def delete_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user_policy myuser mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_user_policy( user_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_user_policy(user_name, policy_name) log.info('Successfully deleted policy %s for IAM user %s.', policy_name, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM user %s.', policy_name, user_name) return False def upload_server_cert(cert_name, cert_body, private_key, cert_chain=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Upload a certificate to Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.upload_server_cert mycert_name crt priv_key :param cert_name: The name for the server certificate. Do not include the path in this value. :param cert_body: The contents of the public key certificate in PEM-encoded format. :param private_key: The contents of the private key in PEM-encoded format. :param cert_chain: The contents of the certificate chain. This is typically a concatenation of the PEM-encoded public key certificates of the chain. :param path: The path for the server certificate. :param region: The name of the region to connect to. :param key: The key to be used in order to connect :param keyid: The keyid to be used in order to connect :param profile: The profile that contains a dict of region, key, keyid :return: True / False ''' exists = get_server_certificate(cert_name, region, key, keyid, profile) if exists: return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.upload_server_cert(cert_name, cert_body, private_key, cert_chain) log.info('Created certificate %s.', cert_name) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to failed to create certificate %s.', cert_name) return False def list_server_certificates(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Lists the server certificates stored in IAM that have the specified path prefix. .. versionadded:: ??? :param path_prefix: The path prefix for filtering the results. For example: /company/servercerts would get all server certificates for which the path starts with /company/servercerts . This parameter is optional. If it is not included, it defaults to a slash (/), listing all server certificates. This parameter allows (per its regex pattern) a string of characters consisting of either a forward slash (/) by itself or a string that must begin and end with forward slashes. In addition, it can contain any ASCII character from the ! (u0021) through the DEL character (u007F), including most punctuation characters, digits, and upper and lowercased letters. CLI Example: .. code-block:: bash salt myminion boto_iam.list_server_certificates path_prefix=/somepath/ ''' retries = 10 sleep = 6 conn = __utils__['boto3.get_connection']('iam', region=region, key=key, keyid=keyid, profile=profile) Items = [] while retries: try: log.debug('Garnering list of IAM Server Certificates') IsTruncated = True while IsTruncated: kwargs = {'PathPrefix': path_prefix} ret = conn.list_server_certificates(**kwargs) Items += ret.get('ServerCertificateMetadataList', []) IsTruncated = ret.get('IsTruncated') kwargs.update({'Marker': ret.get('Marker')}) return Items except botocore.exceptions.ParamValidationError as err: raise SaltInvocationError(str(err)) except botocore.exceptions.ClientError as err: if retries and jmespath.search('Error.Code', err.response) == 'Throttling': retries -= 1 log.debug('Throttled by AWS API, retrying in %s seconds...', sleep) time.sleep(sleep) continue log.error('Failed to list IAM Server Certificates: %s', err.message) return None def get_server_certificate(cert_name, region=None, key=None, keyid=None, profile=None): ''' Returns certificate information from Amazon .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_server_certificate mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_server_certificate(cert_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get certificate %s information.', cert_name) return False def delete_server_cert(cert_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a certificate from Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_server_cert mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_server_cert(cert_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete certificate %s.', cert_name) return False def export_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM user details. Produces results that can be used to create an sls file. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.export_users --out=txt | sed "s/local: //" > iam_users.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() users = get_all_users(path_prefix, region, key, keyid, profile) for user in users: name = user.user_name _policies = conn.get_all_user_policies(name, max_items=100) _policies = _policies.list_user_policies_response.list_user_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_user_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_user_policy_response.get_user_policy_result.policy_document )) policies[policy_name] = _policy user_sls = [] user_sls.append({"name": name}) user_sls.append({"policies": policies}) user_sls.append({"path": user.path}) results["manage user " + name] = {"boto_iam.user_present": user_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def export_roles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM role details. Produces results that can be used to create an sls file. CLI Example: salt-call boto_iam.export_roles --out=txt | sed "s/local: //" > iam_roles.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() roles = get_all_roles(path_prefix, region, key, keyid, profile) for role in roles: name = role.role_name _policies = conn.list_role_policies(name, max_items=100) _policies = _policies.list_role_policies_response.list_role_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_role_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_role_policy_response.get_role_policy_result.policy_document )) policies[policy_name] = _policy role_sls = [] role_sls.append({"name": name}) role_sls.append({"policies": policies}) role_sls.append({'policy_document': salt.utils.json.loads(_unquote(role.assume_role_policy_document))}) role_sls.append({"path": role.path}) results["manage role " + name] = {"boto_iam_role.present": role_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def _get_policy_arn(name, region=None, key=None, keyid=None, profile=None): if name.startswith('arn:aws:iam:'): return name account_id = get_account_id( region=region, key=key, keyid=keyid, profile=profile ) return 'arn:aws:iam::{0}:policy/{1}'.format(account_id, name) def policy_exists(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return True except boto.exception.BotoServerError: return False def get_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return ret.get('get_policy_response', {}).get('get_policy_result', {}) except boto.exception.BotoServerError: return None def create_policy(policy_name, policy_document, path=None, description=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in 'path', 'description': if locals()[arg] is not None: params[arg] = locals()[arg] if policy_exists(policy_name, region, key, keyid, profile): return True try: conn.create_policy(policy_name, policy_document, **params) log.info('Created IAM policy %s.', policy_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s.', policy_name) return False return True def delete_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_exists(policy_arn, region, key, keyid, profile): return True try: conn.delete_policy(policy_arn) log.info('Deleted %s policy.', policy_name) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete %s policy: %s.', policy_name, aws.get('message')) return False return True def list_policies(region=None, key=None, keyid=None, profile=None): ''' List policies. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policies ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: policies = [] for ret in __utils__['boto.paged_call'](conn.list_policies): policies.append(ret.get('list_policies_response', {}).get('list_policies_result', {}).get('policies')) return policies except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to list policy versions.' log.error(msg) return [] def policy_version_exists(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.get_policy_version(policy_arn, version_id) return True except boto.exception.BotoServerError: return False def get_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy_version(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile), version_id) retval = ret.get('get_policy_version_response', {}).get('get_policy_version_result', {}).get('policy_version', {}) retval['document'] = _unquote(retval.get('document')) return {'policy_version': retval} except boto.exception.BotoServerError: return None def create_policy_version(policy_name, policy_document, set_as_default=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy version. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy_version mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in ('set_as_default',): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.create_policy_version(policy_arn, policy_document, **params) vid = ret.get('create_policy_version_response', {}).get('create_policy_version_result', {}).get('policy_version', {}).get('version_id') log.info('Created IAM policy %s version %s.', policy_name, vid) return {'created': True, 'version_id': vid} except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s version %s.', policy_name, vid) return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Delete a policy version. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_version_exists(policy_arn, version_id, region, key, keyid, profile): return True try: conn.delete_policy_version(policy_arn, version_id) log.info('Deleted IAM policy %s version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete IAM policy %s version %s: %s', policy_name, version_id, aws.get('message')) return False return True def list_policy_versions(policy_name, region=None, key=None, keyid=None, profile=None): ''' List versions of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policy_versions mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.list_policy_versions(policy_arn) return ret.get('list_policy_versions_response', {}).get('list_policy_versions_result', {}).get('versions') except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list versions for IAM policy %s.', policy_name) return [] def set_default_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Set the default version of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.set_default_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.set_default_policy_version(policy_arn, version_id) log.info('Set %s policy to version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to set %s policy to version %s: %s', policy_name, version_id, aws.get('message')) return False return True def attach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_user_policy(policy_arn, user_name) log.info('Attached policy %s to IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach %s policy to IAM user %s.', policy_name, user_name) return False return True def detach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_user_policy(policy_arn, user_name) log.info('Detached %s policy from IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach %s policy from IAM user %s.', policy_name, user_name) return False return True def attach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_group_policy(policy_arn, group_name) log.info('Attached policy %s to IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM group %s.', policy_name, group_name) return False return True def detach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_group_policy(policy_arn, group_name) log.info('Detached policy %s from IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM group %s.', policy_name, group_name) return False return True def attach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_role_policy(policy_arn, role_name) log.info('Attached policy %s to IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM role %s.', policy_name, role_name) return False return True def detach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_role_policy(policy_arn, role_name) log.info('Detached policy %s from IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM role %s.', policy_name, role_name) return False return True def list_entities_for_policy(policy_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities that a policy is attached to. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 params = {} for arg in ('path_prefix', 'entity_filter'): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) while retries: try: allret = { 'policy_groups': [], 'policy_users': [], 'policy_roles': [], } for ret in __utils__['boto.paged_call'](conn.list_entities_for_policy, policy_arn=policy_arn, **params): for k, v in six.iteritems(allret): v.extend(ret.get('list_entities_for_policy_response', {}).get('list_entities_for_policy_result', {}).get(k)) return allret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('Failed to list entities for IAM policy %s: %s', policy_name, e.message) return {} return {} def list_attached_user_policies(user_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given user. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'UserName': user_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedUserPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_user_policies_response', {}).get('list_attached_user_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM user %s.', user_name) return [] def list_attached_group_policies(group_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given group. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'GroupName': group_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedGroupPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_group_policies_response', {}).get('list_attached_group_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM group %s.', group_name) return [] def list_attached_role_policies(role_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'RoleName': role_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedRolePolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_role_policies_response', {}).get('list_attached_role_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM role %s.', role_name) return [] def create_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Create SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.create_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_saml_provider(saml_metadata_document, name) log.info('Successfully created %s SAML provider.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to create SAML provider %s.', name) return False def get_saml_provider_arn(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider_arn my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_saml_providers() for saml_provider in response.list_saml_providers_response.list_saml_providers_result.saml_provider_list: if saml_provider['arn'].endswith(':saml-provider/' + name): return saml_provider['arn'] return False except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to get ARN of SAML provider %s.', name) return False def delete_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Delete SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.delete_saml_provider my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return True conn.delete_saml_provider(saml_provider_arn) log.info('Successfully deleted SAML provider %s.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete SAML provider %s.', name) return False def list_saml_providers(region=None, key=None, keyid=None, profile=None): ''' List SAML providers. CLI Example: .. code-block:: bash salt myminion boto_iam.list_saml_providers ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: providers = [] info = conn.list_saml_providers() for arn in info['list_saml_providers_response']['list_saml_providers_result']['saml_provider_list']: providers.append(arn['arn'].rsplit('/', 1)[1]) return providers except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get list of SAML providers.') return False def get_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider document. CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider arn ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: provider = conn.get_saml_provider(name) return provider['get_saml_provider_response']['get_saml_provider_result']['saml_metadata_document'] except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get SAML provider document %s.', name) return False def update_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Update SAML provider. CLI Example: .. code-block:: bash salt myminion boto_iam.update_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return False if conn.update_saml_provider(name, saml_metadata_document): return True return False except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to update SAML provider %s.', name) return False
saltstack/salt
salt/modules/boto_iam.py
create_role
python
def create_role(name, policy_document=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Create an instance role. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if role_exists(name, region, key, keyid, profile): return True if not policy_document: policy_document = None try: conn.create_role(name, assume_role_policy_document=policy_document, path=path) log.info('Created IAM role %s.', name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to create IAM role %s.', name) return False
Create an instance role. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role myrole
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iam.py#L955-L980
[ "def role_exists(name, region=None, key=None, keyid=None, profile=None):\n '''\n Check to see if an IAM role exists.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_iam.role_exists myirole\n '''\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n try:\n conn.get_role(name)\n return True\n except boto.exception.BotoServerError:\n return False\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon IAM .. versionadded:: 2014.7.0 :configuration: This module accepts explicit iam 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 iam.keyid: GKTADJGHEIQSXMKKRBJ08H iam.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs iam.region: 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: boto ''' # keep lint from choking on _get_conn and _cache_id #pylint: disable=E0602 # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import salt libs from salt.ext import six import salt.utils.compat import salt.utils.json import salt.utils.odict as odict import salt.utils.versions from salt.exceptions import SaltInvocationError # Import third party libs # pylint: disable=unused-import from salt.ext.six.moves.urllib.parse import unquote as _unquote # pylint: disable=no-name-in-module try: import boto import boto.iam import boto3 import botocore logging.getLogger('boto').setLevel(logging.CRITICAL) logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=unused-import log = logging.getLogger(__name__) def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'iam', pack=__salt__) def instance_profile_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an instance profile exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: # Boto weirdly returns an exception here if an instance profile doesn't # exist. conn.get_instance_profile(name) return True except boto.exception.BotoServerError: return False def create_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Create an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.create_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if instance_profile_exists(name, region, key, keyid, profile): return True try: # This call returns an instance profile if successful and an exception # if not. It's annoying. conn.create_instance_profile(name) log.info('Created %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create %s instance profile.', name) return False return True def delete_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Delete an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not instance_profile_exists(name, region, key, keyid, profile): return True try: conn.delete_instance_profile(name) log.info('Deleted %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s instance profile.', name) return False return True def role_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an IAM role exists. CLI Example: .. code-block:: bash salt myminion boto_iam.role_exists myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_role(name) return True except boto.exception.BotoServerError: return False def describe_role(name, region=None, key=None, keyid=None, profile=None): ''' Get information for a role. CLI Example: .. code-block:: bash salt myminion boto_iam.describe_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_role(name) if not info: return False role = info.get_role_response.get_role_result.role role['assume_role_policy_document'] = salt.utils.json.loads(_unquote( role.assume_role_policy_document )) # If Sid wasn't defined by the user, boto will still return a Sid in # each policy. To properly check idempotently, let's remove the Sid # from the return if it's not actually set. for policy_key, policy in role['assume_role_policy_document'].items(): if policy_key == 'Statement': for val in policy: if 'Sid' in val and not val['Sid']: del val['Sid'] return role except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get %s information.', name) return False def create_user(user_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_user myuser ''' if not path: path = '/' if get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_user(user_name, path) log.info('Created IAM user : %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM user %s.', user_name) return False def get_all_access_keys(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all access keys from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_access_keys myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.get_all_access_keys(user_name, marker, max_items) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get access keys for IAM user %s.', user_name) return six.text_type(e) def create_access_key(user_name, region=None, key=None, keyid=None, profile=None): ''' Create access key id for a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.create_access_key(user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create access key.') return six.text_type(e) def delete_access_key(access_key_id, user_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete access key id from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_access_key(access_key_id, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete access key id %s.', access_key_id) return six.text_type(e) def delete_user(user_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user myuser ''' if not get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.delete_user(user_name) log.info('Deleted IAM user : %s .', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM user %s', user_name) return six.text_type(e) def get_user(user_name=None, region=None, key=None, keyid=None, profile=None): ''' Get user information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user(user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM user %s info.', user_name) return False def create_group(group_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_group group ''' if not path: path = '/' if get_group(group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_group(group_name, path) log.info('Created IAM group : %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM group %s.', group_name) return False def get_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group(group_name, max_items=1) if not info: return False return info['get_group_response']['get_group_result']['group'] except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_group_members(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: marker = None truncated = True users = [] while truncated: info = conn.get_group(group_name, marker=marker, max_items=1000) if not info: return False truncated = bool(info['get_group_response']['get_group_result']['is_truncated']) if truncated and 'marker' in info['get_group_response']['get_group_result']: marker = info['get_group_response']['get_group_result']['marker'] else: marker = None truncated = False users += info['get_group_response']['get_group_result']['users'] return users except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get members for IAM group %s.', group_name) return False def add_user_to_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Add user to group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.add_user_to_group myuser mygroup ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('Username : %s does not exist.', user_name) return False if user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.add_user_to_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add IAM user %s to group %s.', user_name, group_name) return False def user_exists_in_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Check if user exists in group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.user_exists_in_group myuser mygroup ''' # TODO this should probably use boto.iam.get_groups_for_user users = get_group_members( group_name=group_name, region=region, key=key, keyid=keyid, profile=profile ) if users: for _user in users: if user_name == _user['user_name']: log.debug('IAM user %s is already in IAM group %s.', user_name, group_name) return True return False def remove_user_from_group(group_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Remove user from group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.remove_user_from_group mygroup myuser ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist.', user_name) return False if not user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.remove_user_from_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove IAM user %s from group %s', user_name, group_name) return False def put_group_policy(group_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_group_policy mygroup policyname policyrules ''' group = get_group(group_name, region=region, key=key, keyid=keyid, profile=profile) if not group: log.error('Group %s does not exist', group_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_group_policy(group_name, policy_name, policy_json) if created: log.info('Created policy for IAM group %s.', group_name) return True log.error('Could not create policy for IAM group %s', group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy for IAM group %s', group_name) return False def delete_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group_policy mygroup mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_group_policy( group_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_group_policy(group_name, policy_name) log.info('Successfully deleted policy %s for IAM group %s.', policy_name, group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM group %s.', policy_name, group_name) return False def get_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group_policy mygroup policyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group_policy(group_name, policy_name) log.debug('info for group policy is : %s', info) if not info: return False info = info.get_group_policy_response.get_group_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_all_groups(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM group details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_groups ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _groups = conn.get_all_groups(path_prefix=path_prefix) groups = _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) while marker: _groups = conn.get_all_groups(path_prefix=path_prefix, marker=marker) groups = groups + _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) return groups def get_all_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.get_all_instance_profiles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) marker = False profiles = [] while marker is not None: marker = marker if marker else None p = conn.list_instance_profiles(path_prefix=path_prefix, marker=marker) res = p.list_instance_profiles_response.list_instance_profiles_result profiles += res.instance_profiles marker = getattr(res, 'marker', None) return profiles def list_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' List all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.list_instance_profiles ''' p = get_all_instance_profiles(path_prefix, region, key, keyid, profile) return [i['instance_profile_name'] for i in p] def get_all_group_policies(group_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a group. CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_group_policies mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False try: response = conn.get_all_group_policies(group_name) _list = response.list_group_policies_response.list_group_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def delete_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _group = get_group( group_name, region, key, keyid, profile ) if not _group: return True try: conn.delete_group(group_name) log.info('Successfully deleted IAM group %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM group %s.', group_name) return False def create_login_profile(user_name, password, region=None, key=None, keyid=None, profile=None): ''' Creates a login profile for the specified user, give the user the ability to access AWS services and the AWS Management Console. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_login_profile user_name password ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.create_login_profile(user_name, password) log.info('Created profile for IAM user %s.', user_name) return info except boto.exception.BotoServerError as e: log.debug(e) if 'Conflict' in e: log.info('Profile already exists for IAM user %s.', user_name) return 'Conflict' log.error('Failed to update profile for IAM user %s.', user_name) return False def delete_login_profile(user_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a login profile for the specified user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_login_profile user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.delete_login_profile(user_name) log.info('Deleted login profile for IAM user %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Login profile already deleted for IAM user %s.', user_name) return True log.error('Failed to delete login profile for IAM user %s.', user_name) return False def get_all_mfa_devices(user_name, region=None, key=None, keyid=None, profile=None): ''' Get all MFA devices associated with an IAM user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_mfa_devices user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: result = conn.get_all_mfa_devices(user_name) devices = result['list_mfa_devices_response']['list_mfa_devices_result']['mfa_devices'] return devices except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Could not find IAM user %s.', user_name) return [] log.error('Failed to get all MFA devices for IAM user %s.', user_name) return False def deactivate_mfa_device(user_name, serial, region=None, key=None, keyid=None, profile=None): ''' Deactivates the specified MFA device and removes it from association with the user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.deactivate_mfa_device user_name serial_num ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.deactivate_mfa_device(user_name, serial) log.info('Deactivated MFA device %s for IAM user %s.', serial, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('MFA device %s not associated with IAM user %s.', serial, user_name) return True log.error('Failed to deactivate MFA device %s for IAM user %s.', serial, user_name) return False def delete_virtual_mfa_device(serial, region=None, key=None, keyid=None, profile=None): ''' Deletes the specified virtual MFA device. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_virtual_mfa_device serial_num ''' conn = __utils__['boto3.get_connection_func']('iam')() try: conn.delete_virtual_mfa_device(SerialNumber=serial) log.info('Deleted virtual MFA device %s.', serial) return True except botocore.exceptions.ClientError as e: log.debug(e) if 'NoSuchEntity' in six.text_type(e): log.info('Virtual MFA device %s not found.', serial) return True log.error('Failed to delete virtual MFA device %s.', serial) return False def update_account_password_policy(allow_users_to_change_password=None, hard_expiry=None, max_password_age=None, minimum_password_length=None, password_reuse_prevention=None, require_lowercase_characters=None, require_numbers=None, require_symbols=None, require_uppercase_characters=None, region=None, key=None, keyid=None, profile=None): ''' Update the password policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_account_password_policy True ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.update_account_password_policy(allow_users_to_change_password, hard_expiry, max_password_age, minimum_password_length, password_reuse_prevention, require_lowercase_characters, require_numbers, require_symbols, require_uppercase_characters) log.info('The password policy has been updated.') return True except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy' log.error(msg) return False def get_account_policy(region=None, key=None, keyid=None, profile=None): ''' Get account policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_account_password_policy() return info.get_account_password_policy_response.get_account_password_policy_result.password_policy except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy.' log.error(msg) return False def delete_role(name, region=None, key=None, keyid=None, profile=None): ''' Delete an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(name, region, key, keyid, profile): return True try: conn.delete_role(name) log.info('Deleted %s IAM role.', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s IAM role.', name) return False def profile_associated(role_name, profile_name, region, key, keyid, profile): ''' Check to see if an instance profile is associated with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.profile_associated myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # The IAM module of boto doesn't return objects. Instead you need to grab # values through its properties. Sigh. try: profiles = conn.list_instance_profiles_for_role(role_name) except boto.exception.BotoServerError as e: log.debug(e) return False profiles = profiles.list_instance_profiles_for_role_response profiles = profiles.list_instance_profiles_for_role_result profiles = profiles.instance_profiles for profile in profiles: if profile.instance_profile_name == profile_name: return True return False def associate_profile_to_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Associate an instance profile with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.associate_profile_to_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if associated: return True else: try: conn.add_role_to_instance_profile(profile_name, role_name) log.info('Added %s instance profile to IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add %s instance profile to IAM role %s', profile_name, role_name) return False def disassociate_profile_from_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Disassociate an instance profile from an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.disassociate_profile_from_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if not associated: return True else: try: conn.remove_role_from_instance_profile(profile_name, role_name) log.info('Removed %s instance profile from IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove %s instance profile from IAM role %s.', profile_name, role_name) return False def list_role_policies(role_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_role_policies myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_role_policies(role_name) _list = response.list_role_policies_response.list_role_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def get_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.get_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: _policy = conn.get_role_policy(role_name, policy_name) # I _hate_ you for not giving me an object boto. _policy = _policy.get_role_policy_response.policy_document # Policy is url encoded _policy = _unquote(_policy) _policy = salt.utils.json.loads(_policy, object_pairs_hook=odict.OrderedDict) return _policy except boto.exception.BotoServerError: return {} def create_role_policy(role_name, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Create or modify a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role_policy myirole mypolicy '{"MyPolicy": "Statement": [{"Action": ["sqs:*"], "Effect": "Allow", "Resource": ["arn:aws:sqs:*:*:*"], "Sid": "MyPolicySqs1"}]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) mode = 'create' if _policy: if _policy == policy: return True mode = 'modify' if isinstance(policy, six.string_types): policy = salt.utils.json.loads(policy, object_pairs_hook=odict.OrderedDict) try: _policy = salt.utils.json.dumps(policy) conn.put_role_policy(role_name, policy_name, _policy) if mode == 'create': msg = 'Successfully added policy %s to IAM role %s.' else: msg = 'Successfully modified policy %s for IAM role %s.' log.info(msg, policy_name, role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to %s policy %s for IAM role %s.', mode, policy_name, role_name) return False def delete_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) if not _policy: return True try: conn.delete_role_policy(role_name, policy_name) log.info('Successfully deleted policy %s for IAM role %s.', policy_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM role %s.', policy_name, role_name) return False def update_assume_role_policy(role_name, policy_document, region=None, key=None, keyid=None, profile=None): ''' Update an assume role policy for a role. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_assume_role_policy myrole '{"Statement":"..."}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(policy_document, six.string_types): policy_document = salt.utils.json.loads(policy_document, object_pairs_hook=odict.OrderedDict) try: _policy_document = salt.utils.json.dumps(policy_document) conn.update_assume_role_policy(role_name, _policy_document) log.info('Successfully updated assume role policy for IAM role %s.', role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to update assume role policy for IAM role %s.', role_name) return False def build_policy(region=None, key=None, keyid=None, profile=None): ''' Build a default assume role policy. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.build_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if hasattr(conn, 'build_policy'): policy = salt.utils.json.loads(conn.build_policy()) elif hasattr(conn, '_build_policy'): policy = salt.utils.json.loads(conn._build_policy()) else: return {} # The format we get from build_policy isn't going to be what we get back # from AWS for the exact same policy. AWS converts single item list values # into strings, so let's do the same here. for key, policy_val in policy.items(): for statement in policy_val: if (isinstance(statement['Action'], list) and len(statement['Action']) == 1): statement['Action'] = statement['Action'][0] if (isinstance(statement['Principal']['Service'], list) and len(statement['Principal']['Service']) == 1): statement['Principal']['Service'] = statement['Principal']['Service'][0] # build_policy doesn't add a version field, which AWS is going to set to a # default value, when we get it back, so let's set it. policy['Version'] = '2008-10-17' return policy def get_account_id(region=None, key=None, keyid=None, profile=None): ''' Get a the AWS account id associated with the used credentials. CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_id ''' cache_key = 'boto_iam.account_id' if cache_key not in __context__: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_user() # The get_user call returns an user ARN: # arn:aws:iam::027050522557:user/salt-test arn = ret['get_user_response']['get_user_result']['user']['arn'] account_id = arn.split(':')[4] except boto.exception.BotoServerError: # If call failed, then let's try to get the ARN from the metadata timeout = boto.config.getfloat( 'Boto', 'metadata_service_timeout', 1.0 ) attempts = boto.config.getint( 'Boto', 'metadata_service_num_attempts', 1 ) identity = boto.utils.get_instance_identity( timeout=timeout, num_retries=attempts ) try: account_id = identity['document']['accountId'] except KeyError: log.error('Failed to get account id from instance_identity in' ' boto_iam.get_account_id.') __context__[cache_key] = account_id return __context__[cache_key] def get_all_roles(path_prefix=None, region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM role details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_roles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _roles = conn.list_roles(path_prefix=path_prefix) roles = _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) while marker: _roles = conn.list_roles(path_prefix=path_prefix, marker=marker) roles = roles + _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) return roles def get_all_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM user details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_users ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _users = conn.get_all_users(path_prefix=path_prefix) users = _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) while marker: _users = conn.get_all_users(path_prefix=path_prefix, marker=marker) users = users + _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) return users def get_all_user_policies(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all user policies. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_user_policies myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_all_user_policies(user_name, marker, max_items) if not info: return False _list = info.list_user_policies_response.list_user_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policies for user %s.', user_name) return False def get_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user_policy myuser mypolicyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user_policy(user_name, policy_name) log.debug('Info for IAM user %s policy %s: %s.', user_name, policy_name, info) if not info: return False info = info.get_user_policy_response.get_user_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policy %s for IAM user %s.', policy_name, user_name) return False def put_user_policy(user_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_user_policy myuser policyname policyrules ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_user_policy(user_name, policy_name, policy_json) if created: log.info('Created policy %s for IAM user %s.', policy_name, user_name) return True log.error('Could not create policy %s for IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy %s for IAM user %s.', policy_name, user_name) return False def delete_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user_policy myuser mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_user_policy( user_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_user_policy(user_name, policy_name) log.info('Successfully deleted policy %s for IAM user %s.', policy_name, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM user %s.', policy_name, user_name) return False def upload_server_cert(cert_name, cert_body, private_key, cert_chain=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Upload a certificate to Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.upload_server_cert mycert_name crt priv_key :param cert_name: The name for the server certificate. Do not include the path in this value. :param cert_body: The contents of the public key certificate in PEM-encoded format. :param private_key: The contents of the private key in PEM-encoded format. :param cert_chain: The contents of the certificate chain. This is typically a concatenation of the PEM-encoded public key certificates of the chain. :param path: The path for the server certificate. :param region: The name of the region to connect to. :param key: The key to be used in order to connect :param keyid: The keyid to be used in order to connect :param profile: The profile that contains a dict of region, key, keyid :return: True / False ''' exists = get_server_certificate(cert_name, region, key, keyid, profile) if exists: return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.upload_server_cert(cert_name, cert_body, private_key, cert_chain) log.info('Created certificate %s.', cert_name) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to failed to create certificate %s.', cert_name) return False def list_server_certificates(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Lists the server certificates stored in IAM that have the specified path prefix. .. versionadded:: ??? :param path_prefix: The path prefix for filtering the results. For example: /company/servercerts would get all server certificates for which the path starts with /company/servercerts . This parameter is optional. If it is not included, it defaults to a slash (/), listing all server certificates. This parameter allows (per its regex pattern) a string of characters consisting of either a forward slash (/) by itself or a string that must begin and end with forward slashes. In addition, it can contain any ASCII character from the ! (u0021) through the DEL character (u007F), including most punctuation characters, digits, and upper and lowercased letters. CLI Example: .. code-block:: bash salt myminion boto_iam.list_server_certificates path_prefix=/somepath/ ''' retries = 10 sleep = 6 conn = __utils__['boto3.get_connection']('iam', region=region, key=key, keyid=keyid, profile=profile) Items = [] while retries: try: log.debug('Garnering list of IAM Server Certificates') IsTruncated = True while IsTruncated: kwargs = {'PathPrefix': path_prefix} ret = conn.list_server_certificates(**kwargs) Items += ret.get('ServerCertificateMetadataList', []) IsTruncated = ret.get('IsTruncated') kwargs.update({'Marker': ret.get('Marker')}) return Items except botocore.exceptions.ParamValidationError as err: raise SaltInvocationError(str(err)) except botocore.exceptions.ClientError as err: if retries and jmespath.search('Error.Code', err.response) == 'Throttling': retries -= 1 log.debug('Throttled by AWS API, retrying in %s seconds...', sleep) time.sleep(sleep) continue log.error('Failed to list IAM Server Certificates: %s', err.message) return None def get_server_certificate(cert_name, region=None, key=None, keyid=None, profile=None): ''' Returns certificate information from Amazon .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_server_certificate mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_server_certificate(cert_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get certificate %s information.', cert_name) return False def delete_server_cert(cert_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a certificate from Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_server_cert mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_server_cert(cert_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete certificate %s.', cert_name) return False def export_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM user details. Produces results that can be used to create an sls file. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.export_users --out=txt | sed "s/local: //" > iam_users.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() users = get_all_users(path_prefix, region, key, keyid, profile) for user in users: name = user.user_name _policies = conn.get_all_user_policies(name, max_items=100) _policies = _policies.list_user_policies_response.list_user_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_user_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_user_policy_response.get_user_policy_result.policy_document )) policies[policy_name] = _policy user_sls = [] user_sls.append({"name": name}) user_sls.append({"policies": policies}) user_sls.append({"path": user.path}) results["manage user " + name] = {"boto_iam.user_present": user_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def export_roles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM role details. Produces results that can be used to create an sls file. CLI Example: salt-call boto_iam.export_roles --out=txt | sed "s/local: //" > iam_roles.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() roles = get_all_roles(path_prefix, region, key, keyid, profile) for role in roles: name = role.role_name _policies = conn.list_role_policies(name, max_items=100) _policies = _policies.list_role_policies_response.list_role_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_role_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_role_policy_response.get_role_policy_result.policy_document )) policies[policy_name] = _policy role_sls = [] role_sls.append({"name": name}) role_sls.append({"policies": policies}) role_sls.append({'policy_document': salt.utils.json.loads(_unquote(role.assume_role_policy_document))}) role_sls.append({"path": role.path}) results["manage role " + name] = {"boto_iam_role.present": role_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def _get_policy_arn(name, region=None, key=None, keyid=None, profile=None): if name.startswith('arn:aws:iam:'): return name account_id = get_account_id( region=region, key=key, keyid=keyid, profile=profile ) return 'arn:aws:iam::{0}:policy/{1}'.format(account_id, name) def policy_exists(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return True except boto.exception.BotoServerError: return False def get_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return ret.get('get_policy_response', {}).get('get_policy_result', {}) except boto.exception.BotoServerError: return None def create_policy(policy_name, policy_document, path=None, description=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in 'path', 'description': if locals()[arg] is not None: params[arg] = locals()[arg] if policy_exists(policy_name, region, key, keyid, profile): return True try: conn.create_policy(policy_name, policy_document, **params) log.info('Created IAM policy %s.', policy_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s.', policy_name) return False return True def delete_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_exists(policy_arn, region, key, keyid, profile): return True try: conn.delete_policy(policy_arn) log.info('Deleted %s policy.', policy_name) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete %s policy: %s.', policy_name, aws.get('message')) return False return True def list_policies(region=None, key=None, keyid=None, profile=None): ''' List policies. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policies ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: policies = [] for ret in __utils__['boto.paged_call'](conn.list_policies): policies.append(ret.get('list_policies_response', {}).get('list_policies_result', {}).get('policies')) return policies except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to list policy versions.' log.error(msg) return [] def policy_version_exists(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.get_policy_version(policy_arn, version_id) return True except boto.exception.BotoServerError: return False def get_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy_version(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile), version_id) retval = ret.get('get_policy_version_response', {}).get('get_policy_version_result', {}).get('policy_version', {}) retval['document'] = _unquote(retval.get('document')) return {'policy_version': retval} except boto.exception.BotoServerError: return None def create_policy_version(policy_name, policy_document, set_as_default=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy version. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy_version mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in ('set_as_default',): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.create_policy_version(policy_arn, policy_document, **params) vid = ret.get('create_policy_version_response', {}).get('create_policy_version_result', {}).get('policy_version', {}).get('version_id') log.info('Created IAM policy %s version %s.', policy_name, vid) return {'created': True, 'version_id': vid} except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s version %s.', policy_name, vid) return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Delete a policy version. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_version_exists(policy_arn, version_id, region, key, keyid, profile): return True try: conn.delete_policy_version(policy_arn, version_id) log.info('Deleted IAM policy %s version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete IAM policy %s version %s: %s', policy_name, version_id, aws.get('message')) return False return True def list_policy_versions(policy_name, region=None, key=None, keyid=None, profile=None): ''' List versions of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policy_versions mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.list_policy_versions(policy_arn) return ret.get('list_policy_versions_response', {}).get('list_policy_versions_result', {}).get('versions') except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list versions for IAM policy %s.', policy_name) return [] def set_default_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Set the default version of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.set_default_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.set_default_policy_version(policy_arn, version_id) log.info('Set %s policy to version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to set %s policy to version %s: %s', policy_name, version_id, aws.get('message')) return False return True def attach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_user_policy(policy_arn, user_name) log.info('Attached policy %s to IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach %s policy to IAM user %s.', policy_name, user_name) return False return True def detach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_user_policy(policy_arn, user_name) log.info('Detached %s policy from IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach %s policy from IAM user %s.', policy_name, user_name) return False return True def attach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_group_policy(policy_arn, group_name) log.info('Attached policy %s to IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM group %s.', policy_name, group_name) return False return True def detach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_group_policy(policy_arn, group_name) log.info('Detached policy %s from IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM group %s.', policy_name, group_name) return False return True def attach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_role_policy(policy_arn, role_name) log.info('Attached policy %s to IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM role %s.', policy_name, role_name) return False return True def detach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_role_policy(policy_arn, role_name) log.info('Detached policy %s from IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM role %s.', policy_name, role_name) return False return True def list_entities_for_policy(policy_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities that a policy is attached to. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 params = {} for arg in ('path_prefix', 'entity_filter'): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) while retries: try: allret = { 'policy_groups': [], 'policy_users': [], 'policy_roles': [], } for ret in __utils__['boto.paged_call'](conn.list_entities_for_policy, policy_arn=policy_arn, **params): for k, v in six.iteritems(allret): v.extend(ret.get('list_entities_for_policy_response', {}).get('list_entities_for_policy_result', {}).get(k)) return allret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('Failed to list entities for IAM policy %s: %s', policy_name, e.message) return {} return {} def list_attached_user_policies(user_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given user. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'UserName': user_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedUserPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_user_policies_response', {}).get('list_attached_user_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM user %s.', user_name) return [] def list_attached_group_policies(group_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given group. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'GroupName': group_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedGroupPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_group_policies_response', {}).get('list_attached_group_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM group %s.', group_name) return [] def list_attached_role_policies(role_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'RoleName': role_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedRolePolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_role_policies_response', {}).get('list_attached_role_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM role %s.', role_name) return [] def create_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Create SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.create_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_saml_provider(saml_metadata_document, name) log.info('Successfully created %s SAML provider.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to create SAML provider %s.', name) return False def get_saml_provider_arn(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider_arn my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_saml_providers() for saml_provider in response.list_saml_providers_response.list_saml_providers_result.saml_provider_list: if saml_provider['arn'].endswith(':saml-provider/' + name): return saml_provider['arn'] return False except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to get ARN of SAML provider %s.', name) return False def delete_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Delete SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.delete_saml_provider my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return True conn.delete_saml_provider(saml_provider_arn) log.info('Successfully deleted SAML provider %s.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete SAML provider %s.', name) return False def list_saml_providers(region=None, key=None, keyid=None, profile=None): ''' List SAML providers. CLI Example: .. code-block:: bash salt myminion boto_iam.list_saml_providers ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: providers = [] info = conn.list_saml_providers() for arn in info['list_saml_providers_response']['list_saml_providers_result']['saml_provider_list']: providers.append(arn['arn'].rsplit('/', 1)[1]) return providers except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get list of SAML providers.') return False def get_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider document. CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider arn ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: provider = conn.get_saml_provider(name) return provider['get_saml_provider_response']['get_saml_provider_result']['saml_metadata_document'] except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get SAML provider document %s.', name) return False def update_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Update SAML provider. CLI Example: .. code-block:: bash salt myminion boto_iam.update_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return False if conn.update_saml_provider(name, saml_metadata_document): return True return False except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to update SAML provider %s.', name) return False
saltstack/salt
salt/modules/boto_iam.py
delete_role
python
def delete_role(name, region=None, key=None, keyid=None, profile=None): ''' Delete an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(name, region, key, keyid, profile): return True try: conn.delete_role(name) log.info('Deleted %s IAM role.', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s IAM role.', name) return False
Delete an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role myirole
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iam.py#L983-L1004
[ "def role_exists(name, region=None, key=None, keyid=None, profile=None):\n '''\n Check to see if an IAM role exists.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_iam.role_exists myirole\n '''\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n try:\n conn.get_role(name)\n return True\n except boto.exception.BotoServerError:\n return False\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon IAM .. versionadded:: 2014.7.0 :configuration: This module accepts explicit iam 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 iam.keyid: GKTADJGHEIQSXMKKRBJ08H iam.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs iam.region: 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: boto ''' # keep lint from choking on _get_conn and _cache_id #pylint: disable=E0602 # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import salt libs from salt.ext import six import salt.utils.compat import salt.utils.json import salt.utils.odict as odict import salt.utils.versions from salt.exceptions import SaltInvocationError # Import third party libs # pylint: disable=unused-import from salt.ext.six.moves.urllib.parse import unquote as _unquote # pylint: disable=no-name-in-module try: import boto import boto.iam import boto3 import botocore logging.getLogger('boto').setLevel(logging.CRITICAL) logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=unused-import log = logging.getLogger(__name__) def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'iam', pack=__salt__) def instance_profile_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an instance profile exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: # Boto weirdly returns an exception here if an instance profile doesn't # exist. conn.get_instance_profile(name) return True except boto.exception.BotoServerError: return False def create_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Create an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.create_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if instance_profile_exists(name, region, key, keyid, profile): return True try: # This call returns an instance profile if successful and an exception # if not. It's annoying. conn.create_instance_profile(name) log.info('Created %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create %s instance profile.', name) return False return True def delete_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Delete an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not instance_profile_exists(name, region, key, keyid, profile): return True try: conn.delete_instance_profile(name) log.info('Deleted %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s instance profile.', name) return False return True def role_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an IAM role exists. CLI Example: .. code-block:: bash salt myminion boto_iam.role_exists myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_role(name) return True except boto.exception.BotoServerError: return False def describe_role(name, region=None, key=None, keyid=None, profile=None): ''' Get information for a role. CLI Example: .. code-block:: bash salt myminion boto_iam.describe_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_role(name) if not info: return False role = info.get_role_response.get_role_result.role role['assume_role_policy_document'] = salt.utils.json.loads(_unquote( role.assume_role_policy_document )) # If Sid wasn't defined by the user, boto will still return a Sid in # each policy. To properly check idempotently, let's remove the Sid # from the return if it's not actually set. for policy_key, policy in role['assume_role_policy_document'].items(): if policy_key == 'Statement': for val in policy: if 'Sid' in val and not val['Sid']: del val['Sid'] return role except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get %s information.', name) return False def create_user(user_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_user myuser ''' if not path: path = '/' if get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_user(user_name, path) log.info('Created IAM user : %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM user %s.', user_name) return False def get_all_access_keys(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all access keys from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_access_keys myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.get_all_access_keys(user_name, marker, max_items) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get access keys for IAM user %s.', user_name) return six.text_type(e) def create_access_key(user_name, region=None, key=None, keyid=None, profile=None): ''' Create access key id for a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.create_access_key(user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create access key.') return six.text_type(e) def delete_access_key(access_key_id, user_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete access key id from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_access_key(access_key_id, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete access key id %s.', access_key_id) return six.text_type(e) def delete_user(user_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user myuser ''' if not get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.delete_user(user_name) log.info('Deleted IAM user : %s .', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM user %s', user_name) return six.text_type(e) def get_user(user_name=None, region=None, key=None, keyid=None, profile=None): ''' Get user information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user(user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM user %s info.', user_name) return False def create_group(group_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_group group ''' if not path: path = '/' if get_group(group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_group(group_name, path) log.info('Created IAM group : %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM group %s.', group_name) return False def get_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group(group_name, max_items=1) if not info: return False return info['get_group_response']['get_group_result']['group'] except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_group_members(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: marker = None truncated = True users = [] while truncated: info = conn.get_group(group_name, marker=marker, max_items=1000) if not info: return False truncated = bool(info['get_group_response']['get_group_result']['is_truncated']) if truncated and 'marker' in info['get_group_response']['get_group_result']: marker = info['get_group_response']['get_group_result']['marker'] else: marker = None truncated = False users += info['get_group_response']['get_group_result']['users'] return users except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get members for IAM group %s.', group_name) return False def add_user_to_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Add user to group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.add_user_to_group myuser mygroup ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('Username : %s does not exist.', user_name) return False if user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.add_user_to_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add IAM user %s to group %s.', user_name, group_name) return False def user_exists_in_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Check if user exists in group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.user_exists_in_group myuser mygroup ''' # TODO this should probably use boto.iam.get_groups_for_user users = get_group_members( group_name=group_name, region=region, key=key, keyid=keyid, profile=profile ) if users: for _user in users: if user_name == _user['user_name']: log.debug('IAM user %s is already in IAM group %s.', user_name, group_name) return True return False def remove_user_from_group(group_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Remove user from group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.remove_user_from_group mygroup myuser ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist.', user_name) return False if not user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.remove_user_from_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove IAM user %s from group %s', user_name, group_name) return False def put_group_policy(group_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_group_policy mygroup policyname policyrules ''' group = get_group(group_name, region=region, key=key, keyid=keyid, profile=profile) if not group: log.error('Group %s does not exist', group_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_group_policy(group_name, policy_name, policy_json) if created: log.info('Created policy for IAM group %s.', group_name) return True log.error('Could not create policy for IAM group %s', group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy for IAM group %s', group_name) return False def delete_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group_policy mygroup mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_group_policy( group_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_group_policy(group_name, policy_name) log.info('Successfully deleted policy %s for IAM group %s.', policy_name, group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM group %s.', policy_name, group_name) return False def get_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group_policy mygroup policyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group_policy(group_name, policy_name) log.debug('info for group policy is : %s', info) if not info: return False info = info.get_group_policy_response.get_group_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_all_groups(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM group details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_groups ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _groups = conn.get_all_groups(path_prefix=path_prefix) groups = _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) while marker: _groups = conn.get_all_groups(path_prefix=path_prefix, marker=marker) groups = groups + _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) return groups def get_all_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.get_all_instance_profiles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) marker = False profiles = [] while marker is not None: marker = marker if marker else None p = conn.list_instance_profiles(path_prefix=path_prefix, marker=marker) res = p.list_instance_profiles_response.list_instance_profiles_result profiles += res.instance_profiles marker = getattr(res, 'marker', None) return profiles def list_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' List all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.list_instance_profiles ''' p = get_all_instance_profiles(path_prefix, region, key, keyid, profile) return [i['instance_profile_name'] for i in p] def get_all_group_policies(group_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a group. CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_group_policies mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False try: response = conn.get_all_group_policies(group_name) _list = response.list_group_policies_response.list_group_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def delete_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _group = get_group( group_name, region, key, keyid, profile ) if not _group: return True try: conn.delete_group(group_name) log.info('Successfully deleted IAM group %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM group %s.', group_name) return False def create_login_profile(user_name, password, region=None, key=None, keyid=None, profile=None): ''' Creates a login profile for the specified user, give the user the ability to access AWS services and the AWS Management Console. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_login_profile user_name password ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.create_login_profile(user_name, password) log.info('Created profile for IAM user %s.', user_name) return info except boto.exception.BotoServerError as e: log.debug(e) if 'Conflict' in e: log.info('Profile already exists for IAM user %s.', user_name) return 'Conflict' log.error('Failed to update profile for IAM user %s.', user_name) return False def delete_login_profile(user_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a login profile for the specified user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_login_profile user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.delete_login_profile(user_name) log.info('Deleted login profile for IAM user %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Login profile already deleted for IAM user %s.', user_name) return True log.error('Failed to delete login profile for IAM user %s.', user_name) return False def get_all_mfa_devices(user_name, region=None, key=None, keyid=None, profile=None): ''' Get all MFA devices associated with an IAM user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_mfa_devices user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: result = conn.get_all_mfa_devices(user_name) devices = result['list_mfa_devices_response']['list_mfa_devices_result']['mfa_devices'] return devices except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Could not find IAM user %s.', user_name) return [] log.error('Failed to get all MFA devices for IAM user %s.', user_name) return False def deactivate_mfa_device(user_name, serial, region=None, key=None, keyid=None, profile=None): ''' Deactivates the specified MFA device and removes it from association with the user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.deactivate_mfa_device user_name serial_num ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.deactivate_mfa_device(user_name, serial) log.info('Deactivated MFA device %s for IAM user %s.', serial, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('MFA device %s not associated with IAM user %s.', serial, user_name) return True log.error('Failed to deactivate MFA device %s for IAM user %s.', serial, user_name) return False def delete_virtual_mfa_device(serial, region=None, key=None, keyid=None, profile=None): ''' Deletes the specified virtual MFA device. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_virtual_mfa_device serial_num ''' conn = __utils__['boto3.get_connection_func']('iam')() try: conn.delete_virtual_mfa_device(SerialNumber=serial) log.info('Deleted virtual MFA device %s.', serial) return True except botocore.exceptions.ClientError as e: log.debug(e) if 'NoSuchEntity' in six.text_type(e): log.info('Virtual MFA device %s not found.', serial) return True log.error('Failed to delete virtual MFA device %s.', serial) return False def update_account_password_policy(allow_users_to_change_password=None, hard_expiry=None, max_password_age=None, minimum_password_length=None, password_reuse_prevention=None, require_lowercase_characters=None, require_numbers=None, require_symbols=None, require_uppercase_characters=None, region=None, key=None, keyid=None, profile=None): ''' Update the password policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_account_password_policy True ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.update_account_password_policy(allow_users_to_change_password, hard_expiry, max_password_age, minimum_password_length, password_reuse_prevention, require_lowercase_characters, require_numbers, require_symbols, require_uppercase_characters) log.info('The password policy has been updated.') return True except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy' log.error(msg) return False def get_account_policy(region=None, key=None, keyid=None, profile=None): ''' Get account policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_account_password_policy() return info.get_account_password_policy_response.get_account_password_policy_result.password_policy except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy.' log.error(msg) return False def create_role(name, policy_document=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Create an instance role. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if role_exists(name, region, key, keyid, profile): return True if not policy_document: policy_document = None try: conn.create_role(name, assume_role_policy_document=policy_document, path=path) log.info('Created IAM role %s.', name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to create IAM role %s.', name) return False def profile_associated(role_name, profile_name, region, key, keyid, profile): ''' Check to see if an instance profile is associated with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.profile_associated myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # The IAM module of boto doesn't return objects. Instead you need to grab # values through its properties. Sigh. try: profiles = conn.list_instance_profiles_for_role(role_name) except boto.exception.BotoServerError as e: log.debug(e) return False profiles = profiles.list_instance_profiles_for_role_response profiles = profiles.list_instance_profiles_for_role_result profiles = profiles.instance_profiles for profile in profiles: if profile.instance_profile_name == profile_name: return True return False def associate_profile_to_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Associate an instance profile with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.associate_profile_to_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if associated: return True else: try: conn.add_role_to_instance_profile(profile_name, role_name) log.info('Added %s instance profile to IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add %s instance profile to IAM role %s', profile_name, role_name) return False def disassociate_profile_from_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Disassociate an instance profile from an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.disassociate_profile_from_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if not associated: return True else: try: conn.remove_role_from_instance_profile(profile_name, role_name) log.info('Removed %s instance profile from IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove %s instance profile from IAM role %s.', profile_name, role_name) return False def list_role_policies(role_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_role_policies myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_role_policies(role_name) _list = response.list_role_policies_response.list_role_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def get_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.get_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: _policy = conn.get_role_policy(role_name, policy_name) # I _hate_ you for not giving me an object boto. _policy = _policy.get_role_policy_response.policy_document # Policy is url encoded _policy = _unquote(_policy) _policy = salt.utils.json.loads(_policy, object_pairs_hook=odict.OrderedDict) return _policy except boto.exception.BotoServerError: return {} def create_role_policy(role_name, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Create or modify a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role_policy myirole mypolicy '{"MyPolicy": "Statement": [{"Action": ["sqs:*"], "Effect": "Allow", "Resource": ["arn:aws:sqs:*:*:*"], "Sid": "MyPolicySqs1"}]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) mode = 'create' if _policy: if _policy == policy: return True mode = 'modify' if isinstance(policy, six.string_types): policy = salt.utils.json.loads(policy, object_pairs_hook=odict.OrderedDict) try: _policy = salt.utils.json.dumps(policy) conn.put_role_policy(role_name, policy_name, _policy) if mode == 'create': msg = 'Successfully added policy %s to IAM role %s.' else: msg = 'Successfully modified policy %s for IAM role %s.' log.info(msg, policy_name, role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to %s policy %s for IAM role %s.', mode, policy_name, role_name) return False def delete_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) if not _policy: return True try: conn.delete_role_policy(role_name, policy_name) log.info('Successfully deleted policy %s for IAM role %s.', policy_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM role %s.', policy_name, role_name) return False def update_assume_role_policy(role_name, policy_document, region=None, key=None, keyid=None, profile=None): ''' Update an assume role policy for a role. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_assume_role_policy myrole '{"Statement":"..."}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(policy_document, six.string_types): policy_document = salt.utils.json.loads(policy_document, object_pairs_hook=odict.OrderedDict) try: _policy_document = salt.utils.json.dumps(policy_document) conn.update_assume_role_policy(role_name, _policy_document) log.info('Successfully updated assume role policy for IAM role %s.', role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to update assume role policy for IAM role %s.', role_name) return False def build_policy(region=None, key=None, keyid=None, profile=None): ''' Build a default assume role policy. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.build_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if hasattr(conn, 'build_policy'): policy = salt.utils.json.loads(conn.build_policy()) elif hasattr(conn, '_build_policy'): policy = salt.utils.json.loads(conn._build_policy()) else: return {} # The format we get from build_policy isn't going to be what we get back # from AWS for the exact same policy. AWS converts single item list values # into strings, so let's do the same here. for key, policy_val in policy.items(): for statement in policy_val: if (isinstance(statement['Action'], list) and len(statement['Action']) == 1): statement['Action'] = statement['Action'][0] if (isinstance(statement['Principal']['Service'], list) and len(statement['Principal']['Service']) == 1): statement['Principal']['Service'] = statement['Principal']['Service'][0] # build_policy doesn't add a version field, which AWS is going to set to a # default value, when we get it back, so let's set it. policy['Version'] = '2008-10-17' return policy def get_account_id(region=None, key=None, keyid=None, profile=None): ''' Get a the AWS account id associated with the used credentials. CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_id ''' cache_key = 'boto_iam.account_id' if cache_key not in __context__: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_user() # The get_user call returns an user ARN: # arn:aws:iam::027050522557:user/salt-test arn = ret['get_user_response']['get_user_result']['user']['arn'] account_id = arn.split(':')[4] except boto.exception.BotoServerError: # If call failed, then let's try to get the ARN from the metadata timeout = boto.config.getfloat( 'Boto', 'metadata_service_timeout', 1.0 ) attempts = boto.config.getint( 'Boto', 'metadata_service_num_attempts', 1 ) identity = boto.utils.get_instance_identity( timeout=timeout, num_retries=attempts ) try: account_id = identity['document']['accountId'] except KeyError: log.error('Failed to get account id from instance_identity in' ' boto_iam.get_account_id.') __context__[cache_key] = account_id return __context__[cache_key] def get_all_roles(path_prefix=None, region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM role details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_roles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _roles = conn.list_roles(path_prefix=path_prefix) roles = _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) while marker: _roles = conn.list_roles(path_prefix=path_prefix, marker=marker) roles = roles + _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) return roles def get_all_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM user details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_users ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _users = conn.get_all_users(path_prefix=path_prefix) users = _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) while marker: _users = conn.get_all_users(path_prefix=path_prefix, marker=marker) users = users + _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) return users def get_all_user_policies(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all user policies. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_user_policies myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_all_user_policies(user_name, marker, max_items) if not info: return False _list = info.list_user_policies_response.list_user_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policies for user %s.', user_name) return False def get_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user_policy myuser mypolicyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user_policy(user_name, policy_name) log.debug('Info for IAM user %s policy %s: %s.', user_name, policy_name, info) if not info: return False info = info.get_user_policy_response.get_user_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policy %s for IAM user %s.', policy_name, user_name) return False def put_user_policy(user_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_user_policy myuser policyname policyrules ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_user_policy(user_name, policy_name, policy_json) if created: log.info('Created policy %s for IAM user %s.', policy_name, user_name) return True log.error('Could not create policy %s for IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy %s for IAM user %s.', policy_name, user_name) return False def delete_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user_policy myuser mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_user_policy( user_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_user_policy(user_name, policy_name) log.info('Successfully deleted policy %s for IAM user %s.', policy_name, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM user %s.', policy_name, user_name) return False def upload_server_cert(cert_name, cert_body, private_key, cert_chain=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Upload a certificate to Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.upload_server_cert mycert_name crt priv_key :param cert_name: The name for the server certificate. Do not include the path in this value. :param cert_body: The contents of the public key certificate in PEM-encoded format. :param private_key: The contents of the private key in PEM-encoded format. :param cert_chain: The contents of the certificate chain. This is typically a concatenation of the PEM-encoded public key certificates of the chain. :param path: The path for the server certificate. :param region: The name of the region to connect to. :param key: The key to be used in order to connect :param keyid: The keyid to be used in order to connect :param profile: The profile that contains a dict of region, key, keyid :return: True / False ''' exists = get_server_certificate(cert_name, region, key, keyid, profile) if exists: return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.upload_server_cert(cert_name, cert_body, private_key, cert_chain) log.info('Created certificate %s.', cert_name) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to failed to create certificate %s.', cert_name) return False def list_server_certificates(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Lists the server certificates stored in IAM that have the specified path prefix. .. versionadded:: ??? :param path_prefix: The path prefix for filtering the results. For example: /company/servercerts would get all server certificates for which the path starts with /company/servercerts . This parameter is optional. If it is not included, it defaults to a slash (/), listing all server certificates. This parameter allows (per its regex pattern) a string of characters consisting of either a forward slash (/) by itself or a string that must begin and end with forward slashes. In addition, it can contain any ASCII character from the ! (u0021) through the DEL character (u007F), including most punctuation characters, digits, and upper and lowercased letters. CLI Example: .. code-block:: bash salt myminion boto_iam.list_server_certificates path_prefix=/somepath/ ''' retries = 10 sleep = 6 conn = __utils__['boto3.get_connection']('iam', region=region, key=key, keyid=keyid, profile=profile) Items = [] while retries: try: log.debug('Garnering list of IAM Server Certificates') IsTruncated = True while IsTruncated: kwargs = {'PathPrefix': path_prefix} ret = conn.list_server_certificates(**kwargs) Items += ret.get('ServerCertificateMetadataList', []) IsTruncated = ret.get('IsTruncated') kwargs.update({'Marker': ret.get('Marker')}) return Items except botocore.exceptions.ParamValidationError as err: raise SaltInvocationError(str(err)) except botocore.exceptions.ClientError as err: if retries and jmespath.search('Error.Code', err.response) == 'Throttling': retries -= 1 log.debug('Throttled by AWS API, retrying in %s seconds...', sleep) time.sleep(sleep) continue log.error('Failed to list IAM Server Certificates: %s', err.message) return None def get_server_certificate(cert_name, region=None, key=None, keyid=None, profile=None): ''' Returns certificate information from Amazon .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_server_certificate mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_server_certificate(cert_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get certificate %s information.', cert_name) return False def delete_server_cert(cert_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a certificate from Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_server_cert mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_server_cert(cert_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete certificate %s.', cert_name) return False def export_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM user details. Produces results that can be used to create an sls file. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.export_users --out=txt | sed "s/local: //" > iam_users.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() users = get_all_users(path_prefix, region, key, keyid, profile) for user in users: name = user.user_name _policies = conn.get_all_user_policies(name, max_items=100) _policies = _policies.list_user_policies_response.list_user_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_user_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_user_policy_response.get_user_policy_result.policy_document )) policies[policy_name] = _policy user_sls = [] user_sls.append({"name": name}) user_sls.append({"policies": policies}) user_sls.append({"path": user.path}) results["manage user " + name] = {"boto_iam.user_present": user_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def export_roles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM role details. Produces results that can be used to create an sls file. CLI Example: salt-call boto_iam.export_roles --out=txt | sed "s/local: //" > iam_roles.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() roles = get_all_roles(path_prefix, region, key, keyid, profile) for role in roles: name = role.role_name _policies = conn.list_role_policies(name, max_items=100) _policies = _policies.list_role_policies_response.list_role_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_role_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_role_policy_response.get_role_policy_result.policy_document )) policies[policy_name] = _policy role_sls = [] role_sls.append({"name": name}) role_sls.append({"policies": policies}) role_sls.append({'policy_document': salt.utils.json.loads(_unquote(role.assume_role_policy_document))}) role_sls.append({"path": role.path}) results["manage role " + name] = {"boto_iam_role.present": role_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def _get_policy_arn(name, region=None, key=None, keyid=None, profile=None): if name.startswith('arn:aws:iam:'): return name account_id = get_account_id( region=region, key=key, keyid=keyid, profile=profile ) return 'arn:aws:iam::{0}:policy/{1}'.format(account_id, name) def policy_exists(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return True except boto.exception.BotoServerError: return False def get_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return ret.get('get_policy_response', {}).get('get_policy_result', {}) except boto.exception.BotoServerError: return None def create_policy(policy_name, policy_document, path=None, description=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in 'path', 'description': if locals()[arg] is not None: params[arg] = locals()[arg] if policy_exists(policy_name, region, key, keyid, profile): return True try: conn.create_policy(policy_name, policy_document, **params) log.info('Created IAM policy %s.', policy_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s.', policy_name) return False return True def delete_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_exists(policy_arn, region, key, keyid, profile): return True try: conn.delete_policy(policy_arn) log.info('Deleted %s policy.', policy_name) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete %s policy: %s.', policy_name, aws.get('message')) return False return True def list_policies(region=None, key=None, keyid=None, profile=None): ''' List policies. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policies ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: policies = [] for ret in __utils__['boto.paged_call'](conn.list_policies): policies.append(ret.get('list_policies_response', {}).get('list_policies_result', {}).get('policies')) return policies except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to list policy versions.' log.error(msg) return [] def policy_version_exists(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.get_policy_version(policy_arn, version_id) return True except boto.exception.BotoServerError: return False def get_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy_version(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile), version_id) retval = ret.get('get_policy_version_response', {}).get('get_policy_version_result', {}).get('policy_version', {}) retval['document'] = _unquote(retval.get('document')) return {'policy_version': retval} except boto.exception.BotoServerError: return None def create_policy_version(policy_name, policy_document, set_as_default=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy version. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy_version mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in ('set_as_default',): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.create_policy_version(policy_arn, policy_document, **params) vid = ret.get('create_policy_version_response', {}).get('create_policy_version_result', {}).get('policy_version', {}).get('version_id') log.info('Created IAM policy %s version %s.', policy_name, vid) return {'created': True, 'version_id': vid} except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s version %s.', policy_name, vid) return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Delete a policy version. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_version_exists(policy_arn, version_id, region, key, keyid, profile): return True try: conn.delete_policy_version(policy_arn, version_id) log.info('Deleted IAM policy %s version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete IAM policy %s version %s: %s', policy_name, version_id, aws.get('message')) return False return True def list_policy_versions(policy_name, region=None, key=None, keyid=None, profile=None): ''' List versions of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policy_versions mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.list_policy_versions(policy_arn) return ret.get('list_policy_versions_response', {}).get('list_policy_versions_result', {}).get('versions') except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list versions for IAM policy %s.', policy_name) return [] def set_default_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Set the default version of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.set_default_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.set_default_policy_version(policy_arn, version_id) log.info('Set %s policy to version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to set %s policy to version %s: %s', policy_name, version_id, aws.get('message')) return False return True def attach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_user_policy(policy_arn, user_name) log.info('Attached policy %s to IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach %s policy to IAM user %s.', policy_name, user_name) return False return True def detach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_user_policy(policy_arn, user_name) log.info('Detached %s policy from IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach %s policy from IAM user %s.', policy_name, user_name) return False return True def attach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_group_policy(policy_arn, group_name) log.info('Attached policy %s to IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM group %s.', policy_name, group_name) return False return True def detach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_group_policy(policy_arn, group_name) log.info('Detached policy %s from IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM group %s.', policy_name, group_name) return False return True def attach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_role_policy(policy_arn, role_name) log.info('Attached policy %s to IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM role %s.', policy_name, role_name) return False return True def detach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_role_policy(policy_arn, role_name) log.info('Detached policy %s from IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM role %s.', policy_name, role_name) return False return True def list_entities_for_policy(policy_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities that a policy is attached to. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 params = {} for arg in ('path_prefix', 'entity_filter'): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) while retries: try: allret = { 'policy_groups': [], 'policy_users': [], 'policy_roles': [], } for ret in __utils__['boto.paged_call'](conn.list_entities_for_policy, policy_arn=policy_arn, **params): for k, v in six.iteritems(allret): v.extend(ret.get('list_entities_for_policy_response', {}).get('list_entities_for_policy_result', {}).get(k)) return allret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('Failed to list entities for IAM policy %s: %s', policy_name, e.message) return {} return {} def list_attached_user_policies(user_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given user. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'UserName': user_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedUserPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_user_policies_response', {}).get('list_attached_user_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM user %s.', user_name) return [] def list_attached_group_policies(group_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given group. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'GroupName': group_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedGroupPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_group_policies_response', {}).get('list_attached_group_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM group %s.', group_name) return [] def list_attached_role_policies(role_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'RoleName': role_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedRolePolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_role_policies_response', {}).get('list_attached_role_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM role %s.', role_name) return [] def create_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Create SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.create_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_saml_provider(saml_metadata_document, name) log.info('Successfully created %s SAML provider.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to create SAML provider %s.', name) return False def get_saml_provider_arn(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider_arn my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_saml_providers() for saml_provider in response.list_saml_providers_response.list_saml_providers_result.saml_provider_list: if saml_provider['arn'].endswith(':saml-provider/' + name): return saml_provider['arn'] return False except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to get ARN of SAML provider %s.', name) return False def delete_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Delete SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.delete_saml_provider my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return True conn.delete_saml_provider(saml_provider_arn) log.info('Successfully deleted SAML provider %s.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete SAML provider %s.', name) return False def list_saml_providers(region=None, key=None, keyid=None, profile=None): ''' List SAML providers. CLI Example: .. code-block:: bash salt myminion boto_iam.list_saml_providers ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: providers = [] info = conn.list_saml_providers() for arn in info['list_saml_providers_response']['list_saml_providers_result']['saml_provider_list']: providers.append(arn['arn'].rsplit('/', 1)[1]) return providers except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get list of SAML providers.') return False def get_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider document. CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider arn ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: provider = conn.get_saml_provider(name) return provider['get_saml_provider_response']['get_saml_provider_result']['saml_metadata_document'] except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get SAML provider document %s.', name) return False def update_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Update SAML provider. CLI Example: .. code-block:: bash salt myminion boto_iam.update_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return False if conn.update_saml_provider(name, saml_metadata_document): return True return False except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to update SAML provider %s.', name) return False
saltstack/salt
salt/modules/boto_iam.py
profile_associated
python
def profile_associated(role_name, profile_name, region, key, keyid, profile): ''' Check to see if an instance profile is associated with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.profile_associated myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # The IAM module of boto doesn't return objects. Instead you need to grab # values through its properties. Sigh. try: profiles = conn.list_instance_profiles_for_role(role_name) except boto.exception.BotoServerError as e: log.debug(e) return False profiles = profiles.list_instance_profiles_for_role_response profiles = profiles.list_instance_profiles_for_role_result profiles = profiles.instance_profiles for profile in profiles: if profile.instance_profile_name == profile_name: return True return False
Check to see if an instance profile is associated with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.profile_associated myirole myiprofile
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iam.py#L1007-L1032
null
# -*- coding: utf-8 -*- ''' Connection module for Amazon IAM .. versionadded:: 2014.7.0 :configuration: This module accepts explicit iam 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 iam.keyid: GKTADJGHEIQSXMKKRBJ08H iam.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs iam.region: 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: boto ''' # keep lint from choking on _get_conn and _cache_id #pylint: disable=E0602 # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import salt libs from salt.ext import six import salt.utils.compat import salt.utils.json import salt.utils.odict as odict import salt.utils.versions from salt.exceptions import SaltInvocationError # Import third party libs # pylint: disable=unused-import from salt.ext.six.moves.urllib.parse import unquote as _unquote # pylint: disable=no-name-in-module try: import boto import boto.iam import boto3 import botocore logging.getLogger('boto').setLevel(logging.CRITICAL) logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=unused-import log = logging.getLogger(__name__) def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'iam', pack=__salt__) def instance_profile_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an instance profile exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: # Boto weirdly returns an exception here if an instance profile doesn't # exist. conn.get_instance_profile(name) return True except boto.exception.BotoServerError: return False def create_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Create an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.create_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if instance_profile_exists(name, region, key, keyid, profile): return True try: # This call returns an instance profile if successful and an exception # if not. It's annoying. conn.create_instance_profile(name) log.info('Created %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create %s instance profile.', name) return False return True def delete_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Delete an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not instance_profile_exists(name, region, key, keyid, profile): return True try: conn.delete_instance_profile(name) log.info('Deleted %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s instance profile.', name) return False return True def role_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an IAM role exists. CLI Example: .. code-block:: bash salt myminion boto_iam.role_exists myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_role(name) return True except boto.exception.BotoServerError: return False def describe_role(name, region=None, key=None, keyid=None, profile=None): ''' Get information for a role. CLI Example: .. code-block:: bash salt myminion boto_iam.describe_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_role(name) if not info: return False role = info.get_role_response.get_role_result.role role['assume_role_policy_document'] = salt.utils.json.loads(_unquote( role.assume_role_policy_document )) # If Sid wasn't defined by the user, boto will still return a Sid in # each policy. To properly check idempotently, let's remove the Sid # from the return if it's not actually set. for policy_key, policy in role['assume_role_policy_document'].items(): if policy_key == 'Statement': for val in policy: if 'Sid' in val and not val['Sid']: del val['Sid'] return role except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get %s information.', name) return False def create_user(user_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_user myuser ''' if not path: path = '/' if get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_user(user_name, path) log.info('Created IAM user : %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM user %s.', user_name) return False def get_all_access_keys(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all access keys from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_access_keys myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.get_all_access_keys(user_name, marker, max_items) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get access keys for IAM user %s.', user_name) return six.text_type(e) def create_access_key(user_name, region=None, key=None, keyid=None, profile=None): ''' Create access key id for a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.create_access_key(user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create access key.') return six.text_type(e) def delete_access_key(access_key_id, user_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete access key id from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_access_key(access_key_id, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete access key id %s.', access_key_id) return six.text_type(e) def delete_user(user_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user myuser ''' if not get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.delete_user(user_name) log.info('Deleted IAM user : %s .', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM user %s', user_name) return six.text_type(e) def get_user(user_name=None, region=None, key=None, keyid=None, profile=None): ''' Get user information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user(user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM user %s info.', user_name) return False def create_group(group_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_group group ''' if not path: path = '/' if get_group(group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_group(group_name, path) log.info('Created IAM group : %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM group %s.', group_name) return False def get_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group(group_name, max_items=1) if not info: return False return info['get_group_response']['get_group_result']['group'] except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_group_members(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: marker = None truncated = True users = [] while truncated: info = conn.get_group(group_name, marker=marker, max_items=1000) if not info: return False truncated = bool(info['get_group_response']['get_group_result']['is_truncated']) if truncated and 'marker' in info['get_group_response']['get_group_result']: marker = info['get_group_response']['get_group_result']['marker'] else: marker = None truncated = False users += info['get_group_response']['get_group_result']['users'] return users except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get members for IAM group %s.', group_name) return False def add_user_to_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Add user to group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.add_user_to_group myuser mygroup ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('Username : %s does not exist.', user_name) return False if user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.add_user_to_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add IAM user %s to group %s.', user_name, group_name) return False def user_exists_in_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Check if user exists in group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.user_exists_in_group myuser mygroup ''' # TODO this should probably use boto.iam.get_groups_for_user users = get_group_members( group_name=group_name, region=region, key=key, keyid=keyid, profile=profile ) if users: for _user in users: if user_name == _user['user_name']: log.debug('IAM user %s is already in IAM group %s.', user_name, group_name) return True return False def remove_user_from_group(group_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Remove user from group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.remove_user_from_group mygroup myuser ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist.', user_name) return False if not user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.remove_user_from_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove IAM user %s from group %s', user_name, group_name) return False def put_group_policy(group_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_group_policy mygroup policyname policyrules ''' group = get_group(group_name, region=region, key=key, keyid=keyid, profile=profile) if not group: log.error('Group %s does not exist', group_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_group_policy(group_name, policy_name, policy_json) if created: log.info('Created policy for IAM group %s.', group_name) return True log.error('Could not create policy for IAM group %s', group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy for IAM group %s', group_name) return False def delete_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group_policy mygroup mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_group_policy( group_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_group_policy(group_name, policy_name) log.info('Successfully deleted policy %s for IAM group %s.', policy_name, group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM group %s.', policy_name, group_name) return False def get_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group_policy mygroup policyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group_policy(group_name, policy_name) log.debug('info for group policy is : %s', info) if not info: return False info = info.get_group_policy_response.get_group_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_all_groups(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM group details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_groups ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _groups = conn.get_all_groups(path_prefix=path_prefix) groups = _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) while marker: _groups = conn.get_all_groups(path_prefix=path_prefix, marker=marker) groups = groups + _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) return groups def get_all_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.get_all_instance_profiles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) marker = False profiles = [] while marker is not None: marker = marker if marker else None p = conn.list_instance_profiles(path_prefix=path_prefix, marker=marker) res = p.list_instance_profiles_response.list_instance_profiles_result profiles += res.instance_profiles marker = getattr(res, 'marker', None) return profiles def list_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' List all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.list_instance_profiles ''' p = get_all_instance_profiles(path_prefix, region, key, keyid, profile) return [i['instance_profile_name'] for i in p] def get_all_group_policies(group_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a group. CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_group_policies mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False try: response = conn.get_all_group_policies(group_name) _list = response.list_group_policies_response.list_group_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def delete_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _group = get_group( group_name, region, key, keyid, profile ) if not _group: return True try: conn.delete_group(group_name) log.info('Successfully deleted IAM group %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM group %s.', group_name) return False def create_login_profile(user_name, password, region=None, key=None, keyid=None, profile=None): ''' Creates a login profile for the specified user, give the user the ability to access AWS services and the AWS Management Console. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_login_profile user_name password ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.create_login_profile(user_name, password) log.info('Created profile for IAM user %s.', user_name) return info except boto.exception.BotoServerError as e: log.debug(e) if 'Conflict' in e: log.info('Profile already exists for IAM user %s.', user_name) return 'Conflict' log.error('Failed to update profile for IAM user %s.', user_name) return False def delete_login_profile(user_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a login profile for the specified user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_login_profile user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.delete_login_profile(user_name) log.info('Deleted login profile for IAM user %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Login profile already deleted for IAM user %s.', user_name) return True log.error('Failed to delete login profile for IAM user %s.', user_name) return False def get_all_mfa_devices(user_name, region=None, key=None, keyid=None, profile=None): ''' Get all MFA devices associated with an IAM user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_mfa_devices user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: result = conn.get_all_mfa_devices(user_name) devices = result['list_mfa_devices_response']['list_mfa_devices_result']['mfa_devices'] return devices except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Could not find IAM user %s.', user_name) return [] log.error('Failed to get all MFA devices for IAM user %s.', user_name) return False def deactivate_mfa_device(user_name, serial, region=None, key=None, keyid=None, profile=None): ''' Deactivates the specified MFA device and removes it from association with the user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.deactivate_mfa_device user_name serial_num ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.deactivate_mfa_device(user_name, serial) log.info('Deactivated MFA device %s for IAM user %s.', serial, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('MFA device %s not associated with IAM user %s.', serial, user_name) return True log.error('Failed to deactivate MFA device %s for IAM user %s.', serial, user_name) return False def delete_virtual_mfa_device(serial, region=None, key=None, keyid=None, profile=None): ''' Deletes the specified virtual MFA device. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_virtual_mfa_device serial_num ''' conn = __utils__['boto3.get_connection_func']('iam')() try: conn.delete_virtual_mfa_device(SerialNumber=serial) log.info('Deleted virtual MFA device %s.', serial) return True except botocore.exceptions.ClientError as e: log.debug(e) if 'NoSuchEntity' in six.text_type(e): log.info('Virtual MFA device %s not found.', serial) return True log.error('Failed to delete virtual MFA device %s.', serial) return False def update_account_password_policy(allow_users_to_change_password=None, hard_expiry=None, max_password_age=None, minimum_password_length=None, password_reuse_prevention=None, require_lowercase_characters=None, require_numbers=None, require_symbols=None, require_uppercase_characters=None, region=None, key=None, keyid=None, profile=None): ''' Update the password policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_account_password_policy True ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.update_account_password_policy(allow_users_to_change_password, hard_expiry, max_password_age, minimum_password_length, password_reuse_prevention, require_lowercase_characters, require_numbers, require_symbols, require_uppercase_characters) log.info('The password policy has been updated.') return True except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy' log.error(msg) return False def get_account_policy(region=None, key=None, keyid=None, profile=None): ''' Get account policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_account_password_policy() return info.get_account_password_policy_response.get_account_password_policy_result.password_policy except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy.' log.error(msg) return False def create_role(name, policy_document=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Create an instance role. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if role_exists(name, region, key, keyid, profile): return True if not policy_document: policy_document = None try: conn.create_role(name, assume_role_policy_document=policy_document, path=path) log.info('Created IAM role %s.', name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to create IAM role %s.', name) return False def delete_role(name, region=None, key=None, keyid=None, profile=None): ''' Delete an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(name, region, key, keyid, profile): return True try: conn.delete_role(name) log.info('Deleted %s IAM role.', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s IAM role.', name) return False def associate_profile_to_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Associate an instance profile with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.associate_profile_to_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if associated: return True else: try: conn.add_role_to_instance_profile(profile_name, role_name) log.info('Added %s instance profile to IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add %s instance profile to IAM role %s', profile_name, role_name) return False def disassociate_profile_from_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Disassociate an instance profile from an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.disassociate_profile_from_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if not associated: return True else: try: conn.remove_role_from_instance_profile(profile_name, role_name) log.info('Removed %s instance profile from IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove %s instance profile from IAM role %s.', profile_name, role_name) return False def list_role_policies(role_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_role_policies myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_role_policies(role_name) _list = response.list_role_policies_response.list_role_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def get_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.get_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: _policy = conn.get_role_policy(role_name, policy_name) # I _hate_ you for not giving me an object boto. _policy = _policy.get_role_policy_response.policy_document # Policy is url encoded _policy = _unquote(_policy) _policy = salt.utils.json.loads(_policy, object_pairs_hook=odict.OrderedDict) return _policy except boto.exception.BotoServerError: return {} def create_role_policy(role_name, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Create or modify a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role_policy myirole mypolicy '{"MyPolicy": "Statement": [{"Action": ["sqs:*"], "Effect": "Allow", "Resource": ["arn:aws:sqs:*:*:*"], "Sid": "MyPolicySqs1"}]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) mode = 'create' if _policy: if _policy == policy: return True mode = 'modify' if isinstance(policy, six.string_types): policy = salt.utils.json.loads(policy, object_pairs_hook=odict.OrderedDict) try: _policy = salt.utils.json.dumps(policy) conn.put_role_policy(role_name, policy_name, _policy) if mode == 'create': msg = 'Successfully added policy %s to IAM role %s.' else: msg = 'Successfully modified policy %s for IAM role %s.' log.info(msg, policy_name, role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to %s policy %s for IAM role %s.', mode, policy_name, role_name) return False def delete_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) if not _policy: return True try: conn.delete_role_policy(role_name, policy_name) log.info('Successfully deleted policy %s for IAM role %s.', policy_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM role %s.', policy_name, role_name) return False def update_assume_role_policy(role_name, policy_document, region=None, key=None, keyid=None, profile=None): ''' Update an assume role policy for a role. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_assume_role_policy myrole '{"Statement":"..."}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(policy_document, six.string_types): policy_document = salt.utils.json.loads(policy_document, object_pairs_hook=odict.OrderedDict) try: _policy_document = salt.utils.json.dumps(policy_document) conn.update_assume_role_policy(role_name, _policy_document) log.info('Successfully updated assume role policy for IAM role %s.', role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to update assume role policy for IAM role %s.', role_name) return False def build_policy(region=None, key=None, keyid=None, profile=None): ''' Build a default assume role policy. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.build_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if hasattr(conn, 'build_policy'): policy = salt.utils.json.loads(conn.build_policy()) elif hasattr(conn, '_build_policy'): policy = salt.utils.json.loads(conn._build_policy()) else: return {} # The format we get from build_policy isn't going to be what we get back # from AWS for the exact same policy. AWS converts single item list values # into strings, so let's do the same here. for key, policy_val in policy.items(): for statement in policy_val: if (isinstance(statement['Action'], list) and len(statement['Action']) == 1): statement['Action'] = statement['Action'][0] if (isinstance(statement['Principal']['Service'], list) and len(statement['Principal']['Service']) == 1): statement['Principal']['Service'] = statement['Principal']['Service'][0] # build_policy doesn't add a version field, which AWS is going to set to a # default value, when we get it back, so let's set it. policy['Version'] = '2008-10-17' return policy def get_account_id(region=None, key=None, keyid=None, profile=None): ''' Get a the AWS account id associated with the used credentials. CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_id ''' cache_key = 'boto_iam.account_id' if cache_key not in __context__: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_user() # The get_user call returns an user ARN: # arn:aws:iam::027050522557:user/salt-test arn = ret['get_user_response']['get_user_result']['user']['arn'] account_id = arn.split(':')[4] except boto.exception.BotoServerError: # If call failed, then let's try to get the ARN from the metadata timeout = boto.config.getfloat( 'Boto', 'metadata_service_timeout', 1.0 ) attempts = boto.config.getint( 'Boto', 'metadata_service_num_attempts', 1 ) identity = boto.utils.get_instance_identity( timeout=timeout, num_retries=attempts ) try: account_id = identity['document']['accountId'] except KeyError: log.error('Failed to get account id from instance_identity in' ' boto_iam.get_account_id.') __context__[cache_key] = account_id return __context__[cache_key] def get_all_roles(path_prefix=None, region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM role details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_roles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _roles = conn.list_roles(path_prefix=path_prefix) roles = _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) while marker: _roles = conn.list_roles(path_prefix=path_prefix, marker=marker) roles = roles + _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) return roles def get_all_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM user details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_users ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _users = conn.get_all_users(path_prefix=path_prefix) users = _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) while marker: _users = conn.get_all_users(path_prefix=path_prefix, marker=marker) users = users + _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) return users def get_all_user_policies(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all user policies. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_user_policies myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_all_user_policies(user_name, marker, max_items) if not info: return False _list = info.list_user_policies_response.list_user_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policies for user %s.', user_name) return False def get_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user_policy myuser mypolicyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user_policy(user_name, policy_name) log.debug('Info for IAM user %s policy %s: %s.', user_name, policy_name, info) if not info: return False info = info.get_user_policy_response.get_user_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policy %s for IAM user %s.', policy_name, user_name) return False def put_user_policy(user_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_user_policy myuser policyname policyrules ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_user_policy(user_name, policy_name, policy_json) if created: log.info('Created policy %s for IAM user %s.', policy_name, user_name) return True log.error('Could not create policy %s for IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy %s for IAM user %s.', policy_name, user_name) return False def delete_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user_policy myuser mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_user_policy( user_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_user_policy(user_name, policy_name) log.info('Successfully deleted policy %s for IAM user %s.', policy_name, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM user %s.', policy_name, user_name) return False def upload_server_cert(cert_name, cert_body, private_key, cert_chain=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Upload a certificate to Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.upload_server_cert mycert_name crt priv_key :param cert_name: The name for the server certificate. Do not include the path in this value. :param cert_body: The contents of the public key certificate in PEM-encoded format. :param private_key: The contents of the private key in PEM-encoded format. :param cert_chain: The contents of the certificate chain. This is typically a concatenation of the PEM-encoded public key certificates of the chain. :param path: The path for the server certificate. :param region: The name of the region to connect to. :param key: The key to be used in order to connect :param keyid: The keyid to be used in order to connect :param profile: The profile that contains a dict of region, key, keyid :return: True / False ''' exists = get_server_certificate(cert_name, region, key, keyid, profile) if exists: return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.upload_server_cert(cert_name, cert_body, private_key, cert_chain) log.info('Created certificate %s.', cert_name) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to failed to create certificate %s.', cert_name) return False def list_server_certificates(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Lists the server certificates stored in IAM that have the specified path prefix. .. versionadded:: ??? :param path_prefix: The path prefix for filtering the results. For example: /company/servercerts would get all server certificates for which the path starts with /company/servercerts . This parameter is optional. If it is not included, it defaults to a slash (/), listing all server certificates. This parameter allows (per its regex pattern) a string of characters consisting of either a forward slash (/) by itself or a string that must begin and end with forward slashes. In addition, it can contain any ASCII character from the ! (u0021) through the DEL character (u007F), including most punctuation characters, digits, and upper and lowercased letters. CLI Example: .. code-block:: bash salt myminion boto_iam.list_server_certificates path_prefix=/somepath/ ''' retries = 10 sleep = 6 conn = __utils__['boto3.get_connection']('iam', region=region, key=key, keyid=keyid, profile=profile) Items = [] while retries: try: log.debug('Garnering list of IAM Server Certificates') IsTruncated = True while IsTruncated: kwargs = {'PathPrefix': path_prefix} ret = conn.list_server_certificates(**kwargs) Items += ret.get('ServerCertificateMetadataList', []) IsTruncated = ret.get('IsTruncated') kwargs.update({'Marker': ret.get('Marker')}) return Items except botocore.exceptions.ParamValidationError as err: raise SaltInvocationError(str(err)) except botocore.exceptions.ClientError as err: if retries and jmespath.search('Error.Code', err.response) == 'Throttling': retries -= 1 log.debug('Throttled by AWS API, retrying in %s seconds...', sleep) time.sleep(sleep) continue log.error('Failed to list IAM Server Certificates: %s', err.message) return None def get_server_certificate(cert_name, region=None, key=None, keyid=None, profile=None): ''' Returns certificate information from Amazon .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_server_certificate mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_server_certificate(cert_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get certificate %s information.', cert_name) return False def delete_server_cert(cert_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a certificate from Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_server_cert mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_server_cert(cert_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete certificate %s.', cert_name) return False def export_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM user details. Produces results that can be used to create an sls file. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.export_users --out=txt | sed "s/local: //" > iam_users.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() users = get_all_users(path_prefix, region, key, keyid, profile) for user in users: name = user.user_name _policies = conn.get_all_user_policies(name, max_items=100) _policies = _policies.list_user_policies_response.list_user_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_user_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_user_policy_response.get_user_policy_result.policy_document )) policies[policy_name] = _policy user_sls = [] user_sls.append({"name": name}) user_sls.append({"policies": policies}) user_sls.append({"path": user.path}) results["manage user " + name] = {"boto_iam.user_present": user_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def export_roles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM role details. Produces results that can be used to create an sls file. CLI Example: salt-call boto_iam.export_roles --out=txt | sed "s/local: //" > iam_roles.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() roles = get_all_roles(path_prefix, region, key, keyid, profile) for role in roles: name = role.role_name _policies = conn.list_role_policies(name, max_items=100) _policies = _policies.list_role_policies_response.list_role_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_role_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_role_policy_response.get_role_policy_result.policy_document )) policies[policy_name] = _policy role_sls = [] role_sls.append({"name": name}) role_sls.append({"policies": policies}) role_sls.append({'policy_document': salt.utils.json.loads(_unquote(role.assume_role_policy_document))}) role_sls.append({"path": role.path}) results["manage role " + name] = {"boto_iam_role.present": role_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def _get_policy_arn(name, region=None, key=None, keyid=None, profile=None): if name.startswith('arn:aws:iam:'): return name account_id = get_account_id( region=region, key=key, keyid=keyid, profile=profile ) return 'arn:aws:iam::{0}:policy/{1}'.format(account_id, name) def policy_exists(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return True except boto.exception.BotoServerError: return False def get_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return ret.get('get_policy_response', {}).get('get_policy_result', {}) except boto.exception.BotoServerError: return None def create_policy(policy_name, policy_document, path=None, description=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in 'path', 'description': if locals()[arg] is not None: params[arg] = locals()[arg] if policy_exists(policy_name, region, key, keyid, profile): return True try: conn.create_policy(policy_name, policy_document, **params) log.info('Created IAM policy %s.', policy_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s.', policy_name) return False return True def delete_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_exists(policy_arn, region, key, keyid, profile): return True try: conn.delete_policy(policy_arn) log.info('Deleted %s policy.', policy_name) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete %s policy: %s.', policy_name, aws.get('message')) return False return True def list_policies(region=None, key=None, keyid=None, profile=None): ''' List policies. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policies ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: policies = [] for ret in __utils__['boto.paged_call'](conn.list_policies): policies.append(ret.get('list_policies_response', {}).get('list_policies_result', {}).get('policies')) return policies except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to list policy versions.' log.error(msg) return [] def policy_version_exists(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.get_policy_version(policy_arn, version_id) return True except boto.exception.BotoServerError: return False def get_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy_version(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile), version_id) retval = ret.get('get_policy_version_response', {}).get('get_policy_version_result', {}).get('policy_version', {}) retval['document'] = _unquote(retval.get('document')) return {'policy_version': retval} except boto.exception.BotoServerError: return None def create_policy_version(policy_name, policy_document, set_as_default=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy version. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy_version mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in ('set_as_default',): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.create_policy_version(policy_arn, policy_document, **params) vid = ret.get('create_policy_version_response', {}).get('create_policy_version_result', {}).get('policy_version', {}).get('version_id') log.info('Created IAM policy %s version %s.', policy_name, vid) return {'created': True, 'version_id': vid} except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s version %s.', policy_name, vid) return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Delete a policy version. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_version_exists(policy_arn, version_id, region, key, keyid, profile): return True try: conn.delete_policy_version(policy_arn, version_id) log.info('Deleted IAM policy %s version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete IAM policy %s version %s: %s', policy_name, version_id, aws.get('message')) return False return True def list_policy_versions(policy_name, region=None, key=None, keyid=None, profile=None): ''' List versions of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policy_versions mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.list_policy_versions(policy_arn) return ret.get('list_policy_versions_response', {}).get('list_policy_versions_result', {}).get('versions') except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list versions for IAM policy %s.', policy_name) return [] def set_default_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Set the default version of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.set_default_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.set_default_policy_version(policy_arn, version_id) log.info('Set %s policy to version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to set %s policy to version %s: %s', policy_name, version_id, aws.get('message')) return False return True def attach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_user_policy(policy_arn, user_name) log.info('Attached policy %s to IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach %s policy to IAM user %s.', policy_name, user_name) return False return True def detach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_user_policy(policy_arn, user_name) log.info('Detached %s policy from IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach %s policy from IAM user %s.', policy_name, user_name) return False return True def attach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_group_policy(policy_arn, group_name) log.info('Attached policy %s to IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM group %s.', policy_name, group_name) return False return True def detach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_group_policy(policy_arn, group_name) log.info('Detached policy %s from IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM group %s.', policy_name, group_name) return False return True def attach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_role_policy(policy_arn, role_name) log.info('Attached policy %s to IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM role %s.', policy_name, role_name) return False return True def detach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_role_policy(policy_arn, role_name) log.info('Detached policy %s from IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM role %s.', policy_name, role_name) return False return True def list_entities_for_policy(policy_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities that a policy is attached to. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 params = {} for arg in ('path_prefix', 'entity_filter'): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) while retries: try: allret = { 'policy_groups': [], 'policy_users': [], 'policy_roles': [], } for ret in __utils__['boto.paged_call'](conn.list_entities_for_policy, policy_arn=policy_arn, **params): for k, v in six.iteritems(allret): v.extend(ret.get('list_entities_for_policy_response', {}).get('list_entities_for_policy_result', {}).get(k)) return allret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('Failed to list entities for IAM policy %s: %s', policy_name, e.message) return {} return {} def list_attached_user_policies(user_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given user. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'UserName': user_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedUserPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_user_policies_response', {}).get('list_attached_user_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM user %s.', user_name) return [] def list_attached_group_policies(group_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given group. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'GroupName': group_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedGroupPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_group_policies_response', {}).get('list_attached_group_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM group %s.', group_name) return [] def list_attached_role_policies(role_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'RoleName': role_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedRolePolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_role_policies_response', {}).get('list_attached_role_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM role %s.', role_name) return [] def create_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Create SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.create_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_saml_provider(saml_metadata_document, name) log.info('Successfully created %s SAML provider.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to create SAML provider %s.', name) return False def get_saml_provider_arn(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider_arn my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_saml_providers() for saml_provider in response.list_saml_providers_response.list_saml_providers_result.saml_provider_list: if saml_provider['arn'].endswith(':saml-provider/' + name): return saml_provider['arn'] return False except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to get ARN of SAML provider %s.', name) return False def delete_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Delete SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.delete_saml_provider my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return True conn.delete_saml_provider(saml_provider_arn) log.info('Successfully deleted SAML provider %s.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete SAML provider %s.', name) return False def list_saml_providers(region=None, key=None, keyid=None, profile=None): ''' List SAML providers. CLI Example: .. code-block:: bash salt myminion boto_iam.list_saml_providers ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: providers = [] info = conn.list_saml_providers() for arn in info['list_saml_providers_response']['list_saml_providers_result']['saml_provider_list']: providers.append(arn['arn'].rsplit('/', 1)[1]) return providers except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get list of SAML providers.') return False def get_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider document. CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider arn ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: provider = conn.get_saml_provider(name) return provider['get_saml_provider_response']['get_saml_provider_result']['saml_metadata_document'] except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get SAML provider document %s.', name) return False def update_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Update SAML provider. CLI Example: .. code-block:: bash salt myminion boto_iam.update_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return False if conn.update_saml_provider(name, saml_metadata_document): return True return False except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to update SAML provider %s.', name) return False
saltstack/salt
salt/modules/boto_iam.py
associate_profile_to_role
python
def associate_profile_to_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Associate an instance profile with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.associate_profile_to_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if associated: return True else: try: conn.add_role_to_instance_profile(profile_name, role_name) log.info('Added %s instance profile to IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add %s instance profile to IAM role %s', profile_name, role_name) return False
Associate an instance profile with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.associate_profile_to_role myirole myiprofile
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iam.py#L1035-L1065
[ "def instance_profile_exists(name, region=None, key=None, keyid=None,\n profile=None):\n '''\n Check to see if an instance profile exists.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_iam.instance_profile_exists myiprofile\n '''\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n\n try:\n # Boto weirdly returns an exception here if an instance profile doesn't\n # exist.\n conn.get_instance_profile(name)\n return True\n except boto.exception.BotoServerError:\n return False\n", "def role_exists(name, region=None, key=None, keyid=None, profile=None):\n '''\n Check to see if an IAM role exists.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_iam.role_exists myirole\n '''\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n try:\n conn.get_role(name)\n return True\n except boto.exception.BotoServerError:\n return False\n", "def profile_associated(role_name, profile_name, region, key, keyid, profile):\n '''\n Check to see if an instance profile is associated with an IAM role.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_iam.profile_associated myirole myiprofile\n '''\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n\n # The IAM module of boto doesn't return objects. Instead you need to grab\n # values through its properties. Sigh.\n try:\n profiles = conn.list_instance_profiles_for_role(role_name)\n except boto.exception.BotoServerError as e:\n log.debug(e)\n return False\n profiles = profiles.list_instance_profiles_for_role_response\n profiles = profiles.list_instance_profiles_for_role_result\n profiles = profiles.instance_profiles\n for profile in profiles:\n if profile.instance_profile_name == profile_name:\n return True\n return False\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon IAM .. versionadded:: 2014.7.0 :configuration: This module accepts explicit iam 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 iam.keyid: GKTADJGHEIQSXMKKRBJ08H iam.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs iam.region: 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: boto ''' # keep lint from choking on _get_conn and _cache_id #pylint: disable=E0602 # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import salt libs from salt.ext import six import salt.utils.compat import salt.utils.json import salt.utils.odict as odict import salt.utils.versions from salt.exceptions import SaltInvocationError # Import third party libs # pylint: disable=unused-import from salt.ext.six.moves.urllib.parse import unquote as _unquote # pylint: disable=no-name-in-module try: import boto import boto.iam import boto3 import botocore logging.getLogger('boto').setLevel(logging.CRITICAL) logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=unused-import log = logging.getLogger(__name__) def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'iam', pack=__salt__) def instance_profile_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an instance profile exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: # Boto weirdly returns an exception here if an instance profile doesn't # exist. conn.get_instance_profile(name) return True except boto.exception.BotoServerError: return False def create_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Create an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.create_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if instance_profile_exists(name, region, key, keyid, profile): return True try: # This call returns an instance profile if successful and an exception # if not. It's annoying. conn.create_instance_profile(name) log.info('Created %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create %s instance profile.', name) return False return True def delete_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Delete an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not instance_profile_exists(name, region, key, keyid, profile): return True try: conn.delete_instance_profile(name) log.info('Deleted %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s instance profile.', name) return False return True def role_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an IAM role exists. CLI Example: .. code-block:: bash salt myminion boto_iam.role_exists myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_role(name) return True except boto.exception.BotoServerError: return False def describe_role(name, region=None, key=None, keyid=None, profile=None): ''' Get information for a role. CLI Example: .. code-block:: bash salt myminion boto_iam.describe_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_role(name) if not info: return False role = info.get_role_response.get_role_result.role role['assume_role_policy_document'] = salt.utils.json.loads(_unquote( role.assume_role_policy_document )) # If Sid wasn't defined by the user, boto will still return a Sid in # each policy. To properly check idempotently, let's remove the Sid # from the return if it's not actually set. for policy_key, policy in role['assume_role_policy_document'].items(): if policy_key == 'Statement': for val in policy: if 'Sid' in val and not val['Sid']: del val['Sid'] return role except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get %s information.', name) return False def create_user(user_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_user myuser ''' if not path: path = '/' if get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_user(user_name, path) log.info('Created IAM user : %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM user %s.', user_name) return False def get_all_access_keys(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all access keys from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_access_keys myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.get_all_access_keys(user_name, marker, max_items) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get access keys for IAM user %s.', user_name) return six.text_type(e) def create_access_key(user_name, region=None, key=None, keyid=None, profile=None): ''' Create access key id for a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.create_access_key(user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create access key.') return six.text_type(e) def delete_access_key(access_key_id, user_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete access key id from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_access_key(access_key_id, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete access key id %s.', access_key_id) return six.text_type(e) def delete_user(user_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user myuser ''' if not get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.delete_user(user_name) log.info('Deleted IAM user : %s .', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM user %s', user_name) return six.text_type(e) def get_user(user_name=None, region=None, key=None, keyid=None, profile=None): ''' Get user information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user(user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM user %s info.', user_name) return False def create_group(group_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_group group ''' if not path: path = '/' if get_group(group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_group(group_name, path) log.info('Created IAM group : %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM group %s.', group_name) return False def get_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group(group_name, max_items=1) if not info: return False return info['get_group_response']['get_group_result']['group'] except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_group_members(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: marker = None truncated = True users = [] while truncated: info = conn.get_group(group_name, marker=marker, max_items=1000) if not info: return False truncated = bool(info['get_group_response']['get_group_result']['is_truncated']) if truncated and 'marker' in info['get_group_response']['get_group_result']: marker = info['get_group_response']['get_group_result']['marker'] else: marker = None truncated = False users += info['get_group_response']['get_group_result']['users'] return users except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get members for IAM group %s.', group_name) return False def add_user_to_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Add user to group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.add_user_to_group myuser mygroup ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('Username : %s does not exist.', user_name) return False if user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.add_user_to_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add IAM user %s to group %s.', user_name, group_name) return False def user_exists_in_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Check if user exists in group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.user_exists_in_group myuser mygroup ''' # TODO this should probably use boto.iam.get_groups_for_user users = get_group_members( group_name=group_name, region=region, key=key, keyid=keyid, profile=profile ) if users: for _user in users: if user_name == _user['user_name']: log.debug('IAM user %s is already in IAM group %s.', user_name, group_name) return True return False def remove_user_from_group(group_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Remove user from group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.remove_user_from_group mygroup myuser ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist.', user_name) return False if not user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.remove_user_from_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove IAM user %s from group %s', user_name, group_name) return False def put_group_policy(group_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_group_policy mygroup policyname policyrules ''' group = get_group(group_name, region=region, key=key, keyid=keyid, profile=profile) if not group: log.error('Group %s does not exist', group_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_group_policy(group_name, policy_name, policy_json) if created: log.info('Created policy for IAM group %s.', group_name) return True log.error('Could not create policy for IAM group %s', group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy for IAM group %s', group_name) return False def delete_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group_policy mygroup mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_group_policy( group_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_group_policy(group_name, policy_name) log.info('Successfully deleted policy %s for IAM group %s.', policy_name, group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM group %s.', policy_name, group_name) return False def get_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group_policy mygroup policyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group_policy(group_name, policy_name) log.debug('info for group policy is : %s', info) if not info: return False info = info.get_group_policy_response.get_group_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_all_groups(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM group details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_groups ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _groups = conn.get_all_groups(path_prefix=path_prefix) groups = _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) while marker: _groups = conn.get_all_groups(path_prefix=path_prefix, marker=marker) groups = groups + _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) return groups def get_all_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.get_all_instance_profiles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) marker = False profiles = [] while marker is not None: marker = marker if marker else None p = conn.list_instance_profiles(path_prefix=path_prefix, marker=marker) res = p.list_instance_profiles_response.list_instance_profiles_result profiles += res.instance_profiles marker = getattr(res, 'marker', None) return profiles def list_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' List all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.list_instance_profiles ''' p = get_all_instance_profiles(path_prefix, region, key, keyid, profile) return [i['instance_profile_name'] for i in p] def get_all_group_policies(group_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a group. CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_group_policies mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False try: response = conn.get_all_group_policies(group_name) _list = response.list_group_policies_response.list_group_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def delete_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _group = get_group( group_name, region, key, keyid, profile ) if not _group: return True try: conn.delete_group(group_name) log.info('Successfully deleted IAM group %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM group %s.', group_name) return False def create_login_profile(user_name, password, region=None, key=None, keyid=None, profile=None): ''' Creates a login profile for the specified user, give the user the ability to access AWS services and the AWS Management Console. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_login_profile user_name password ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.create_login_profile(user_name, password) log.info('Created profile for IAM user %s.', user_name) return info except boto.exception.BotoServerError as e: log.debug(e) if 'Conflict' in e: log.info('Profile already exists for IAM user %s.', user_name) return 'Conflict' log.error('Failed to update profile for IAM user %s.', user_name) return False def delete_login_profile(user_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a login profile for the specified user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_login_profile user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.delete_login_profile(user_name) log.info('Deleted login profile for IAM user %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Login profile already deleted for IAM user %s.', user_name) return True log.error('Failed to delete login profile for IAM user %s.', user_name) return False def get_all_mfa_devices(user_name, region=None, key=None, keyid=None, profile=None): ''' Get all MFA devices associated with an IAM user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_mfa_devices user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: result = conn.get_all_mfa_devices(user_name) devices = result['list_mfa_devices_response']['list_mfa_devices_result']['mfa_devices'] return devices except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Could not find IAM user %s.', user_name) return [] log.error('Failed to get all MFA devices for IAM user %s.', user_name) return False def deactivate_mfa_device(user_name, serial, region=None, key=None, keyid=None, profile=None): ''' Deactivates the specified MFA device and removes it from association with the user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.deactivate_mfa_device user_name serial_num ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.deactivate_mfa_device(user_name, serial) log.info('Deactivated MFA device %s for IAM user %s.', serial, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('MFA device %s not associated with IAM user %s.', serial, user_name) return True log.error('Failed to deactivate MFA device %s for IAM user %s.', serial, user_name) return False def delete_virtual_mfa_device(serial, region=None, key=None, keyid=None, profile=None): ''' Deletes the specified virtual MFA device. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_virtual_mfa_device serial_num ''' conn = __utils__['boto3.get_connection_func']('iam')() try: conn.delete_virtual_mfa_device(SerialNumber=serial) log.info('Deleted virtual MFA device %s.', serial) return True except botocore.exceptions.ClientError as e: log.debug(e) if 'NoSuchEntity' in six.text_type(e): log.info('Virtual MFA device %s not found.', serial) return True log.error('Failed to delete virtual MFA device %s.', serial) return False def update_account_password_policy(allow_users_to_change_password=None, hard_expiry=None, max_password_age=None, minimum_password_length=None, password_reuse_prevention=None, require_lowercase_characters=None, require_numbers=None, require_symbols=None, require_uppercase_characters=None, region=None, key=None, keyid=None, profile=None): ''' Update the password policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_account_password_policy True ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.update_account_password_policy(allow_users_to_change_password, hard_expiry, max_password_age, minimum_password_length, password_reuse_prevention, require_lowercase_characters, require_numbers, require_symbols, require_uppercase_characters) log.info('The password policy has been updated.') return True except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy' log.error(msg) return False def get_account_policy(region=None, key=None, keyid=None, profile=None): ''' Get account policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_account_password_policy() return info.get_account_password_policy_response.get_account_password_policy_result.password_policy except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy.' log.error(msg) return False def create_role(name, policy_document=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Create an instance role. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if role_exists(name, region, key, keyid, profile): return True if not policy_document: policy_document = None try: conn.create_role(name, assume_role_policy_document=policy_document, path=path) log.info('Created IAM role %s.', name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to create IAM role %s.', name) return False def delete_role(name, region=None, key=None, keyid=None, profile=None): ''' Delete an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(name, region, key, keyid, profile): return True try: conn.delete_role(name) log.info('Deleted %s IAM role.', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s IAM role.', name) return False def profile_associated(role_name, profile_name, region, key, keyid, profile): ''' Check to see if an instance profile is associated with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.profile_associated myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # The IAM module of boto doesn't return objects. Instead you need to grab # values through its properties. Sigh. try: profiles = conn.list_instance_profiles_for_role(role_name) except boto.exception.BotoServerError as e: log.debug(e) return False profiles = profiles.list_instance_profiles_for_role_response profiles = profiles.list_instance_profiles_for_role_result profiles = profiles.instance_profiles for profile in profiles: if profile.instance_profile_name == profile_name: return True return False def disassociate_profile_from_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Disassociate an instance profile from an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.disassociate_profile_from_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if not associated: return True else: try: conn.remove_role_from_instance_profile(profile_name, role_name) log.info('Removed %s instance profile from IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove %s instance profile from IAM role %s.', profile_name, role_name) return False def list_role_policies(role_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_role_policies myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_role_policies(role_name) _list = response.list_role_policies_response.list_role_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def get_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.get_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: _policy = conn.get_role_policy(role_name, policy_name) # I _hate_ you for not giving me an object boto. _policy = _policy.get_role_policy_response.policy_document # Policy is url encoded _policy = _unquote(_policy) _policy = salt.utils.json.loads(_policy, object_pairs_hook=odict.OrderedDict) return _policy except boto.exception.BotoServerError: return {} def create_role_policy(role_name, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Create or modify a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role_policy myirole mypolicy '{"MyPolicy": "Statement": [{"Action": ["sqs:*"], "Effect": "Allow", "Resource": ["arn:aws:sqs:*:*:*"], "Sid": "MyPolicySqs1"}]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) mode = 'create' if _policy: if _policy == policy: return True mode = 'modify' if isinstance(policy, six.string_types): policy = salt.utils.json.loads(policy, object_pairs_hook=odict.OrderedDict) try: _policy = salt.utils.json.dumps(policy) conn.put_role_policy(role_name, policy_name, _policy) if mode == 'create': msg = 'Successfully added policy %s to IAM role %s.' else: msg = 'Successfully modified policy %s for IAM role %s.' log.info(msg, policy_name, role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to %s policy %s for IAM role %s.', mode, policy_name, role_name) return False def delete_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) if not _policy: return True try: conn.delete_role_policy(role_name, policy_name) log.info('Successfully deleted policy %s for IAM role %s.', policy_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM role %s.', policy_name, role_name) return False def update_assume_role_policy(role_name, policy_document, region=None, key=None, keyid=None, profile=None): ''' Update an assume role policy for a role. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_assume_role_policy myrole '{"Statement":"..."}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(policy_document, six.string_types): policy_document = salt.utils.json.loads(policy_document, object_pairs_hook=odict.OrderedDict) try: _policy_document = salt.utils.json.dumps(policy_document) conn.update_assume_role_policy(role_name, _policy_document) log.info('Successfully updated assume role policy for IAM role %s.', role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to update assume role policy for IAM role %s.', role_name) return False def build_policy(region=None, key=None, keyid=None, profile=None): ''' Build a default assume role policy. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.build_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if hasattr(conn, 'build_policy'): policy = salt.utils.json.loads(conn.build_policy()) elif hasattr(conn, '_build_policy'): policy = salt.utils.json.loads(conn._build_policy()) else: return {} # The format we get from build_policy isn't going to be what we get back # from AWS for the exact same policy. AWS converts single item list values # into strings, so let's do the same here. for key, policy_val in policy.items(): for statement in policy_val: if (isinstance(statement['Action'], list) and len(statement['Action']) == 1): statement['Action'] = statement['Action'][0] if (isinstance(statement['Principal']['Service'], list) and len(statement['Principal']['Service']) == 1): statement['Principal']['Service'] = statement['Principal']['Service'][0] # build_policy doesn't add a version field, which AWS is going to set to a # default value, when we get it back, so let's set it. policy['Version'] = '2008-10-17' return policy def get_account_id(region=None, key=None, keyid=None, profile=None): ''' Get a the AWS account id associated with the used credentials. CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_id ''' cache_key = 'boto_iam.account_id' if cache_key not in __context__: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_user() # The get_user call returns an user ARN: # arn:aws:iam::027050522557:user/salt-test arn = ret['get_user_response']['get_user_result']['user']['arn'] account_id = arn.split(':')[4] except boto.exception.BotoServerError: # If call failed, then let's try to get the ARN from the metadata timeout = boto.config.getfloat( 'Boto', 'metadata_service_timeout', 1.0 ) attempts = boto.config.getint( 'Boto', 'metadata_service_num_attempts', 1 ) identity = boto.utils.get_instance_identity( timeout=timeout, num_retries=attempts ) try: account_id = identity['document']['accountId'] except KeyError: log.error('Failed to get account id from instance_identity in' ' boto_iam.get_account_id.') __context__[cache_key] = account_id return __context__[cache_key] def get_all_roles(path_prefix=None, region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM role details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_roles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _roles = conn.list_roles(path_prefix=path_prefix) roles = _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) while marker: _roles = conn.list_roles(path_prefix=path_prefix, marker=marker) roles = roles + _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) return roles def get_all_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM user details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_users ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _users = conn.get_all_users(path_prefix=path_prefix) users = _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) while marker: _users = conn.get_all_users(path_prefix=path_prefix, marker=marker) users = users + _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) return users def get_all_user_policies(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all user policies. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_user_policies myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_all_user_policies(user_name, marker, max_items) if not info: return False _list = info.list_user_policies_response.list_user_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policies for user %s.', user_name) return False def get_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user_policy myuser mypolicyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user_policy(user_name, policy_name) log.debug('Info for IAM user %s policy %s: %s.', user_name, policy_name, info) if not info: return False info = info.get_user_policy_response.get_user_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policy %s for IAM user %s.', policy_name, user_name) return False def put_user_policy(user_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_user_policy myuser policyname policyrules ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_user_policy(user_name, policy_name, policy_json) if created: log.info('Created policy %s for IAM user %s.', policy_name, user_name) return True log.error('Could not create policy %s for IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy %s for IAM user %s.', policy_name, user_name) return False def delete_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user_policy myuser mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_user_policy( user_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_user_policy(user_name, policy_name) log.info('Successfully deleted policy %s for IAM user %s.', policy_name, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM user %s.', policy_name, user_name) return False def upload_server_cert(cert_name, cert_body, private_key, cert_chain=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Upload a certificate to Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.upload_server_cert mycert_name crt priv_key :param cert_name: The name for the server certificate. Do not include the path in this value. :param cert_body: The contents of the public key certificate in PEM-encoded format. :param private_key: The contents of the private key in PEM-encoded format. :param cert_chain: The contents of the certificate chain. This is typically a concatenation of the PEM-encoded public key certificates of the chain. :param path: The path for the server certificate. :param region: The name of the region to connect to. :param key: The key to be used in order to connect :param keyid: The keyid to be used in order to connect :param profile: The profile that contains a dict of region, key, keyid :return: True / False ''' exists = get_server_certificate(cert_name, region, key, keyid, profile) if exists: return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.upload_server_cert(cert_name, cert_body, private_key, cert_chain) log.info('Created certificate %s.', cert_name) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to failed to create certificate %s.', cert_name) return False def list_server_certificates(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Lists the server certificates stored in IAM that have the specified path prefix. .. versionadded:: ??? :param path_prefix: The path prefix for filtering the results. For example: /company/servercerts would get all server certificates for which the path starts with /company/servercerts . This parameter is optional. If it is not included, it defaults to a slash (/), listing all server certificates. This parameter allows (per its regex pattern) a string of characters consisting of either a forward slash (/) by itself or a string that must begin and end with forward slashes. In addition, it can contain any ASCII character from the ! (u0021) through the DEL character (u007F), including most punctuation characters, digits, and upper and lowercased letters. CLI Example: .. code-block:: bash salt myminion boto_iam.list_server_certificates path_prefix=/somepath/ ''' retries = 10 sleep = 6 conn = __utils__['boto3.get_connection']('iam', region=region, key=key, keyid=keyid, profile=profile) Items = [] while retries: try: log.debug('Garnering list of IAM Server Certificates') IsTruncated = True while IsTruncated: kwargs = {'PathPrefix': path_prefix} ret = conn.list_server_certificates(**kwargs) Items += ret.get('ServerCertificateMetadataList', []) IsTruncated = ret.get('IsTruncated') kwargs.update({'Marker': ret.get('Marker')}) return Items except botocore.exceptions.ParamValidationError as err: raise SaltInvocationError(str(err)) except botocore.exceptions.ClientError as err: if retries and jmespath.search('Error.Code', err.response) == 'Throttling': retries -= 1 log.debug('Throttled by AWS API, retrying in %s seconds...', sleep) time.sleep(sleep) continue log.error('Failed to list IAM Server Certificates: %s', err.message) return None def get_server_certificate(cert_name, region=None, key=None, keyid=None, profile=None): ''' Returns certificate information from Amazon .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_server_certificate mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_server_certificate(cert_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get certificate %s information.', cert_name) return False def delete_server_cert(cert_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a certificate from Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_server_cert mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_server_cert(cert_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete certificate %s.', cert_name) return False def export_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM user details. Produces results that can be used to create an sls file. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.export_users --out=txt | sed "s/local: //" > iam_users.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() users = get_all_users(path_prefix, region, key, keyid, profile) for user in users: name = user.user_name _policies = conn.get_all_user_policies(name, max_items=100) _policies = _policies.list_user_policies_response.list_user_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_user_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_user_policy_response.get_user_policy_result.policy_document )) policies[policy_name] = _policy user_sls = [] user_sls.append({"name": name}) user_sls.append({"policies": policies}) user_sls.append({"path": user.path}) results["manage user " + name] = {"boto_iam.user_present": user_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def export_roles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM role details. Produces results that can be used to create an sls file. CLI Example: salt-call boto_iam.export_roles --out=txt | sed "s/local: //" > iam_roles.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() roles = get_all_roles(path_prefix, region, key, keyid, profile) for role in roles: name = role.role_name _policies = conn.list_role_policies(name, max_items=100) _policies = _policies.list_role_policies_response.list_role_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_role_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_role_policy_response.get_role_policy_result.policy_document )) policies[policy_name] = _policy role_sls = [] role_sls.append({"name": name}) role_sls.append({"policies": policies}) role_sls.append({'policy_document': salt.utils.json.loads(_unquote(role.assume_role_policy_document))}) role_sls.append({"path": role.path}) results["manage role " + name] = {"boto_iam_role.present": role_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def _get_policy_arn(name, region=None, key=None, keyid=None, profile=None): if name.startswith('arn:aws:iam:'): return name account_id = get_account_id( region=region, key=key, keyid=keyid, profile=profile ) return 'arn:aws:iam::{0}:policy/{1}'.format(account_id, name) def policy_exists(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return True except boto.exception.BotoServerError: return False def get_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return ret.get('get_policy_response', {}).get('get_policy_result', {}) except boto.exception.BotoServerError: return None def create_policy(policy_name, policy_document, path=None, description=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in 'path', 'description': if locals()[arg] is not None: params[arg] = locals()[arg] if policy_exists(policy_name, region, key, keyid, profile): return True try: conn.create_policy(policy_name, policy_document, **params) log.info('Created IAM policy %s.', policy_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s.', policy_name) return False return True def delete_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_exists(policy_arn, region, key, keyid, profile): return True try: conn.delete_policy(policy_arn) log.info('Deleted %s policy.', policy_name) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete %s policy: %s.', policy_name, aws.get('message')) return False return True def list_policies(region=None, key=None, keyid=None, profile=None): ''' List policies. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policies ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: policies = [] for ret in __utils__['boto.paged_call'](conn.list_policies): policies.append(ret.get('list_policies_response', {}).get('list_policies_result', {}).get('policies')) return policies except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to list policy versions.' log.error(msg) return [] def policy_version_exists(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.get_policy_version(policy_arn, version_id) return True except boto.exception.BotoServerError: return False def get_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy_version(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile), version_id) retval = ret.get('get_policy_version_response', {}).get('get_policy_version_result', {}).get('policy_version', {}) retval['document'] = _unquote(retval.get('document')) return {'policy_version': retval} except boto.exception.BotoServerError: return None def create_policy_version(policy_name, policy_document, set_as_default=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy version. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy_version mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in ('set_as_default',): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.create_policy_version(policy_arn, policy_document, **params) vid = ret.get('create_policy_version_response', {}).get('create_policy_version_result', {}).get('policy_version', {}).get('version_id') log.info('Created IAM policy %s version %s.', policy_name, vid) return {'created': True, 'version_id': vid} except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s version %s.', policy_name, vid) return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Delete a policy version. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_version_exists(policy_arn, version_id, region, key, keyid, profile): return True try: conn.delete_policy_version(policy_arn, version_id) log.info('Deleted IAM policy %s version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete IAM policy %s version %s: %s', policy_name, version_id, aws.get('message')) return False return True def list_policy_versions(policy_name, region=None, key=None, keyid=None, profile=None): ''' List versions of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policy_versions mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.list_policy_versions(policy_arn) return ret.get('list_policy_versions_response', {}).get('list_policy_versions_result', {}).get('versions') except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list versions for IAM policy %s.', policy_name) return [] def set_default_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Set the default version of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.set_default_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.set_default_policy_version(policy_arn, version_id) log.info('Set %s policy to version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to set %s policy to version %s: %s', policy_name, version_id, aws.get('message')) return False return True def attach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_user_policy(policy_arn, user_name) log.info('Attached policy %s to IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach %s policy to IAM user %s.', policy_name, user_name) return False return True def detach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_user_policy(policy_arn, user_name) log.info('Detached %s policy from IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach %s policy from IAM user %s.', policy_name, user_name) return False return True def attach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_group_policy(policy_arn, group_name) log.info('Attached policy %s to IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM group %s.', policy_name, group_name) return False return True def detach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_group_policy(policy_arn, group_name) log.info('Detached policy %s from IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM group %s.', policy_name, group_name) return False return True def attach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_role_policy(policy_arn, role_name) log.info('Attached policy %s to IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM role %s.', policy_name, role_name) return False return True def detach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_role_policy(policy_arn, role_name) log.info('Detached policy %s from IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM role %s.', policy_name, role_name) return False return True def list_entities_for_policy(policy_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities that a policy is attached to. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 params = {} for arg in ('path_prefix', 'entity_filter'): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) while retries: try: allret = { 'policy_groups': [], 'policy_users': [], 'policy_roles': [], } for ret in __utils__['boto.paged_call'](conn.list_entities_for_policy, policy_arn=policy_arn, **params): for k, v in six.iteritems(allret): v.extend(ret.get('list_entities_for_policy_response', {}).get('list_entities_for_policy_result', {}).get(k)) return allret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('Failed to list entities for IAM policy %s: %s', policy_name, e.message) return {} return {} def list_attached_user_policies(user_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given user. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'UserName': user_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedUserPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_user_policies_response', {}).get('list_attached_user_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM user %s.', user_name) return [] def list_attached_group_policies(group_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given group. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'GroupName': group_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedGroupPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_group_policies_response', {}).get('list_attached_group_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM group %s.', group_name) return [] def list_attached_role_policies(role_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'RoleName': role_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedRolePolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_role_policies_response', {}).get('list_attached_role_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM role %s.', role_name) return [] def create_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Create SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.create_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_saml_provider(saml_metadata_document, name) log.info('Successfully created %s SAML provider.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to create SAML provider %s.', name) return False def get_saml_provider_arn(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider_arn my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_saml_providers() for saml_provider in response.list_saml_providers_response.list_saml_providers_result.saml_provider_list: if saml_provider['arn'].endswith(':saml-provider/' + name): return saml_provider['arn'] return False except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to get ARN of SAML provider %s.', name) return False def delete_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Delete SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.delete_saml_provider my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return True conn.delete_saml_provider(saml_provider_arn) log.info('Successfully deleted SAML provider %s.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete SAML provider %s.', name) return False def list_saml_providers(region=None, key=None, keyid=None, profile=None): ''' List SAML providers. CLI Example: .. code-block:: bash salt myminion boto_iam.list_saml_providers ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: providers = [] info = conn.list_saml_providers() for arn in info['list_saml_providers_response']['list_saml_providers_result']['saml_provider_list']: providers.append(arn['arn'].rsplit('/', 1)[1]) return providers except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get list of SAML providers.') return False def get_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider document. CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider arn ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: provider = conn.get_saml_provider(name) return provider['get_saml_provider_response']['get_saml_provider_result']['saml_metadata_document'] except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get SAML provider document %s.', name) return False def update_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Update SAML provider. CLI Example: .. code-block:: bash salt myminion boto_iam.update_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return False if conn.update_saml_provider(name, saml_metadata_document): return True return False except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to update SAML provider %s.', name) return False
saltstack/salt
salt/modules/boto_iam.py
list_role_policies
python
def list_role_policies(role_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_role_policies myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_role_policies(role_name) _list = response.list_role_policies_response.list_role_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return []
Get a list of policy names from a role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_role_policies myirole
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iam.py#L1101-L1120
null
# -*- coding: utf-8 -*- ''' Connection module for Amazon IAM .. versionadded:: 2014.7.0 :configuration: This module accepts explicit iam 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 iam.keyid: GKTADJGHEIQSXMKKRBJ08H iam.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs iam.region: 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: boto ''' # keep lint from choking on _get_conn and _cache_id #pylint: disable=E0602 # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import salt libs from salt.ext import six import salt.utils.compat import salt.utils.json import salt.utils.odict as odict import salt.utils.versions from salt.exceptions import SaltInvocationError # Import third party libs # pylint: disable=unused-import from salt.ext.six.moves.urllib.parse import unquote as _unquote # pylint: disable=no-name-in-module try: import boto import boto.iam import boto3 import botocore logging.getLogger('boto').setLevel(logging.CRITICAL) logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=unused-import log = logging.getLogger(__name__) def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'iam', pack=__salt__) def instance_profile_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an instance profile exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: # Boto weirdly returns an exception here if an instance profile doesn't # exist. conn.get_instance_profile(name) return True except boto.exception.BotoServerError: return False def create_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Create an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.create_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if instance_profile_exists(name, region, key, keyid, profile): return True try: # This call returns an instance profile if successful and an exception # if not. It's annoying. conn.create_instance_profile(name) log.info('Created %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create %s instance profile.', name) return False return True def delete_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Delete an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not instance_profile_exists(name, region, key, keyid, profile): return True try: conn.delete_instance_profile(name) log.info('Deleted %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s instance profile.', name) return False return True def role_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an IAM role exists. CLI Example: .. code-block:: bash salt myminion boto_iam.role_exists myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_role(name) return True except boto.exception.BotoServerError: return False def describe_role(name, region=None, key=None, keyid=None, profile=None): ''' Get information for a role. CLI Example: .. code-block:: bash salt myminion boto_iam.describe_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_role(name) if not info: return False role = info.get_role_response.get_role_result.role role['assume_role_policy_document'] = salt.utils.json.loads(_unquote( role.assume_role_policy_document )) # If Sid wasn't defined by the user, boto will still return a Sid in # each policy. To properly check idempotently, let's remove the Sid # from the return if it's not actually set. for policy_key, policy in role['assume_role_policy_document'].items(): if policy_key == 'Statement': for val in policy: if 'Sid' in val and not val['Sid']: del val['Sid'] return role except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get %s information.', name) return False def create_user(user_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_user myuser ''' if not path: path = '/' if get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_user(user_name, path) log.info('Created IAM user : %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM user %s.', user_name) return False def get_all_access_keys(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all access keys from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_access_keys myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.get_all_access_keys(user_name, marker, max_items) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get access keys for IAM user %s.', user_name) return six.text_type(e) def create_access_key(user_name, region=None, key=None, keyid=None, profile=None): ''' Create access key id for a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.create_access_key(user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create access key.') return six.text_type(e) def delete_access_key(access_key_id, user_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete access key id from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_access_key(access_key_id, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete access key id %s.', access_key_id) return six.text_type(e) def delete_user(user_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user myuser ''' if not get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.delete_user(user_name) log.info('Deleted IAM user : %s .', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM user %s', user_name) return six.text_type(e) def get_user(user_name=None, region=None, key=None, keyid=None, profile=None): ''' Get user information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user(user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM user %s info.', user_name) return False def create_group(group_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_group group ''' if not path: path = '/' if get_group(group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_group(group_name, path) log.info('Created IAM group : %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM group %s.', group_name) return False def get_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group(group_name, max_items=1) if not info: return False return info['get_group_response']['get_group_result']['group'] except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_group_members(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: marker = None truncated = True users = [] while truncated: info = conn.get_group(group_name, marker=marker, max_items=1000) if not info: return False truncated = bool(info['get_group_response']['get_group_result']['is_truncated']) if truncated and 'marker' in info['get_group_response']['get_group_result']: marker = info['get_group_response']['get_group_result']['marker'] else: marker = None truncated = False users += info['get_group_response']['get_group_result']['users'] return users except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get members for IAM group %s.', group_name) return False def add_user_to_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Add user to group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.add_user_to_group myuser mygroup ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('Username : %s does not exist.', user_name) return False if user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.add_user_to_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add IAM user %s to group %s.', user_name, group_name) return False def user_exists_in_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Check if user exists in group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.user_exists_in_group myuser mygroup ''' # TODO this should probably use boto.iam.get_groups_for_user users = get_group_members( group_name=group_name, region=region, key=key, keyid=keyid, profile=profile ) if users: for _user in users: if user_name == _user['user_name']: log.debug('IAM user %s is already in IAM group %s.', user_name, group_name) return True return False def remove_user_from_group(group_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Remove user from group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.remove_user_from_group mygroup myuser ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist.', user_name) return False if not user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.remove_user_from_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove IAM user %s from group %s', user_name, group_name) return False def put_group_policy(group_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_group_policy mygroup policyname policyrules ''' group = get_group(group_name, region=region, key=key, keyid=keyid, profile=profile) if not group: log.error('Group %s does not exist', group_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_group_policy(group_name, policy_name, policy_json) if created: log.info('Created policy for IAM group %s.', group_name) return True log.error('Could not create policy for IAM group %s', group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy for IAM group %s', group_name) return False def delete_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group_policy mygroup mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_group_policy( group_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_group_policy(group_name, policy_name) log.info('Successfully deleted policy %s for IAM group %s.', policy_name, group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM group %s.', policy_name, group_name) return False def get_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group_policy mygroup policyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group_policy(group_name, policy_name) log.debug('info for group policy is : %s', info) if not info: return False info = info.get_group_policy_response.get_group_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_all_groups(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM group details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_groups ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _groups = conn.get_all_groups(path_prefix=path_prefix) groups = _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) while marker: _groups = conn.get_all_groups(path_prefix=path_prefix, marker=marker) groups = groups + _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) return groups def get_all_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.get_all_instance_profiles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) marker = False profiles = [] while marker is not None: marker = marker if marker else None p = conn.list_instance_profiles(path_prefix=path_prefix, marker=marker) res = p.list_instance_profiles_response.list_instance_profiles_result profiles += res.instance_profiles marker = getattr(res, 'marker', None) return profiles def list_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' List all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.list_instance_profiles ''' p = get_all_instance_profiles(path_prefix, region, key, keyid, profile) return [i['instance_profile_name'] for i in p] def get_all_group_policies(group_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a group. CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_group_policies mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False try: response = conn.get_all_group_policies(group_name) _list = response.list_group_policies_response.list_group_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def delete_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _group = get_group( group_name, region, key, keyid, profile ) if not _group: return True try: conn.delete_group(group_name) log.info('Successfully deleted IAM group %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM group %s.', group_name) return False def create_login_profile(user_name, password, region=None, key=None, keyid=None, profile=None): ''' Creates a login profile for the specified user, give the user the ability to access AWS services and the AWS Management Console. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_login_profile user_name password ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.create_login_profile(user_name, password) log.info('Created profile for IAM user %s.', user_name) return info except boto.exception.BotoServerError as e: log.debug(e) if 'Conflict' in e: log.info('Profile already exists for IAM user %s.', user_name) return 'Conflict' log.error('Failed to update profile for IAM user %s.', user_name) return False def delete_login_profile(user_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a login profile for the specified user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_login_profile user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.delete_login_profile(user_name) log.info('Deleted login profile for IAM user %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Login profile already deleted for IAM user %s.', user_name) return True log.error('Failed to delete login profile for IAM user %s.', user_name) return False def get_all_mfa_devices(user_name, region=None, key=None, keyid=None, profile=None): ''' Get all MFA devices associated with an IAM user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_mfa_devices user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: result = conn.get_all_mfa_devices(user_name) devices = result['list_mfa_devices_response']['list_mfa_devices_result']['mfa_devices'] return devices except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Could not find IAM user %s.', user_name) return [] log.error('Failed to get all MFA devices for IAM user %s.', user_name) return False def deactivate_mfa_device(user_name, serial, region=None, key=None, keyid=None, profile=None): ''' Deactivates the specified MFA device and removes it from association with the user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.deactivate_mfa_device user_name serial_num ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.deactivate_mfa_device(user_name, serial) log.info('Deactivated MFA device %s for IAM user %s.', serial, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('MFA device %s not associated with IAM user %s.', serial, user_name) return True log.error('Failed to deactivate MFA device %s for IAM user %s.', serial, user_name) return False def delete_virtual_mfa_device(serial, region=None, key=None, keyid=None, profile=None): ''' Deletes the specified virtual MFA device. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_virtual_mfa_device serial_num ''' conn = __utils__['boto3.get_connection_func']('iam')() try: conn.delete_virtual_mfa_device(SerialNumber=serial) log.info('Deleted virtual MFA device %s.', serial) return True except botocore.exceptions.ClientError as e: log.debug(e) if 'NoSuchEntity' in six.text_type(e): log.info('Virtual MFA device %s not found.', serial) return True log.error('Failed to delete virtual MFA device %s.', serial) return False def update_account_password_policy(allow_users_to_change_password=None, hard_expiry=None, max_password_age=None, minimum_password_length=None, password_reuse_prevention=None, require_lowercase_characters=None, require_numbers=None, require_symbols=None, require_uppercase_characters=None, region=None, key=None, keyid=None, profile=None): ''' Update the password policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_account_password_policy True ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.update_account_password_policy(allow_users_to_change_password, hard_expiry, max_password_age, minimum_password_length, password_reuse_prevention, require_lowercase_characters, require_numbers, require_symbols, require_uppercase_characters) log.info('The password policy has been updated.') return True except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy' log.error(msg) return False def get_account_policy(region=None, key=None, keyid=None, profile=None): ''' Get account policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_account_password_policy() return info.get_account_password_policy_response.get_account_password_policy_result.password_policy except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy.' log.error(msg) return False def create_role(name, policy_document=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Create an instance role. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if role_exists(name, region, key, keyid, profile): return True if not policy_document: policy_document = None try: conn.create_role(name, assume_role_policy_document=policy_document, path=path) log.info('Created IAM role %s.', name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to create IAM role %s.', name) return False def delete_role(name, region=None, key=None, keyid=None, profile=None): ''' Delete an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(name, region, key, keyid, profile): return True try: conn.delete_role(name) log.info('Deleted %s IAM role.', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s IAM role.', name) return False def profile_associated(role_name, profile_name, region, key, keyid, profile): ''' Check to see if an instance profile is associated with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.profile_associated myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # The IAM module of boto doesn't return objects. Instead you need to grab # values through its properties. Sigh. try: profiles = conn.list_instance_profiles_for_role(role_name) except boto.exception.BotoServerError as e: log.debug(e) return False profiles = profiles.list_instance_profiles_for_role_response profiles = profiles.list_instance_profiles_for_role_result profiles = profiles.instance_profiles for profile in profiles: if profile.instance_profile_name == profile_name: return True return False def associate_profile_to_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Associate an instance profile with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.associate_profile_to_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if associated: return True else: try: conn.add_role_to_instance_profile(profile_name, role_name) log.info('Added %s instance profile to IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add %s instance profile to IAM role %s', profile_name, role_name) return False def disassociate_profile_from_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Disassociate an instance profile from an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.disassociate_profile_from_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if not associated: return True else: try: conn.remove_role_from_instance_profile(profile_name, role_name) log.info('Removed %s instance profile from IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove %s instance profile from IAM role %s.', profile_name, role_name) return False def get_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.get_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: _policy = conn.get_role_policy(role_name, policy_name) # I _hate_ you for not giving me an object boto. _policy = _policy.get_role_policy_response.policy_document # Policy is url encoded _policy = _unquote(_policy) _policy = salt.utils.json.loads(_policy, object_pairs_hook=odict.OrderedDict) return _policy except boto.exception.BotoServerError: return {} def create_role_policy(role_name, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Create or modify a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role_policy myirole mypolicy '{"MyPolicy": "Statement": [{"Action": ["sqs:*"], "Effect": "Allow", "Resource": ["arn:aws:sqs:*:*:*"], "Sid": "MyPolicySqs1"}]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) mode = 'create' if _policy: if _policy == policy: return True mode = 'modify' if isinstance(policy, six.string_types): policy = salt.utils.json.loads(policy, object_pairs_hook=odict.OrderedDict) try: _policy = salt.utils.json.dumps(policy) conn.put_role_policy(role_name, policy_name, _policy) if mode == 'create': msg = 'Successfully added policy %s to IAM role %s.' else: msg = 'Successfully modified policy %s for IAM role %s.' log.info(msg, policy_name, role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to %s policy %s for IAM role %s.', mode, policy_name, role_name) return False def delete_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) if not _policy: return True try: conn.delete_role_policy(role_name, policy_name) log.info('Successfully deleted policy %s for IAM role %s.', policy_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM role %s.', policy_name, role_name) return False def update_assume_role_policy(role_name, policy_document, region=None, key=None, keyid=None, profile=None): ''' Update an assume role policy for a role. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_assume_role_policy myrole '{"Statement":"..."}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(policy_document, six.string_types): policy_document = salt.utils.json.loads(policy_document, object_pairs_hook=odict.OrderedDict) try: _policy_document = salt.utils.json.dumps(policy_document) conn.update_assume_role_policy(role_name, _policy_document) log.info('Successfully updated assume role policy for IAM role %s.', role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to update assume role policy for IAM role %s.', role_name) return False def build_policy(region=None, key=None, keyid=None, profile=None): ''' Build a default assume role policy. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.build_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if hasattr(conn, 'build_policy'): policy = salt.utils.json.loads(conn.build_policy()) elif hasattr(conn, '_build_policy'): policy = salt.utils.json.loads(conn._build_policy()) else: return {} # The format we get from build_policy isn't going to be what we get back # from AWS for the exact same policy. AWS converts single item list values # into strings, so let's do the same here. for key, policy_val in policy.items(): for statement in policy_val: if (isinstance(statement['Action'], list) and len(statement['Action']) == 1): statement['Action'] = statement['Action'][0] if (isinstance(statement['Principal']['Service'], list) and len(statement['Principal']['Service']) == 1): statement['Principal']['Service'] = statement['Principal']['Service'][0] # build_policy doesn't add a version field, which AWS is going to set to a # default value, when we get it back, so let's set it. policy['Version'] = '2008-10-17' return policy def get_account_id(region=None, key=None, keyid=None, profile=None): ''' Get a the AWS account id associated with the used credentials. CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_id ''' cache_key = 'boto_iam.account_id' if cache_key not in __context__: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_user() # The get_user call returns an user ARN: # arn:aws:iam::027050522557:user/salt-test arn = ret['get_user_response']['get_user_result']['user']['arn'] account_id = arn.split(':')[4] except boto.exception.BotoServerError: # If call failed, then let's try to get the ARN from the metadata timeout = boto.config.getfloat( 'Boto', 'metadata_service_timeout', 1.0 ) attempts = boto.config.getint( 'Boto', 'metadata_service_num_attempts', 1 ) identity = boto.utils.get_instance_identity( timeout=timeout, num_retries=attempts ) try: account_id = identity['document']['accountId'] except KeyError: log.error('Failed to get account id from instance_identity in' ' boto_iam.get_account_id.') __context__[cache_key] = account_id return __context__[cache_key] def get_all_roles(path_prefix=None, region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM role details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_roles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _roles = conn.list_roles(path_prefix=path_prefix) roles = _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) while marker: _roles = conn.list_roles(path_prefix=path_prefix, marker=marker) roles = roles + _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) return roles def get_all_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM user details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_users ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _users = conn.get_all_users(path_prefix=path_prefix) users = _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) while marker: _users = conn.get_all_users(path_prefix=path_prefix, marker=marker) users = users + _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) return users def get_all_user_policies(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all user policies. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_user_policies myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_all_user_policies(user_name, marker, max_items) if not info: return False _list = info.list_user_policies_response.list_user_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policies for user %s.', user_name) return False def get_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user_policy myuser mypolicyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user_policy(user_name, policy_name) log.debug('Info for IAM user %s policy %s: %s.', user_name, policy_name, info) if not info: return False info = info.get_user_policy_response.get_user_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policy %s for IAM user %s.', policy_name, user_name) return False def put_user_policy(user_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_user_policy myuser policyname policyrules ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_user_policy(user_name, policy_name, policy_json) if created: log.info('Created policy %s for IAM user %s.', policy_name, user_name) return True log.error('Could not create policy %s for IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy %s for IAM user %s.', policy_name, user_name) return False def delete_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user_policy myuser mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_user_policy( user_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_user_policy(user_name, policy_name) log.info('Successfully deleted policy %s for IAM user %s.', policy_name, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM user %s.', policy_name, user_name) return False def upload_server_cert(cert_name, cert_body, private_key, cert_chain=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Upload a certificate to Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.upload_server_cert mycert_name crt priv_key :param cert_name: The name for the server certificate. Do not include the path in this value. :param cert_body: The contents of the public key certificate in PEM-encoded format. :param private_key: The contents of the private key in PEM-encoded format. :param cert_chain: The contents of the certificate chain. This is typically a concatenation of the PEM-encoded public key certificates of the chain. :param path: The path for the server certificate. :param region: The name of the region to connect to. :param key: The key to be used in order to connect :param keyid: The keyid to be used in order to connect :param profile: The profile that contains a dict of region, key, keyid :return: True / False ''' exists = get_server_certificate(cert_name, region, key, keyid, profile) if exists: return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.upload_server_cert(cert_name, cert_body, private_key, cert_chain) log.info('Created certificate %s.', cert_name) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to failed to create certificate %s.', cert_name) return False def list_server_certificates(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Lists the server certificates stored in IAM that have the specified path prefix. .. versionadded:: ??? :param path_prefix: The path prefix for filtering the results. For example: /company/servercerts would get all server certificates for which the path starts with /company/servercerts . This parameter is optional. If it is not included, it defaults to a slash (/), listing all server certificates. This parameter allows (per its regex pattern) a string of characters consisting of either a forward slash (/) by itself or a string that must begin and end with forward slashes. In addition, it can contain any ASCII character from the ! (u0021) through the DEL character (u007F), including most punctuation characters, digits, and upper and lowercased letters. CLI Example: .. code-block:: bash salt myminion boto_iam.list_server_certificates path_prefix=/somepath/ ''' retries = 10 sleep = 6 conn = __utils__['boto3.get_connection']('iam', region=region, key=key, keyid=keyid, profile=profile) Items = [] while retries: try: log.debug('Garnering list of IAM Server Certificates') IsTruncated = True while IsTruncated: kwargs = {'PathPrefix': path_prefix} ret = conn.list_server_certificates(**kwargs) Items += ret.get('ServerCertificateMetadataList', []) IsTruncated = ret.get('IsTruncated') kwargs.update({'Marker': ret.get('Marker')}) return Items except botocore.exceptions.ParamValidationError as err: raise SaltInvocationError(str(err)) except botocore.exceptions.ClientError as err: if retries and jmespath.search('Error.Code', err.response) == 'Throttling': retries -= 1 log.debug('Throttled by AWS API, retrying in %s seconds...', sleep) time.sleep(sleep) continue log.error('Failed to list IAM Server Certificates: %s', err.message) return None def get_server_certificate(cert_name, region=None, key=None, keyid=None, profile=None): ''' Returns certificate information from Amazon .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_server_certificate mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_server_certificate(cert_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get certificate %s information.', cert_name) return False def delete_server_cert(cert_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a certificate from Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_server_cert mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_server_cert(cert_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete certificate %s.', cert_name) return False def export_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM user details. Produces results that can be used to create an sls file. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.export_users --out=txt | sed "s/local: //" > iam_users.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() users = get_all_users(path_prefix, region, key, keyid, profile) for user in users: name = user.user_name _policies = conn.get_all_user_policies(name, max_items=100) _policies = _policies.list_user_policies_response.list_user_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_user_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_user_policy_response.get_user_policy_result.policy_document )) policies[policy_name] = _policy user_sls = [] user_sls.append({"name": name}) user_sls.append({"policies": policies}) user_sls.append({"path": user.path}) results["manage user " + name] = {"boto_iam.user_present": user_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def export_roles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM role details. Produces results that can be used to create an sls file. CLI Example: salt-call boto_iam.export_roles --out=txt | sed "s/local: //" > iam_roles.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() roles = get_all_roles(path_prefix, region, key, keyid, profile) for role in roles: name = role.role_name _policies = conn.list_role_policies(name, max_items=100) _policies = _policies.list_role_policies_response.list_role_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_role_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_role_policy_response.get_role_policy_result.policy_document )) policies[policy_name] = _policy role_sls = [] role_sls.append({"name": name}) role_sls.append({"policies": policies}) role_sls.append({'policy_document': salt.utils.json.loads(_unquote(role.assume_role_policy_document))}) role_sls.append({"path": role.path}) results["manage role " + name] = {"boto_iam_role.present": role_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def _get_policy_arn(name, region=None, key=None, keyid=None, profile=None): if name.startswith('arn:aws:iam:'): return name account_id = get_account_id( region=region, key=key, keyid=keyid, profile=profile ) return 'arn:aws:iam::{0}:policy/{1}'.format(account_id, name) def policy_exists(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return True except boto.exception.BotoServerError: return False def get_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return ret.get('get_policy_response', {}).get('get_policy_result', {}) except boto.exception.BotoServerError: return None def create_policy(policy_name, policy_document, path=None, description=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in 'path', 'description': if locals()[arg] is not None: params[arg] = locals()[arg] if policy_exists(policy_name, region, key, keyid, profile): return True try: conn.create_policy(policy_name, policy_document, **params) log.info('Created IAM policy %s.', policy_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s.', policy_name) return False return True def delete_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_exists(policy_arn, region, key, keyid, profile): return True try: conn.delete_policy(policy_arn) log.info('Deleted %s policy.', policy_name) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete %s policy: %s.', policy_name, aws.get('message')) return False return True def list_policies(region=None, key=None, keyid=None, profile=None): ''' List policies. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policies ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: policies = [] for ret in __utils__['boto.paged_call'](conn.list_policies): policies.append(ret.get('list_policies_response', {}).get('list_policies_result', {}).get('policies')) return policies except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to list policy versions.' log.error(msg) return [] def policy_version_exists(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.get_policy_version(policy_arn, version_id) return True except boto.exception.BotoServerError: return False def get_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy_version(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile), version_id) retval = ret.get('get_policy_version_response', {}).get('get_policy_version_result', {}).get('policy_version', {}) retval['document'] = _unquote(retval.get('document')) return {'policy_version': retval} except boto.exception.BotoServerError: return None def create_policy_version(policy_name, policy_document, set_as_default=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy version. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy_version mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in ('set_as_default',): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.create_policy_version(policy_arn, policy_document, **params) vid = ret.get('create_policy_version_response', {}).get('create_policy_version_result', {}).get('policy_version', {}).get('version_id') log.info('Created IAM policy %s version %s.', policy_name, vid) return {'created': True, 'version_id': vid} except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s version %s.', policy_name, vid) return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Delete a policy version. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_version_exists(policy_arn, version_id, region, key, keyid, profile): return True try: conn.delete_policy_version(policy_arn, version_id) log.info('Deleted IAM policy %s version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete IAM policy %s version %s: %s', policy_name, version_id, aws.get('message')) return False return True def list_policy_versions(policy_name, region=None, key=None, keyid=None, profile=None): ''' List versions of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policy_versions mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.list_policy_versions(policy_arn) return ret.get('list_policy_versions_response', {}).get('list_policy_versions_result', {}).get('versions') except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list versions for IAM policy %s.', policy_name) return [] def set_default_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Set the default version of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.set_default_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.set_default_policy_version(policy_arn, version_id) log.info('Set %s policy to version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to set %s policy to version %s: %s', policy_name, version_id, aws.get('message')) return False return True def attach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_user_policy(policy_arn, user_name) log.info('Attached policy %s to IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach %s policy to IAM user %s.', policy_name, user_name) return False return True def detach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_user_policy(policy_arn, user_name) log.info('Detached %s policy from IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach %s policy from IAM user %s.', policy_name, user_name) return False return True def attach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_group_policy(policy_arn, group_name) log.info('Attached policy %s to IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM group %s.', policy_name, group_name) return False return True def detach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_group_policy(policy_arn, group_name) log.info('Detached policy %s from IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM group %s.', policy_name, group_name) return False return True def attach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_role_policy(policy_arn, role_name) log.info('Attached policy %s to IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM role %s.', policy_name, role_name) return False return True def detach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_role_policy(policy_arn, role_name) log.info('Detached policy %s from IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM role %s.', policy_name, role_name) return False return True def list_entities_for_policy(policy_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities that a policy is attached to. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 params = {} for arg in ('path_prefix', 'entity_filter'): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) while retries: try: allret = { 'policy_groups': [], 'policy_users': [], 'policy_roles': [], } for ret in __utils__['boto.paged_call'](conn.list_entities_for_policy, policy_arn=policy_arn, **params): for k, v in six.iteritems(allret): v.extend(ret.get('list_entities_for_policy_response', {}).get('list_entities_for_policy_result', {}).get(k)) return allret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('Failed to list entities for IAM policy %s: %s', policy_name, e.message) return {} return {} def list_attached_user_policies(user_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given user. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'UserName': user_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedUserPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_user_policies_response', {}).get('list_attached_user_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM user %s.', user_name) return [] def list_attached_group_policies(group_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given group. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'GroupName': group_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedGroupPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_group_policies_response', {}).get('list_attached_group_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM group %s.', group_name) return [] def list_attached_role_policies(role_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'RoleName': role_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedRolePolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_role_policies_response', {}).get('list_attached_role_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM role %s.', role_name) return [] def create_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Create SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.create_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_saml_provider(saml_metadata_document, name) log.info('Successfully created %s SAML provider.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to create SAML provider %s.', name) return False def get_saml_provider_arn(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider_arn my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_saml_providers() for saml_provider in response.list_saml_providers_response.list_saml_providers_result.saml_provider_list: if saml_provider['arn'].endswith(':saml-provider/' + name): return saml_provider['arn'] return False except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to get ARN of SAML provider %s.', name) return False def delete_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Delete SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.delete_saml_provider my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return True conn.delete_saml_provider(saml_provider_arn) log.info('Successfully deleted SAML provider %s.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete SAML provider %s.', name) return False def list_saml_providers(region=None, key=None, keyid=None, profile=None): ''' List SAML providers. CLI Example: .. code-block:: bash salt myminion boto_iam.list_saml_providers ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: providers = [] info = conn.list_saml_providers() for arn in info['list_saml_providers_response']['list_saml_providers_result']['saml_provider_list']: providers.append(arn['arn'].rsplit('/', 1)[1]) return providers except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get list of SAML providers.') return False def get_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider document. CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider arn ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: provider = conn.get_saml_provider(name) return provider['get_saml_provider_response']['get_saml_provider_result']['saml_metadata_document'] except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get SAML provider document %s.', name) return False def update_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Update SAML provider. CLI Example: .. code-block:: bash salt myminion boto_iam.update_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return False if conn.update_saml_provider(name, saml_metadata_document): return True return False except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to update SAML provider %s.', name) return False
saltstack/salt
salt/modules/boto_iam.py
get_role_policy
python
def get_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.get_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: _policy = conn.get_role_policy(role_name, policy_name) # I _hate_ you for not giving me an object boto. _policy = _policy.get_role_policy_response.policy_document # Policy is url encoded _policy = _unquote(_policy) _policy = salt.utils.json.loads(_policy, object_pairs_hook=odict.OrderedDict) return _policy except boto.exception.BotoServerError: return {}
Get a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.get_role_policy myirole mypolicy
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iam.py#L1123-L1145
[ "def loads(s, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.loads and prevents a traceback in the event that a bytestring is\n passed to the function. (Python < 3.6 cannot load bytestrings)\n\n You can pass an alternate json module (loaded via import_json() above)\n using the _json_module argument)\n '''\n json_module = kwargs.pop('_json_module', json)\n try:\n return json_module.loads(s, **kwargs)\n except TypeError as exc:\n # json.loads cannot load bytestrings in Python < 3.6\n if six.PY3 and isinstance(s, bytes):\n return json_module.loads(salt.utils.stringutils.to_unicode(s), **kwargs)\n else:\n raise exc\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon IAM .. versionadded:: 2014.7.0 :configuration: This module accepts explicit iam 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 iam.keyid: GKTADJGHEIQSXMKKRBJ08H iam.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs iam.region: 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: boto ''' # keep lint from choking on _get_conn and _cache_id #pylint: disable=E0602 # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import salt libs from salt.ext import six import salt.utils.compat import salt.utils.json import salt.utils.odict as odict import salt.utils.versions from salt.exceptions import SaltInvocationError # Import third party libs # pylint: disable=unused-import from salt.ext.six.moves.urllib.parse import unquote as _unquote # pylint: disable=no-name-in-module try: import boto import boto.iam import boto3 import botocore logging.getLogger('boto').setLevel(logging.CRITICAL) logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=unused-import log = logging.getLogger(__name__) def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'iam', pack=__salt__) def instance_profile_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an instance profile exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: # Boto weirdly returns an exception here if an instance profile doesn't # exist. conn.get_instance_profile(name) return True except boto.exception.BotoServerError: return False def create_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Create an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.create_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if instance_profile_exists(name, region, key, keyid, profile): return True try: # This call returns an instance profile if successful and an exception # if not. It's annoying. conn.create_instance_profile(name) log.info('Created %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create %s instance profile.', name) return False return True def delete_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Delete an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not instance_profile_exists(name, region, key, keyid, profile): return True try: conn.delete_instance_profile(name) log.info('Deleted %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s instance profile.', name) return False return True def role_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an IAM role exists. CLI Example: .. code-block:: bash salt myminion boto_iam.role_exists myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_role(name) return True except boto.exception.BotoServerError: return False def describe_role(name, region=None, key=None, keyid=None, profile=None): ''' Get information for a role. CLI Example: .. code-block:: bash salt myminion boto_iam.describe_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_role(name) if not info: return False role = info.get_role_response.get_role_result.role role['assume_role_policy_document'] = salt.utils.json.loads(_unquote( role.assume_role_policy_document )) # If Sid wasn't defined by the user, boto will still return a Sid in # each policy. To properly check idempotently, let's remove the Sid # from the return if it's not actually set. for policy_key, policy in role['assume_role_policy_document'].items(): if policy_key == 'Statement': for val in policy: if 'Sid' in val and not val['Sid']: del val['Sid'] return role except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get %s information.', name) return False def create_user(user_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_user myuser ''' if not path: path = '/' if get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_user(user_name, path) log.info('Created IAM user : %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM user %s.', user_name) return False def get_all_access_keys(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all access keys from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_access_keys myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.get_all_access_keys(user_name, marker, max_items) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get access keys for IAM user %s.', user_name) return six.text_type(e) def create_access_key(user_name, region=None, key=None, keyid=None, profile=None): ''' Create access key id for a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.create_access_key(user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create access key.') return six.text_type(e) def delete_access_key(access_key_id, user_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete access key id from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_access_key(access_key_id, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete access key id %s.', access_key_id) return six.text_type(e) def delete_user(user_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user myuser ''' if not get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.delete_user(user_name) log.info('Deleted IAM user : %s .', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM user %s', user_name) return six.text_type(e) def get_user(user_name=None, region=None, key=None, keyid=None, profile=None): ''' Get user information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user(user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM user %s info.', user_name) return False def create_group(group_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_group group ''' if not path: path = '/' if get_group(group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_group(group_name, path) log.info('Created IAM group : %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM group %s.', group_name) return False def get_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group(group_name, max_items=1) if not info: return False return info['get_group_response']['get_group_result']['group'] except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_group_members(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: marker = None truncated = True users = [] while truncated: info = conn.get_group(group_name, marker=marker, max_items=1000) if not info: return False truncated = bool(info['get_group_response']['get_group_result']['is_truncated']) if truncated and 'marker' in info['get_group_response']['get_group_result']: marker = info['get_group_response']['get_group_result']['marker'] else: marker = None truncated = False users += info['get_group_response']['get_group_result']['users'] return users except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get members for IAM group %s.', group_name) return False def add_user_to_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Add user to group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.add_user_to_group myuser mygroup ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('Username : %s does not exist.', user_name) return False if user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.add_user_to_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add IAM user %s to group %s.', user_name, group_name) return False def user_exists_in_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Check if user exists in group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.user_exists_in_group myuser mygroup ''' # TODO this should probably use boto.iam.get_groups_for_user users = get_group_members( group_name=group_name, region=region, key=key, keyid=keyid, profile=profile ) if users: for _user in users: if user_name == _user['user_name']: log.debug('IAM user %s is already in IAM group %s.', user_name, group_name) return True return False def remove_user_from_group(group_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Remove user from group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.remove_user_from_group mygroup myuser ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist.', user_name) return False if not user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.remove_user_from_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove IAM user %s from group %s', user_name, group_name) return False def put_group_policy(group_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_group_policy mygroup policyname policyrules ''' group = get_group(group_name, region=region, key=key, keyid=keyid, profile=profile) if not group: log.error('Group %s does not exist', group_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_group_policy(group_name, policy_name, policy_json) if created: log.info('Created policy for IAM group %s.', group_name) return True log.error('Could not create policy for IAM group %s', group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy for IAM group %s', group_name) return False def delete_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group_policy mygroup mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_group_policy( group_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_group_policy(group_name, policy_name) log.info('Successfully deleted policy %s for IAM group %s.', policy_name, group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM group %s.', policy_name, group_name) return False def get_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group_policy mygroup policyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group_policy(group_name, policy_name) log.debug('info for group policy is : %s', info) if not info: return False info = info.get_group_policy_response.get_group_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_all_groups(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM group details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_groups ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _groups = conn.get_all_groups(path_prefix=path_prefix) groups = _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) while marker: _groups = conn.get_all_groups(path_prefix=path_prefix, marker=marker) groups = groups + _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) return groups def get_all_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.get_all_instance_profiles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) marker = False profiles = [] while marker is not None: marker = marker if marker else None p = conn.list_instance_profiles(path_prefix=path_prefix, marker=marker) res = p.list_instance_profiles_response.list_instance_profiles_result profiles += res.instance_profiles marker = getattr(res, 'marker', None) return profiles def list_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' List all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.list_instance_profiles ''' p = get_all_instance_profiles(path_prefix, region, key, keyid, profile) return [i['instance_profile_name'] for i in p] def get_all_group_policies(group_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a group. CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_group_policies mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False try: response = conn.get_all_group_policies(group_name) _list = response.list_group_policies_response.list_group_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def delete_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _group = get_group( group_name, region, key, keyid, profile ) if not _group: return True try: conn.delete_group(group_name) log.info('Successfully deleted IAM group %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM group %s.', group_name) return False def create_login_profile(user_name, password, region=None, key=None, keyid=None, profile=None): ''' Creates a login profile for the specified user, give the user the ability to access AWS services and the AWS Management Console. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_login_profile user_name password ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.create_login_profile(user_name, password) log.info('Created profile for IAM user %s.', user_name) return info except boto.exception.BotoServerError as e: log.debug(e) if 'Conflict' in e: log.info('Profile already exists for IAM user %s.', user_name) return 'Conflict' log.error('Failed to update profile for IAM user %s.', user_name) return False def delete_login_profile(user_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a login profile for the specified user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_login_profile user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.delete_login_profile(user_name) log.info('Deleted login profile for IAM user %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Login profile already deleted for IAM user %s.', user_name) return True log.error('Failed to delete login profile for IAM user %s.', user_name) return False def get_all_mfa_devices(user_name, region=None, key=None, keyid=None, profile=None): ''' Get all MFA devices associated with an IAM user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_mfa_devices user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: result = conn.get_all_mfa_devices(user_name) devices = result['list_mfa_devices_response']['list_mfa_devices_result']['mfa_devices'] return devices except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Could not find IAM user %s.', user_name) return [] log.error('Failed to get all MFA devices for IAM user %s.', user_name) return False def deactivate_mfa_device(user_name, serial, region=None, key=None, keyid=None, profile=None): ''' Deactivates the specified MFA device and removes it from association with the user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.deactivate_mfa_device user_name serial_num ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.deactivate_mfa_device(user_name, serial) log.info('Deactivated MFA device %s for IAM user %s.', serial, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('MFA device %s not associated with IAM user %s.', serial, user_name) return True log.error('Failed to deactivate MFA device %s for IAM user %s.', serial, user_name) return False def delete_virtual_mfa_device(serial, region=None, key=None, keyid=None, profile=None): ''' Deletes the specified virtual MFA device. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_virtual_mfa_device serial_num ''' conn = __utils__['boto3.get_connection_func']('iam')() try: conn.delete_virtual_mfa_device(SerialNumber=serial) log.info('Deleted virtual MFA device %s.', serial) return True except botocore.exceptions.ClientError as e: log.debug(e) if 'NoSuchEntity' in six.text_type(e): log.info('Virtual MFA device %s not found.', serial) return True log.error('Failed to delete virtual MFA device %s.', serial) return False def update_account_password_policy(allow_users_to_change_password=None, hard_expiry=None, max_password_age=None, minimum_password_length=None, password_reuse_prevention=None, require_lowercase_characters=None, require_numbers=None, require_symbols=None, require_uppercase_characters=None, region=None, key=None, keyid=None, profile=None): ''' Update the password policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_account_password_policy True ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.update_account_password_policy(allow_users_to_change_password, hard_expiry, max_password_age, minimum_password_length, password_reuse_prevention, require_lowercase_characters, require_numbers, require_symbols, require_uppercase_characters) log.info('The password policy has been updated.') return True except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy' log.error(msg) return False def get_account_policy(region=None, key=None, keyid=None, profile=None): ''' Get account policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_account_password_policy() return info.get_account_password_policy_response.get_account_password_policy_result.password_policy except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy.' log.error(msg) return False def create_role(name, policy_document=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Create an instance role. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if role_exists(name, region, key, keyid, profile): return True if not policy_document: policy_document = None try: conn.create_role(name, assume_role_policy_document=policy_document, path=path) log.info('Created IAM role %s.', name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to create IAM role %s.', name) return False def delete_role(name, region=None, key=None, keyid=None, profile=None): ''' Delete an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(name, region, key, keyid, profile): return True try: conn.delete_role(name) log.info('Deleted %s IAM role.', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s IAM role.', name) return False def profile_associated(role_name, profile_name, region, key, keyid, profile): ''' Check to see if an instance profile is associated with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.profile_associated myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # The IAM module of boto doesn't return objects. Instead you need to grab # values through its properties. Sigh. try: profiles = conn.list_instance_profiles_for_role(role_name) except boto.exception.BotoServerError as e: log.debug(e) return False profiles = profiles.list_instance_profiles_for_role_response profiles = profiles.list_instance_profiles_for_role_result profiles = profiles.instance_profiles for profile in profiles: if profile.instance_profile_name == profile_name: return True return False def associate_profile_to_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Associate an instance profile with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.associate_profile_to_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if associated: return True else: try: conn.add_role_to_instance_profile(profile_name, role_name) log.info('Added %s instance profile to IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add %s instance profile to IAM role %s', profile_name, role_name) return False def disassociate_profile_from_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Disassociate an instance profile from an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.disassociate_profile_from_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if not associated: return True else: try: conn.remove_role_from_instance_profile(profile_name, role_name) log.info('Removed %s instance profile from IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove %s instance profile from IAM role %s.', profile_name, role_name) return False def list_role_policies(role_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_role_policies myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_role_policies(role_name) _list = response.list_role_policies_response.list_role_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def create_role_policy(role_name, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Create or modify a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role_policy myirole mypolicy '{"MyPolicy": "Statement": [{"Action": ["sqs:*"], "Effect": "Allow", "Resource": ["arn:aws:sqs:*:*:*"], "Sid": "MyPolicySqs1"}]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) mode = 'create' if _policy: if _policy == policy: return True mode = 'modify' if isinstance(policy, six.string_types): policy = salt.utils.json.loads(policy, object_pairs_hook=odict.OrderedDict) try: _policy = salt.utils.json.dumps(policy) conn.put_role_policy(role_name, policy_name, _policy) if mode == 'create': msg = 'Successfully added policy %s to IAM role %s.' else: msg = 'Successfully modified policy %s for IAM role %s.' log.info(msg, policy_name, role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to %s policy %s for IAM role %s.', mode, policy_name, role_name) return False def delete_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) if not _policy: return True try: conn.delete_role_policy(role_name, policy_name) log.info('Successfully deleted policy %s for IAM role %s.', policy_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM role %s.', policy_name, role_name) return False def update_assume_role_policy(role_name, policy_document, region=None, key=None, keyid=None, profile=None): ''' Update an assume role policy for a role. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_assume_role_policy myrole '{"Statement":"..."}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(policy_document, six.string_types): policy_document = salt.utils.json.loads(policy_document, object_pairs_hook=odict.OrderedDict) try: _policy_document = salt.utils.json.dumps(policy_document) conn.update_assume_role_policy(role_name, _policy_document) log.info('Successfully updated assume role policy for IAM role %s.', role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to update assume role policy for IAM role %s.', role_name) return False def build_policy(region=None, key=None, keyid=None, profile=None): ''' Build a default assume role policy. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.build_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if hasattr(conn, 'build_policy'): policy = salt.utils.json.loads(conn.build_policy()) elif hasattr(conn, '_build_policy'): policy = salt.utils.json.loads(conn._build_policy()) else: return {} # The format we get from build_policy isn't going to be what we get back # from AWS for the exact same policy. AWS converts single item list values # into strings, so let's do the same here. for key, policy_val in policy.items(): for statement in policy_val: if (isinstance(statement['Action'], list) and len(statement['Action']) == 1): statement['Action'] = statement['Action'][0] if (isinstance(statement['Principal']['Service'], list) and len(statement['Principal']['Service']) == 1): statement['Principal']['Service'] = statement['Principal']['Service'][0] # build_policy doesn't add a version field, which AWS is going to set to a # default value, when we get it back, so let's set it. policy['Version'] = '2008-10-17' return policy def get_account_id(region=None, key=None, keyid=None, profile=None): ''' Get a the AWS account id associated with the used credentials. CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_id ''' cache_key = 'boto_iam.account_id' if cache_key not in __context__: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_user() # The get_user call returns an user ARN: # arn:aws:iam::027050522557:user/salt-test arn = ret['get_user_response']['get_user_result']['user']['arn'] account_id = arn.split(':')[4] except boto.exception.BotoServerError: # If call failed, then let's try to get the ARN from the metadata timeout = boto.config.getfloat( 'Boto', 'metadata_service_timeout', 1.0 ) attempts = boto.config.getint( 'Boto', 'metadata_service_num_attempts', 1 ) identity = boto.utils.get_instance_identity( timeout=timeout, num_retries=attempts ) try: account_id = identity['document']['accountId'] except KeyError: log.error('Failed to get account id from instance_identity in' ' boto_iam.get_account_id.') __context__[cache_key] = account_id return __context__[cache_key] def get_all_roles(path_prefix=None, region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM role details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_roles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _roles = conn.list_roles(path_prefix=path_prefix) roles = _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) while marker: _roles = conn.list_roles(path_prefix=path_prefix, marker=marker) roles = roles + _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) return roles def get_all_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM user details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_users ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _users = conn.get_all_users(path_prefix=path_prefix) users = _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) while marker: _users = conn.get_all_users(path_prefix=path_prefix, marker=marker) users = users + _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) return users def get_all_user_policies(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all user policies. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_user_policies myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_all_user_policies(user_name, marker, max_items) if not info: return False _list = info.list_user_policies_response.list_user_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policies for user %s.', user_name) return False def get_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user_policy myuser mypolicyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user_policy(user_name, policy_name) log.debug('Info for IAM user %s policy %s: %s.', user_name, policy_name, info) if not info: return False info = info.get_user_policy_response.get_user_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policy %s for IAM user %s.', policy_name, user_name) return False def put_user_policy(user_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_user_policy myuser policyname policyrules ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_user_policy(user_name, policy_name, policy_json) if created: log.info('Created policy %s for IAM user %s.', policy_name, user_name) return True log.error('Could not create policy %s for IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy %s for IAM user %s.', policy_name, user_name) return False def delete_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user_policy myuser mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_user_policy( user_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_user_policy(user_name, policy_name) log.info('Successfully deleted policy %s for IAM user %s.', policy_name, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM user %s.', policy_name, user_name) return False def upload_server_cert(cert_name, cert_body, private_key, cert_chain=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Upload a certificate to Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.upload_server_cert mycert_name crt priv_key :param cert_name: The name for the server certificate. Do not include the path in this value. :param cert_body: The contents of the public key certificate in PEM-encoded format. :param private_key: The contents of the private key in PEM-encoded format. :param cert_chain: The contents of the certificate chain. This is typically a concatenation of the PEM-encoded public key certificates of the chain. :param path: The path for the server certificate. :param region: The name of the region to connect to. :param key: The key to be used in order to connect :param keyid: The keyid to be used in order to connect :param profile: The profile that contains a dict of region, key, keyid :return: True / False ''' exists = get_server_certificate(cert_name, region, key, keyid, profile) if exists: return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.upload_server_cert(cert_name, cert_body, private_key, cert_chain) log.info('Created certificate %s.', cert_name) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to failed to create certificate %s.', cert_name) return False def list_server_certificates(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Lists the server certificates stored in IAM that have the specified path prefix. .. versionadded:: ??? :param path_prefix: The path prefix for filtering the results. For example: /company/servercerts would get all server certificates for which the path starts with /company/servercerts . This parameter is optional. If it is not included, it defaults to a slash (/), listing all server certificates. This parameter allows (per its regex pattern) a string of characters consisting of either a forward slash (/) by itself or a string that must begin and end with forward slashes. In addition, it can contain any ASCII character from the ! (u0021) through the DEL character (u007F), including most punctuation characters, digits, and upper and lowercased letters. CLI Example: .. code-block:: bash salt myminion boto_iam.list_server_certificates path_prefix=/somepath/ ''' retries = 10 sleep = 6 conn = __utils__['boto3.get_connection']('iam', region=region, key=key, keyid=keyid, profile=profile) Items = [] while retries: try: log.debug('Garnering list of IAM Server Certificates') IsTruncated = True while IsTruncated: kwargs = {'PathPrefix': path_prefix} ret = conn.list_server_certificates(**kwargs) Items += ret.get('ServerCertificateMetadataList', []) IsTruncated = ret.get('IsTruncated') kwargs.update({'Marker': ret.get('Marker')}) return Items except botocore.exceptions.ParamValidationError as err: raise SaltInvocationError(str(err)) except botocore.exceptions.ClientError as err: if retries and jmespath.search('Error.Code', err.response) == 'Throttling': retries -= 1 log.debug('Throttled by AWS API, retrying in %s seconds...', sleep) time.sleep(sleep) continue log.error('Failed to list IAM Server Certificates: %s', err.message) return None def get_server_certificate(cert_name, region=None, key=None, keyid=None, profile=None): ''' Returns certificate information from Amazon .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_server_certificate mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_server_certificate(cert_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get certificate %s information.', cert_name) return False def delete_server_cert(cert_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a certificate from Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_server_cert mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_server_cert(cert_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete certificate %s.', cert_name) return False def export_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM user details. Produces results that can be used to create an sls file. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.export_users --out=txt | sed "s/local: //" > iam_users.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() users = get_all_users(path_prefix, region, key, keyid, profile) for user in users: name = user.user_name _policies = conn.get_all_user_policies(name, max_items=100) _policies = _policies.list_user_policies_response.list_user_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_user_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_user_policy_response.get_user_policy_result.policy_document )) policies[policy_name] = _policy user_sls = [] user_sls.append({"name": name}) user_sls.append({"policies": policies}) user_sls.append({"path": user.path}) results["manage user " + name] = {"boto_iam.user_present": user_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def export_roles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM role details. Produces results that can be used to create an sls file. CLI Example: salt-call boto_iam.export_roles --out=txt | sed "s/local: //" > iam_roles.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() roles = get_all_roles(path_prefix, region, key, keyid, profile) for role in roles: name = role.role_name _policies = conn.list_role_policies(name, max_items=100) _policies = _policies.list_role_policies_response.list_role_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_role_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_role_policy_response.get_role_policy_result.policy_document )) policies[policy_name] = _policy role_sls = [] role_sls.append({"name": name}) role_sls.append({"policies": policies}) role_sls.append({'policy_document': salt.utils.json.loads(_unquote(role.assume_role_policy_document))}) role_sls.append({"path": role.path}) results["manage role " + name] = {"boto_iam_role.present": role_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def _get_policy_arn(name, region=None, key=None, keyid=None, profile=None): if name.startswith('arn:aws:iam:'): return name account_id = get_account_id( region=region, key=key, keyid=keyid, profile=profile ) return 'arn:aws:iam::{0}:policy/{1}'.format(account_id, name) def policy_exists(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return True except boto.exception.BotoServerError: return False def get_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return ret.get('get_policy_response', {}).get('get_policy_result', {}) except boto.exception.BotoServerError: return None def create_policy(policy_name, policy_document, path=None, description=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in 'path', 'description': if locals()[arg] is not None: params[arg] = locals()[arg] if policy_exists(policy_name, region, key, keyid, profile): return True try: conn.create_policy(policy_name, policy_document, **params) log.info('Created IAM policy %s.', policy_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s.', policy_name) return False return True def delete_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_exists(policy_arn, region, key, keyid, profile): return True try: conn.delete_policy(policy_arn) log.info('Deleted %s policy.', policy_name) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete %s policy: %s.', policy_name, aws.get('message')) return False return True def list_policies(region=None, key=None, keyid=None, profile=None): ''' List policies. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policies ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: policies = [] for ret in __utils__['boto.paged_call'](conn.list_policies): policies.append(ret.get('list_policies_response', {}).get('list_policies_result', {}).get('policies')) return policies except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to list policy versions.' log.error(msg) return [] def policy_version_exists(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.get_policy_version(policy_arn, version_id) return True except boto.exception.BotoServerError: return False def get_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy_version(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile), version_id) retval = ret.get('get_policy_version_response', {}).get('get_policy_version_result', {}).get('policy_version', {}) retval['document'] = _unquote(retval.get('document')) return {'policy_version': retval} except boto.exception.BotoServerError: return None def create_policy_version(policy_name, policy_document, set_as_default=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy version. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy_version mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in ('set_as_default',): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.create_policy_version(policy_arn, policy_document, **params) vid = ret.get('create_policy_version_response', {}).get('create_policy_version_result', {}).get('policy_version', {}).get('version_id') log.info('Created IAM policy %s version %s.', policy_name, vid) return {'created': True, 'version_id': vid} except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s version %s.', policy_name, vid) return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Delete a policy version. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_version_exists(policy_arn, version_id, region, key, keyid, profile): return True try: conn.delete_policy_version(policy_arn, version_id) log.info('Deleted IAM policy %s version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete IAM policy %s version %s: %s', policy_name, version_id, aws.get('message')) return False return True def list_policy_versions(policy_name, region=None, key=None, keyid=None, profile=None): ''' List versions of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policy_versions mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.list_policy_versions(policy_arn) return ret.get('list_policy_versions_response', {}).get('list_policy_versions_result', {}).get('versions') except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list versions for IAM policy %s.', policy_name) return [] def set_default_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Set the default version of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.set_default_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.set_default_policy_version(policy_arn, version_id) log.info('Set %s policy to version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to set %s policy to version %s: %s', policy_name, version_id, aws.get('message')) return False return True def attach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_user_policy(policy_arn, user_name) log.info('Attached policy %s to IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach %s policy to IAM user %s.', policy_name, user_name) return False return True def detach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_user_policy(policy_arn, user_name) log.info('Detached %s policy from IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach %s policy from IAM user %s.', policy_name, user_name) return False return True def attach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_group_policy(policy_arn, group_name) log.info('Attached policy %s to IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM group %s.', policy_name, group_name) return False return True def detach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_group_policy(policy_arn, group_name) log.info('Detached policy %s from IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM group %s.', policy_name, group_name) return False return True def attach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_role_policy(policy_arn, role_name) log.info('Attached policy %s to IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM role %s.', policy_name, role_name) return False return True def detach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_role_policy(policy_arn, role_name) log.info('Detached policy %s from IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM role %s.', policy_name, role_name) return False return True def list_entities_for_policy(policy_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities that a policy is attached to. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 params = {} for arg in ('path_prefix', 'entity_filter'): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) while retries: try: allret = { 'policy_groups': [], 'policy_users': [], 'policy_roles': [], } for ret in __utils__['boto.paged_call'](conn.list_entities_for_policy, policy_arn=policy_arn, **params): for k, v in six.iteritems(allret): v.extend(ret.get('list_entities_for_policy_response', {}).get('list_entities_for_policy_result', {}).get(k)) return allret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('Failed to list entities for IAM policy %s: %s', policy_name, e.message) return {} return {} def list_attached_user_policies(user_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given user. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'UserName': user_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedUserPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_user_policies_response', {}).get('list_attached_user_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM user %s.', user_name) return [] def list_attached_group_policies(group_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given group. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'GroupName': group_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedGroupPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_group_policies_response', {}).get('list_attached_group_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM group %s.', group_name) return [] def list_attached_role_policies(role_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'RoleName': role_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedRolePolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_role_policies_response', {}).get('list_attached_role_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM role %s.', role_name) return [] def create_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Create SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.create_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_saml_provider(saml_metadata_document, name) log.info('Successfully created %s SAML provider.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to create SAML provider %s.', name) return False def get_saml_provider_arn(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider_arn my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_saml_providers() for saml_provider in response.list_saml_providers_response.list_saml_providers_result.saml_provider_list: if saml_provider['arn'].endswith(':saml-provider/' + name): return saml_provider['arn'] return False except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to get ARN of SAML provider %s.', name) return False def delete_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Delete SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.delete_saml_provider my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return True conn.delete_saml_provider(saml_provider_arn) log.info('Successfully deleted SAML provider %s.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete SAML provider %s.', name) return False def list_saml_providers(region=None, key=None, keyid=None, profile=None): ''' List SAML providers. CLI Example: .. code-block:: bash salt myminion boto_iam.list_saml_providers ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: providers = [] info = conn.list_saml_providers() for arn in info['list_saml_providers_response']['list_saml_providers_result']['saml_provider_list']: providers.append(arn['arn'].rsplit('/', 1)[1]) return providers except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get list of SAML providers.') return False def get_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider document. CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider arn ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: provider = conn.get_saml_provider(name) return provider['get_saml_provider_response']['get_saml_provider_result']['saml_metadata_document'] except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get SAML provider document %s.', name) return False def update_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Update SAML provider. CLI Example: .. code-block:: bash salt myminion boto_iam.update_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return False if conn.update_saml_provider(name, saml_metadata_document): return True return False except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to update SAML provider %s.', name) return False
saltstack/salt
salt/modules/boto_iam.py
create_role_policy
python
def create_role_policy(role_name, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Create or modify a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role_policy myirole mypolicy '{"MyPolicy": "Statement": [{"Action": ["sqs:*"], "Effect": "Allow", "Resource": ["arn:aws:sqs:*:*:*"], "Sid": "MyPolicySqs1"}]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) mode = 'create' if _policy: if _policy == policy: return True mode = 'modify' if isinstance(policy, six.string_types): policy = salt.utils.json.loads(policy, object_pairs_hook=odict.OrderedDict) try: _policy = salt.utils.json.dumps(policy) conn.put_role_policy(role_name, policy_name, _policy) if mode == 'create': msg = 'Successfully added policy %s to IAM role %s.' else: msg = 'Successfully modified policy %s for IAM role %s.' log.info(msg, policy_name, role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to %s policy %s for IAM role %s.', mode, policy_name, role_name) return False
Create or modify a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role_policy myirole mypolicy '{"MyPolicy": "Statement": [{"Action": ["sqs:*"], "Effect": "Allow", "Resource": ["arn:aws:sqs:*:*:*"], "Sid": "MyPolicySqs1"}]}'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iam.py#L1148-L1182
[ "def loads(s, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.loads and prevents a traceback in the event that a bytestring is\n passed to the function. (Python < 3.6 cannot load bytestrings)\n\n You can pass an alternate json module (loaded via import_json() above)\n using the _json_module argument)\n '''\n json_module = kwargs.pop('_json_module', json)\n try:\n return json_module.loads(s, **kwargs)\n except TypeError as exc:\n # json.loads cannot load bytestrings in Python < 3.6\n if six.PY3 and isinstance(s, bytes):\n return json_module.loads(salt.utils.stringutils.to_unicode(s), **kwargs)\n else:\n raise exc\n", "def dumps(obj, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.dumps, and assumes that ensure_ascii is False (unless explicitly\n passed as True) for unicode compatibility. Note that setting it to True\n will mess up any unicode characters, as they will be dumped as the string\n literal version of the unicode code point.\n\n On Python 2, encodes the result to a str since json.dumps does not want\n unicode types.\n\n You can pass an alternate json module (loaded via import_json() above)\n using the _json_module argument)\n '''\n json_module = kwargs.pop('_json_module', json)\n orig_enc_func = kwargs.pop('default', lambda x: x)\n\n def _enc_func(obj):\n obj = ThreadLocalProxy.unproxy(obj)\n return orig_enc_func(obj)\n\n if 'ensure_ascii' not in kwargs:\n kwargs['ensure_ascii'] = False\n if six.PY2:\n obj = salt.utils.data.encode(obj)\n return json_module.dumps(obj, default=_enc_func, **kwargs) # future lint: blacklisted-function\n", "def get_role_policy(role_name, policy_name, region=None, key=None,\n keyid=None, profile=None):\n '''\n Get a role policy.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_iam.get_role_policy myirole mypolicy\n '''\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n\n try:\n _policy = conn.get_role_policy(role_name, policy_name)\n # I _hate_ you for not giving me an object boto.\n _policy = _policy.get_role_policy_response.policy_document\n # Policy is url encoded\n _policy = _unquote(_policy)\n _policy = salt.utils.json.loads(_policy, object_pairs_hook=odict.OrderedDict)\n return _policy\n except boto.exception.BotoServerError:\n return {}\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon IAM .. versionadded:: 2014.7.0 :configuration: This module accepts explicit iam 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 iam.keyid: GKTADJGHEIQSXMKKRBJ08H iam.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs iam.region: 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: boto ''' # keep lint from choking on _get_conn and _cache_id #pylint: disable=E0602 # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import salt libs from salt.ext import six import salt.utils.compat import salt.utils.json import salt.utils.odict as odict import salt.utils.versions from salt.exceptions import SaltInvocationError # Import third party libs # pylint: disable=unused-import from salt.ext.six.moves.urllib.parse import unquote as _unquote # pylint: disable=no-name-in-module try: import boto import boto.iam import boto3 import botocore logging.getLogger('boto').setLevel(logging.CRITICAL) logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=unused-import log = logging.getLogger(__name__) def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'iam', pack=__salt__) def instance_profile_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an instance profile exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: # Boto weirdly returns an exception here if an instance profile doesn't # exist. conn.get_instance_profile(name) return True except boto.exception.BotoServerError: return False def create_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Create an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.create_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if instance_profile_exists(name, region, key, keyid, profile): return True try: # This call returns an instance profile if successful and an exception # if not. It's annoying. conn.create_instance_profile(name) log.info('Created %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create %s instance profile.', name) return False return True def delete_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Delete an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not instance_profile_exists(name, region, key, keyid, profile): return True try: conn.delete_instance_profile(name) log.info('Deleted %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s instance profile.', name) return False return True def role_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an IAM role exists. CLI Example: .. code-block:: bash salt myminion boto_iam.role_exists myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_role(name) return True except boto.exception.BotoServerError: return False def describe_role(name, region=None, key=None, keyid=None, profile=None): ''' Get information for a role. CLI Example: .. code-block:: bash salt myminion boto_iam.describe_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_role(name) if not info: return False role = info.get_role_response.get_role_result.role role['assume_role_policy_document'] = salt.utils.json.loads(_unquote( role.assume_role_policy_document )) # If Sid wasn't defined by the user, boto will still return a Sid in # each policy. To properly check idempotently, let's remove the Sid # from the return if it's not actually set. for policy_key, policy in role['assume_role_policy_document'].items(): if policy_key == 'Statement': for val in policy: if 'Sid' in val and not val['Sid']: del val['Sid'] return role except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get %s information.', name) return False def create_user(user_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_user myuser ''' if not path: path = '/' if get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_user(user_name, path) log.info('Created IAM user : %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM user %s.', user_name) return False def get_all_access_keys(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all access keys from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_access_keys myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.get_all_access_keys(user_name, marker, max_items) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get access keys for IAM user %s.', user_name) return six.text_type(e) def create_access_key(user_name, region=None, key=None, keyid=None, profile=None): ''' Create access key id for a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.create_access_key(user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create access key.') return six.text_type(e) def delete_access_key(access_key_id, user_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete access key id from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_access_key(access_key_id, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete access key id %s.', access_key_id) return six.text_type(e) def delete_user(user_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user myuser ''' if not get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.delete_user(user_name) log.info('Deleted IAM user : %s .', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM user %s', user_name) return six.text_type(e) def get_user(user_name=None, region=None, key=None, keyid=None, profile=None): ''' Get user information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user(user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM user %s info.', user_name) return False def create_group(group_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_group group ''' if not path: path = '/' if get_group(group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_group(group_name, path) log.info('Created IAM group : %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM group %s.', group_name) return False def get_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group(group_name, max_items=1) if not info: return False return info['get_group_response']['get_group_result']['group'] except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_group_members(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: marker = None truncated = True users = [] while truncated: info = conn.get_group(group_name, marker=marker, max_items=1000) if not info: return False truncated = bool(info['get_group_response']['get_group_result']['is_truncated']) if truncated and 'marker' in info['get_group_response']['get_group_result']: marker = info['get_group_response']['get_group_result']['marker'] else: marker = None truncated = False users += info['get_group_response']['get_group_result']['users'] return users except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get members for IAM group %s.', group_name) return False def add_user_to_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Add user to group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.add_user_to_group myuser mygroup ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('Username : %s does not exist.', user_name) return False if user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.add_user_to_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add IAM user %s to group %s.', user_name, group_name) return False def user_exists_in_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Check if user exists in group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.user_exists_in_group myuser mygroup ''' # TODO this should probably use boto.iam.get_groups_for_user users = get_group_members( group_name=group_name, region=region, key=key, keyid=keyid, profile=profile ) if users: for _user in users: if user_name == _user['user_name']: log.debug('IAM user %s is already in IAM group %s.', user_name, group_name) return True return False def remove_user_from_group(group_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Remove user from group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.remove_user_from_group mygroup myuser ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist.', user_name) return False if not user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.remove_user_from_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove IAM user %s from group %s', user_name, group_name) return False def put_group_policy(group_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_group_policy mygroup policyname policyrules ''' group = get_group(group_name, region=region, key=key, keyid=keyid, profile=profile) if not group: log.error('Group %s does not exist', group_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_group_policy(group_name, policy_name, policy_json) if created: log.info('Created policy for IAM group %s.', group_name) return True log.error('Could not create policy for IAM group %s', group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy for IAM group %s', group_name) return False def delete_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group_policy mygroup mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_group_policy( group_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_group_policy(group_name, policy_name) log.info('Successfully deleted policy %s for IAM group %s.', policy_name, group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM group %s.', policy_name, group_name) return False def get_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group_policy mygroup policyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group_policy(group_name, policy_name) log.debug('info for group policy is : %s', info) if not info: return False info = info.get_group_policy_response.get_group_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_all_groups(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM group details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_groups ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _groups = conn.get_all_groups(path_prefix=path_prefix) groups = _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) while marker: _groups = conn.get_all_groups(path_prefix=path_prefix, marker=marker) groups = groups + _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) return groups def get_all_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.get_all_instance_profiles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) marker = False profiles = [] while marker is not None: marker = marker if marker else None p = conn.list_instance_profiles(path_prefix=path_prefix, marker=marker) res = p.list_instance_profiles_response.list_instance_profiles_result profiles += res.instance_profiles marker = getattr(res, 'marker', None) return profiles def list_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' List all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.list_instance_profiles ''' p = get_all_instance_profiles(path_prefix, region, key, keyid, profile) return [i['instance_profile_name'] for i in p] def get_all_group_policies(group_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a group. CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_group_policies mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False try: response = conn.get_all_group_policies(group_name) _list = response.list_group_policies_response.list_group_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def delete_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _group = get_group( group_name, region, key, keyid, profile ) if not _group: return True try: conn.delete_group(group_name) log.info('Successfully deleted IAM group %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM group %s.', group_name) return False def create_login_profile(user_name, password, region=None, key=None, keyid=None, profile=None): ''' Creates a login profile for the specified user, give the user the ability to access AWS services and the AWS Management Console. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_login_profile user_name password ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.create_login_profile(user_name, password) log.info('Created profile for IAM user %s.', user_name) return info except boto.exception.BotoServerError as e: log.debug(e) if 'Conflict' in e: log.info('Profile already exists for IAM user %s.', user_name) return 'Conflict' log.error('Failed to update profile for IAM user %s.', user_name) return False def delete_login_profile(user_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a login profile for the specified user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_login_profile user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.delete_login_profile(user_name) log.info('Deleted login profile for IAM user %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Login profile already deleted for IAM user %s.', user_name) return True log.error('Failed to delete login profile for IAM user %s.', user_name) return False def get_all_mfa_devices(user_name, region=None, key=None, keyid=None, profile=None): ''' Get all MFA devices associated with an IAM user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_mfa_devices user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: result = conn.get_all_mfa_devices(user_name) devices = result['list_mfa_devices_response']['list_mfa_devices_result']['mfa_devices'] return devices except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Could not find IAM user %s.', user_name) return [] log.error('Failed to get all MFA devices for IAM user %s.', user_name) return False def deactivate_mfa_device(user_name, serial, region=None, key=None, keyid=None, profile=None): ''' Deactivates the specified MFA device and removes it from association with the user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.deactivate_mfa_device user_name serial_num ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.deactivate_mfa_device(user_name, serial) log.info('Deactivated MFA device %s for IAM user %s.', serial, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('MFA device %s not associated with IAM user %s.', serial, user_name) return True log.error('Failed to deactivate MFA device %s for IAM user %s.', serial, user_name) return False def delete_virtual_mfa_device(serial, region=None, key=None, keyid=None, profile=None): ''' Deletes the specified virtual MFA device. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_virtual_mfa_device serial_num ''' conn = __utils__['boto3.get_connection_func']('iam')() try: conn.delete_virtual_mfa_device(SerialNumber=serial) log.info('Deleted virtual MFA device %s.', serial) return True except botocore.exceptions.ClientError as e: log.debug(e) if 'NoSuchEntity' in six.text_type(e): log.info('Virtual MFA device %s not found.', serial) return True log.error('Failed to delete virtual MFA device %s.', serial) return False def update_account_password_policy(allow_users_to_change_password=None, hard_expiry=None, max_password_age=None, minimum_password_length=None, password_reuse_prevention=None, require_lowercase_characters=None, require_numbers=None, require_symbols=None, require_uppercase_characters=None, region=None, key=None, keyid=None, profile=None): ''' Update the password policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_account_password_policy True ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.update_account_password_policy(allow_users_to_change_password, hard_expiry, max_password_age, minimum_password_length, password_reuse_prevention, require_lowercase_characters, require_numbers, require_symbols, require_uppercase_characters) log.info('The password policy has been updated.') return True except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy' log.error(msg) return False def get_account_policy(region=None, key=None, keyid=None, profile=None): ''' Get account policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_account_password_policy() return info.get_account_password_policy_response.get_account_password_policy_result.password_policy except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy.' log.error(msg) return False def create_role(name, policy_document=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Create an instance role. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if role_exists(name, region, key, keyid, profile): return True if not policy_document: policy_document = None try: conn.create_role(name, assume_role_policy_document=policy_document, path=path) log.info('Created IAM role %s.', name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to create IAM role %s.', name) return False def delete_role(name, region=None, key=None, keyid=None, profile=None): ''' Delete an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(name, region, key, keyid, profile): return True try: conn.delete_role(name) log.info('Deleted %s IAM role.', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s IAM role.', name) return False def profile_associated(role_name, profile_name, region, key, keyid, profile): ''' Check to see if an instance profile is associated with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.profile_associated myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # The IAM module of boto doesn't return objects. Instead you need to grab # values through its properties. Sigh. try: profiles = conn.list_instance_profiles_for_role(role_name) except boto.exception.BotoServerError as e: log.debug(e) return False profiles = profiles.list_instance_profiles_for_role_response profiles = profiles.list_instance_profiles_for_role_result profiles = profiles.instance_profiles for profile in profiles: if profile.instance_profile_name == profile_name: return True return False def associate_profile_to_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Associate an instance profile with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.associate_profile_to_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if associated: return True else: try: conn.add_role_to_instance_profile(profile_name, role_name) log.info('Added %s instance profile to IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add %s instance profile to IAM role %s', profile_name, role_name) return False def disassociate_profile_from_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Disassociate an instance profile from an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.disassociate_profile_from_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if not associated: return True else: try: conn.remove_role_from_instance_profile(profile_name, role_name) log.info('Removed %s instance profile from IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove %s instance profile from IAM role %s.', profile_name, role_name) return False def list_role_policies(role_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_role_policies myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_role_policies(role_name) _list = response.list_role_policies_response.list_role_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def get_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.get_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: _policy = conn.get_role_policy(role_name, policy_name) # I _hate_ you for not giving me an object boto. _policy = _policy.get_role_policy_response.policy_document # Policy is url encoded _policy = _unquote(_policy) _policy = salt.utils.json.loads(_policy, object_pairs_hook=odict.OrderedDict) return _policy except boto.exception.BotoServerError: return {} def delete_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) if not _policy: return True try: conn.delete_role_policy(role_name, policy_name) log.info('Successfully deleted policy %s for IAM role %s.', policy_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM role %s.', policy_name, role_name) return False def update_assume_role_policy(role_name, policy_document, region=None, key=None, keyid=None, profile=None): ''' Update an assume role policy for a role. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_assume_role_policy myrole '{"Statement":"..."}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(policy_document, six.string_types): policy_document = salt.utils.json.loads(policy_document, object_pairs_hook=odict.OrderedDict) try: _policy_document = salt.utils.json.dumps(policy_document) conn.update_assume_role_policy(role_name, _policy_document) log.info('Successfully updated assume role policy for IAM role %s.', role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to update assume role policy for IAM role %s.', role_name) return False def build_policy(region=None, key=None, keyid=None, profile=None): ''' Build a default assume role policy. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.build_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if hasattr(conn, 'build_policy'): policy = salt.utils.json.loads(conn.build_policy()) elif hasattr(conn, '_build_policy'): policy = salt.utils.json.loads(conn._build_policy()) else: return {} # The format we get from build_policy isn't going to be what we get back # from AWS for the exact same policy. AWS converts single item list values # into strings, so let's do the same here. for key, policy_val in policy.items(): for statement in policy_val: if (isinstance(statement['Action'], list) and len(statement['Action']) == 1): statement['Action'] = statement['Action'][0] if (isinstance(statement['Principal']['Service'], list) and len(statement['Principal']['Service']) == 1): statement['Principal']['Service'] = statement['Principal']['Service'][0] # build_policy doesn't add a version field, which AWS is going to set to a # default value, when we get it back, so let's set it. policy['Version'] = '2008-10-17' return policy def get_account_id(region=None, key=None, keyid=None, profile=None): ''' Get a the AWS account id associated with the used credentials. CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_id ''' cache_key = 'boto_iam.account_id' if cache_key not in __context__: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_user() # The get_user call returns an user ARN: # arn:aws:iam::027050522557:user/salt-test arn = ret['get_user_response']['get_user_result']['user']['arn'] account_id = arn.split(':')[4] except boto.exception.BotoServerError: # If call failed, then let's try to get the ARN from the metadata timeout = boto.config.getfloat( 'Boto', 'metadata_service_timeout', 1.0 ) attempts = boto.config.getint( 'Boto', 'metadata_service_num_attempts', 1 ) identity = boto.utils.get_instance_identity( timeout=timeout, num_retries=attempts ) try: account_id = identity['document']['accountId'] except KeyError: log.error('Failed to get account id from instance_identity in' ' boto_iam.get_account_id.') __context__[cache_key] = account_id return __context__[cache_key] def get_all_roles(path_prefix=None, region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM role details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_roles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _roles = conn.list_roles(path_prefix=path_prefix) roles = _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) while marker: _roles = conn.list_roles(path_prefix=path_prefix, marker=marker) roles = roles + _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) return roles def get_all_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM user details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_users ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _users = conn.get_all_users(path_prefix=path_prefix) users = _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) while marker: _users = conn.get_all_users(path_prefix=path_prefix, marker=marker) users = users + _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) return users def get_all_user_policies(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all user policies. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_user_policies myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_all_user_policies(user_name, marker, max_items) if not info: return False _list = info.list_user_policies_response.list_user_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policies for user %s.', user_name) return False def get_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user_policy myuser mypolicyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user_policy(user_name, policy_name) log.debug('Info for IAM user %s policy %s: %s.', user_name, policy_name, info) if not info: return False info = info.get_user_policy_response.get_user_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policy %s for IAM user %s.', policy_name, user_name) return False def put_user_policy(user_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_user_policy myuser policyname policyrules ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_user_policy(user_name, policy_name, policy_json) if created: log.info('Created policy %s for IAM user %s.', policy_name, user_name) return True log.error('Could not create policy %s for IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy %s for IAM user %s.', policy_name, user_name) return False def delete_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user_policy myuser mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_user_policy( user_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_user_policy(user_name, policy_name) log.info('Successfully deleted policy %s for IAM user %s.', policy_name, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM user %s.', policy_name, user_name) return False def upload_server_cert(cert_name, cert_body, private_key, cert_chain=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Upload a certificate to Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.upload_server_cert mycert_name crt priv_key :param cert_name: The name for the server certificate. Do not include the path in this value. :param cert_body: The contents of the public key certificate in PEM-encoded format. :param private_key: The contents of the private key in PEM-encoded format. :param cert_chain: The contents of the certificate chain. This is typically a concatenation of the PEM-encoded public key certificates of the chain. :param path: The path for the server certificate. :param region: The name of the region to connect to. :param key: The key to be used in order to connect :param keyid: The keyid to be used in order to connect :param profile: The profile that contains a dict of region, key, keyid :return: True / False ''' exists = get_server_certificate(cert_name, region, key, keyid, profile) if exists: return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.upload_server_cert(cert_name, cert_body, private_key, cert_chain) log.info('Created certificate %s.', cert_name) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to failed to create certificate %s.', cert_name) return False def list_server_certificates(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Lists the server certificates stored in IAM that have the specified path prefix. .. versionadded:: ??? :param path_prefix: The path prefix for filtering the results. For example: /company/servercerts would get all server certificates for which the path starts with /company/servercerts . This parameter is optional. If it is not included, it defaults to a slash (/), listing all server certificates. This parameter allows (per its regex pattern) a string of characters consisting of either a forward slash (/) by itself or a string that must begin and end with forward slashes. In addition, it can contain any ASCII character from the ! (u0021) through the DEL character (u007F), including most punctuation characters, digits, and upper and lowercased letters. CLI Example: .. code-block:: bash salt myminion boto_iam.list_server_certificates path_prefix=/somepath/ ''' retries = 10 sleep = 6 conn = __utils__['boto3.get_connection']('iam', region=region, key=key, keyid=keyid, profile=profile) Items = [] while retries: try: log.debug('Garnering list of IAM Server Certificates') IsTruncated = True while IsTruncated: kwargs = {'PathPrefix': path_prefix} ret = conn.list_server_certificates(**kwargs) Items += ret.get('ServerCertificateMetadataList', []) IsTruncated = ret.get('IsTruncated') kwargs.update({'Marker': ret.get('Marker')}) return Items except botocore.exceptions.ParamValidationError as err: raise SaltInvocationError(str(err)) except botocore.exceptions.ClientError as err: if retries and jmespath.search('Error.Code', err.response) == 'Throttling': retries -= 1 log.debug('Throttled by AWS API, retrying in %s seconds...', sleep) time.sleep(sleep) continue log.error('Failed to list IAM Server Certificates: %s', err.message) return None def get_server_certificate(cert_name, region=None, key=None, keyid=None, profile=None): ''' Returns certificate information from Amazon .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_server_certificate mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_server_certificate(cert_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get certificate %s information.', cert_name) return False def delete_server_cert(cert_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a certificate from Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_server_cert mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_server_cert(cert_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete certificate %s.', cert_name) return False def export_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM user details. Produces results that can be used to create an sls file. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.export_users --out=txt | sed "s/local: //" > iam_users.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() users = get_all_users(path_prefix, region, key, keyid, profile) for user in users: name = user.user_name _policies = conn.get_all_user_policies(name, max_items=100) _policies = _policies.list_user_policies_response.list_user_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_user_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_user_policy_response.get_user_policy_result.policy_document )) policies[policy_name] = _policy user_sls = [] user_sls.append({"name": name}) user_sls.append({"policies": policies}) user_sls.append({"path": user.path}) results["manage user " + name] = {"boto_iam.user_present": user_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def export_roles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM role details. Produces results that can be used to create an sls file. CLI Example: salt-call boto_iam.export_roles --out=txt | sed "s/local: //" > iam_roles.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() roles = get_all_roles(path_prefix, region, key, keyid, profile) for role in roles: name = role.role_name _policies = conn.list_role_policies(name, max_items=100) _policies = _policies.list_role_policies_response.list_role_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_role_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_role_policy_response.get_role_policy_result.policy_document )) policies[policy_name] = _policy role_sls = [] role_sls.append({"name": name}) role_sls.append({"policies": policies}) role_sls.append({'policy_document': salt.utils.json.loads(_unquote(role.assume_role_policy_document))}) role_sls.append({"path": role.path}) results["manage role " + name] = {"boto_iam_role.present": role_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def _get_policy_arn(name, region=None, key=None, keyid=None, profile=None): if name.startswith('arn:aws:iam:'): return name account_id = get_account_id( region=region, key=key, keyid=keyid, profile=profile ) return 'arn:aws:iam::{0}:policy/{1}'.format(account_id, name) def policy_exists(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return True except boto.exception.BotoServerError: return False def get_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return ret.get('get_policy_response', {}).get('get_policy_result', {}) except boto.exception.BotoServerError: return None def create_policy(policy_name, policy_document, path=None, description=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in 'path', 'description': if locals()[arg] is not None: params[arg] = locals()[arg] if policy_exists(policy_name, region, key, keyid, profile): return True try: conn.create_policy(policy_name, policy_document, **params) log.info('Created IAM policy %s.', policy_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s.', policy_name) return False return True def delete_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_exists(policy_arn, region, key, keyid, profile): return True try: conn.delete_policy(policy_arn) log.info('Deleted %s policy.', policy_name) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete %s policy: %s.', policy_name, aws.get('message')) return False return True def list_policies(region=None, key=None, keyid=None, profile=None): ''' List policies. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policies ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: policies = [] for ret in __utils__['boto.paged_call'](conn.list_policies): policies.append(ret.get('list_policies_response', {}).get('list_policies_result', {}).get('policies')) return policies except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to list policy versions.' log.error(msg) return [] def policy_version_exists(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.get_policy_version(policy_arn, version_id) return True except boto.exception.BotoServerError: return False def get_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy_version(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile), version_id) retval = ret.get('get_policy_version_response', {}).get('get_policy_version_result', {}).get('policy_version', {}) retval['document'] = _unquote(retval.get('document')) return {'policy_version': retval} except boto.exception.BotoServerError: return None def create_policy_version(policy_name, policy_document, set_as_default=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy version. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy_version mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in ('set_as_default',): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.create_policy_version(policy_arn, policy_document, **params) vid = ret.get('create_policy_version_response', {}).get('create_policy_version_result', {}).get('policy_version', {}).get('version_id') log.info('Created IAM policy %s version %s.', policy_name, vid) return {'created': True, 'version_id': vid} except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s version %s.', policy_name, vid) return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Delete a policy version. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_version_exists(policy_arn, version_id, region, key, keyid, profile): return True try: conn.delete_policy_version(policy_arn, version_id) log.info('Deleted IAM policy %s version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete IAM policy %s version %s: %s', policy_name, version_id, aws.get('message')) return False return True def list_policy_versions(policy_name, region=None, key=None, keyid=None, profile=None): ''' List versions of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policy_versions mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.list_policy_versions(policy_arn) return ret.get('list_policy_versions_response', {}).get('list_policy_versions_result', {}).get('versions') except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list versions for IAM policy %s.', policy_name) return [] def set_default_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Set the default version of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.set_default_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.set_default_policy_version(policy_arn, version_id) log.info('Set %s policy to version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to set %s policy to version %s: %s', policy_name, version_id, aws.get('message')) return False return True def attach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_user_policy(policy_arn, user_name) log.info('Attached policy %s to IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach %s policy to IAM user %s.', policy_name, user_name) return False return True def detach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_user_policy(policy_arn, user_name) log.info('Detached %s policy from IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach %s policy from IAM user %s.', policy_name, user_name) return False return True def attach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_group_policy(policy_arn, group_name) log.info('Attached policy %s to IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM group %s.', policy_name, group_name) return False return True def detach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_group_policy(policy_arn, group_name) log.info('Detached policy %s from IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM group %s.', policy_name, group_name) return False return True def attach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_role_policy(policy_arn, role_name) log.info('Attached policy %s to IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM role %s.', policy_name, role_name) return False return True def detach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_role_policy(policy_arn, role_name) log.info('Detached policy %s from IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM role %s.', policy_name, role_name) return False return True def list_entities_for_policy(policy_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities that a policy is attached to. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 params = {} for arg in ('path_prefix', 'entity_filter'): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) while retries: try: allret = { 'policy_groups': [], 'policy_users': [], 'policy_roles': [], } for ret in __utils__['boto.paged_call'](conn.list_entities_for_policy, policy_arn=policy_arn, **params): for k, v in six.iteritems(allret): v.extend(ret.get('list_entities_for_policy_response', {}).get('list_entities_for_policy_result', {}).get(k)) return allret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('Failed to list entities for IAM policy %s: %s', policy_name, e.message) return {} return {} def list_attached_user_policies(user_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given user. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'UserName': user_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedUserPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_user_policies_response', {}).get('list_attached_user_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM user %s.', user_name) return [] def list_attached_group_policies(group_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given group. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'GroupName': group_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedGroupPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_group_policies_response', {}).get('list_attached_group_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM group %s.', group_name) return [] def list_attached_role_policies(role_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'RoleName': role_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedRolePolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_role_policies_response', {}).get('list_attached_role_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM role %s.', role_name) return [] def create_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Create SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.create_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_saml_provider(saml_metadata_document, name) log.info('Successfully created %s SAML provider.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to create SAML provider %s.', name) return False def get_saml_provider_arn(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider_arn my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_saml_providers() for saml_provider in response.list_saml_providers_response.list_saml_providers_result.saml_provider_list: if saml_provider['arn'].endswith(':saml-provider/' + name): return saml_provider['arn'] return False except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to get ARN of SAML provider %s.', name) return False def delete_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Delete SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.delete_saml_provider my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return True conn.delete_saml_provider(saml_provider_arn) log.info('Successfully deleted SAML provider %s.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete SAML provider %s.', name) return False def list_saml_providers(region=None, key=None, keyid=None, profile=None): ''' List SAML providers. CLI Example: .. code-block:: bash salt myminion boto_iam.list_saml_providers ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: providers = [] info = conn.list_saml_providers() for arn in info['list_saml_providers_response']['list_saml_providers_result']['saml_provider_list']: providers.append(arn['arn'].rsplit('/', 1)[1]) return providers except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get list of SAML providers.') return False def get_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider document. CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider arn ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: provider = conn.get_saml_provider(name) return provider['get_saml_provider_response']['get_saml_provider_result']['saml_metadata_document'] except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get SAML provider document %s.', name) return False def update_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Update SAML provider. CLI Example: .. code-block:: bash salt myminion boto_iam.update_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return False if conn.update_saml_provider(name, saml_metadata_document): return True return False except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to update SAML provider %s.', name) return False
saltstack/salt
salt/modules/boto_iam.py
delete_role_policy
python
def delete_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) if not _policy: return True try: conn.delete_role_policy(role_name, policy_name) log.info('Successfully deleted policy %s for IAM role %s.', policy_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM role %s.', policy_name, role_name) return False
Delete a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role_policy myirole mypolicy
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iam.py#L1185-L1210
[ "def get_role_policy(role_name, policy_name, region=None, key=None,\n keyid=None, profile=None):\n '''\n Get a role policy.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_iam.get_role_policy myirole mypolicy\n '''\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n\n try:\n _policy = conn.get_role_policy(role_name, policy_name)\n # I _hate_ you for not giving me an object boto.\n _policy = _policy.get_role_policy_response.policy_document\n # Policy is url encoded\n _policy = _unquote(_policy)\n _policy = salt.utils.json.loads(_policy, object_pairs_hook=odict.OrderedDict)\n return _policy\n except boto.exception.BotoServerError:\n return {}\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon IAM .. versionadded:: 2014.7.0 :configuration: This module accepts explicit iam 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 iam.keyid: GKTADJGHEIQSXMKKRBJ08H iam.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs iam.region: 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: boto ''' # keep lint from choking on _get_conn and _cache_id #pylint: disable=E0602 # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import salt libs from salt.ext import six import salt.utils.compat import salt.utils.json import salt.utils.odict as odict import salt.utils.versions from salt.exceptions import SaltInvocationError # Import third party libs # pylint: disable=unused-import from salt.ext.six.moves.urllib.parse import unquote as _unquote # pylint: disable=no-name-in-module try: import boto import boto.iam import boto3 import botocore logging.getLogger('boto').setLevel(logging.CRITICAL) logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=unused-import log = logging.getLogger(__name__) def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'iam', pack=__salt__) def instance_profile_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an instance profile exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: # Boto weirdly returns an exception here if an instance profile doesn't # exist. conn.get_instance_profile(name) return True except boto.exception.BotoServerError: return False def create_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Create an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.create_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if instance_profile_exists(name, region, key, keyid, profile): return True try: # This call returns an instance profile if successful and an exception # if not. It's annoying. conn.create_instance_profile(name) log.info('Created %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create %s instance profile.', name) return False return True def delete_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Delete an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not instance_profile_exists(name, region, key, keyid, profile): return True try: conn.delete_instance_profile(name) log.info('Deleted %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s instance profile.', name) return False return True def role_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an IAM role exists. CLI Example: .. code-block:: bash salt myminion boto_iam.role_exists myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_role(name) return True except boto.exception.BotoServerError: return False def describe_role(name, region=None, key=None, keyid=None, profile=None): ''' Get information for a role. CLI Example: .. code-block:: bash salt myminion boto_iam.describe_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_role(name) if not info: return False role = info.get_role_response.get_role_result.role role['assume_role_policy_document'] = salt.utils.json.loads(_unquote( role.assume_role_policy_document )) # If Sid wasn't defined by the user, boto will still return a Sid in # each policy. To properly check idempotently, let's remove the Sid # from the return if it's not actually set. for policy_key, policy in role['assume_role_policy_document'].items(): if policy_key == 'Statement': for val in policy: if 'Sid' in val and not val['Sid']: del val['Sid'] return role except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get %s information.', name) return False def create_user(user_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_user myuser ''' if not path: path = '/' if get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_user(user_name, path) log.info('Created IAM user : %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM user %s.', user_name) return False def get_all_access_keys(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all access keys from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_access_keys myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.get_all_access_keys(user_name, marker, max_items) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get access keys for IAM user %s.', user_name) return six.text_type(e) def create_access_key(user_name, region=None, key=None, keyid=None, profile=None): ''' Create access key id for a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.create_access_key(user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create access key.') return six.text_type(e) def delete_access_key(access_key_id, user_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete access key id from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_access_key(access_key_id, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete access key id %s.', access_key_id) return six.text_type(e) def delete_user(user_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user myuser ''' if not get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.delete_user(user_name) log.info('Deleted IAM user : %s .', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM user %s', user_name) return six.text_type(e) def get_user(user_name=None, region=None, key=None, keyid=None, profile=None): ''' Get user information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user(user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM user %s info.', user_name) return False def create_group(group_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_group group ''' if not path: path = '/' if get_group(group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_group(group_name, path) log.info('Created IAM group : %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM group %s.', group_name) return False def get_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group(group_name, max_items=1) if not info: return False return info['get_group_response']['get_group_result']['group'] except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_group_members(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: marker = None truncated = True users = [] while truncated: info = conn.get_group(group_name, marker=marker, max_items=1000) if not info: return False truncated = bool(info['get_group_response']['get_group_result']['is_truncated']) if truncated and 'marker' in info['get_group_response']['get_group_result']: marker = info['get_group_response']['get_group_result']['marker'] else: marker = None truncated = False users += info['get_group_response']['get_group_result']['users'] return users except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get members for IAM group %s.', group_name) return False def add_user_to_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Add user to group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.add_user_to_group myuser mygroup ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('Username : %s does not exist.', user_name) return False if user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.add_user_to_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add IAM user %s to group %s.', user_name, group_name) return False def user_exists_in_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Check if user exists in group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.user_exists_in_group myuser mygroup ''' # TODO this should probably use boto.iam.get_groups_for_user users = get_group_members( group_name=group_name, region=region, key=key, keyid=keyid, profile=profile ) if users: for _user in users: if user_name == _user['user_name']: log.debug('IAM user %s is already in IAM group %s.', user_name, group_name) return True return False def remove_user_from_group(group_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Remove user from group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.remove_user_from_group mygroup myuser ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist.', user_name) return False if not user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.remove_user_from_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove IAM user %s from group %s', user_name, group_name) return False def put_group_policy(group_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_group_policy mygroup policyname policyrules ''' group = get_group(group_name, region=region, key=key, keyid=keyid, profile=profile) if not group: log.error('Group %s does not exist', group_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_group_policy(group_name, policy_name, policy_json) if created: log.info('Created policy for IAM group %s.', group_name) return True log.error('Could not create policy for IAM group %s', group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy for IAM group %s', group_name) return False def delete_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group_policy mygroup mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_group_policy( group_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_group_policy(group_name, policy_name) log.info('Successfully deleted policy %s for IAM group %s.', policy_name, group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM group %s.', policy_name, group_name) return False def get_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group_policy mygroup policyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group_policy(group_name, policy_name) log.debug('info for group policy is : %s', info) if not info: return False info = info.get_group_policy_response.get_group_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_all_groups(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM group details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_groups ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _groups = conn.get_all_groups(path_prefix=path_prefix) groups = _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) while marker: _groups = conn.get_all_groups(path_prefix=path_prefix, marker=marker) groups = groups + _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) return groups def get_all_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.get_all_instance_profiles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) marker = False profiles = [] while marker is not None: marker = marker if marker else None p = conn.list_instance_profiles(path_prefix=path_prefix, marker=marker) res = p.list_instance_profiles_response.list_instance_profiles_result profiles += res.instance_profiles marker = getattr(res, 'marker', None) return profiles def list_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' List all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.list_instance_profiles ''' p = get_all_instance_profiles(path_prefix, region, key, keyid, profile) return [i['instance_profile_name'] for i in p] def get_all_group_policies(group_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a group. CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_group_policies mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False try: response = conn.get_all_group_policies(group_name) _list = response.list_group_policies_response.list_group_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def delete_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _group = get_group( group_name, region, key, keyid, profile ) if not _group: return True try: conn.delete_group(group_name) log.info('Successfully deleted IAM group %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM group %s.', group_name) return False def create_login_profile(user_name, password, region=None, key=None, keyid=None, profile=None): ''' Creates a login profile for the specified user, give the user the ability to access AWS services and the AWS Management Console. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_login_profile user_name password ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.create_login_profile(user_name, password) log.info('Created profile for IAM user %s.', user_name) return info except boto.exception.BotoServerError as e: log.debug(e) if 'Conflict' in e: log.info('Profile already exists for IAM user %s.', user_name) return 'Conflict' log.error('Failed to update profile for IAM user %s.', user_name) return False def delete_login_profile(user_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a login profile for the specified user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_login_profile user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.delete_login_profile(user_name) log.info('Deleted login profile for IAM user %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Login profile already deleted for IAM user %s.', user_name) return True log.error('Failed to delete login profile for IAM user %s.', user_name) return False def get_all_mfa_devices(user_name, region=None, key=None, keyid=None, profile=None): ''' Get all MFA devices associated with an IAM user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_mfa_devices user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: result = conn.get_all_mfa_devices(user_name) devices = result['list_mfa_devices_response']['list_mfa_devices_result']['mfa_devices'] return devices except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Could not find IAM user %s.', user_name) return [] log.error('Failed to get all MFA devices for IAM user %s.', user_name) return False def deactivate_mfa_device(user_name, serial, region=None, key=None, keyid=None, profile=None): ''' Deactivates the specified MFA device and removes it from association with the user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.deactivate_mfa_device user_name serial_num ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.deactivate_mfa_device(user_name, serial) log.info('Deactivated MFA device %s for IAM user %s.', serial, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('MFA device %s not associated with IAM user %s.', serial, user_name) return True log.error('Failed to deactivate MFA device %s for IAM user %s.', serial, user_name) return False def delete_virtual_mfa_device(serial, region=None, key=None, keyid=None, profile=None): ''' Deletes the specified virtual MFA device. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_virtual_mfa_device serial_num ''' conn = __utils__['boto3.get_connection_func']('iam')() try: conn.delete_virtual_mfa_device(SerialNumber=serial) log.info('Deleted virtual MFA device %s.', serial) return True except botocore.exceptions.ClientError as e: log.debug(e) if 'NoSuchEntity' in six.text_type(e): log.info('Virtual MFA device %s not found.', serial) return True log.error('Failed to delete virtual MFA device %s.', serial) return False def update_account_password_policy(allow_users_to_change_password=None, hard_expiry=None, max_password_age=None, minimum_password_length=None, password_reuse_prevention=None, require_lowercase_characters=None, require_numbers=None, require_symbols=None, require_uppercase_characters=None, region=None, key=None, keyid=None, profile=None): ''' Update the password policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_account_password_policy True ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.update_account_password_policy(allow_users_to_change_password, hard_expiry, max_password_age, minimum_password_length, password_reuse_prevention, require_lowercase_characters, require_numbers, require_symbols, require_uppercase_characters) log.info('The password policy has been updated.') return True except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy' log.error(msg) return False def get_account_policy(region=None, key=None, keyid=None, profile=None): ''' Get account policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_account_password_policy() return info.get_account_password_policy_response.get_account_password_policy_result.password_policy except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy.' log.error(msg) return False def create_role(name, policy_document=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Create an instance role. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if role_exists(name, region, key, keyid, profile): return True if not policy_document: policy_document = None try: conn.create_role(name, assume_role_policy_document=policy_document, path=path) log.info('Created IAM role %s.', name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to create IAM role %s.', name) return False def delete_role(name, region=None, key=None, keyid=None, profile=None): ''' Delete an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(name, region, key, keyid, profile): return True try: conn.delete_role(name) log.info('Deleted %s IAM role.', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s IAM role.', name) return False def profile_associated(role_name, profile_name, region, key, keyid, profile): ''' Check to see if an instance profile is associated with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.profile_associated myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # The IAM module of boto doesn't return objects. Instead you need to grab # values through its properties. Sigh. try: profiles = conn.list_instance_profiles_for_role(role_name) except boto.exception.BotoServerError as e: log.debug(e) return False profiles = profiles.list_instance_profiles_for_role_response profiles = profiles.list_instance_profiles_for_role_result profiles = profiles.instance_profiles for profile in profiles: if profile.instance_profile_name == profile_name: return True return False def associate_profile_to_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Associate an instance profile with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.associate_profile_to_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if associated: return True else: try: conn.add_role_to_instance_profile(profile_name, role_name) log.info('Added %s instance profile to IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add %s instance profile to IAM role %s', profile_name, role_name) return False def disassociate_profile_from_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Disassociate an instance profile from an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.disassociate_profile_from_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if not associated: return True else: try: conn.remove_role_from_instance_profile(profile_name, role_name) log.info('Removed %s instance profile from IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove %s instance profile from IAM role %s.', profile_name, role_name) return False def list_role_policies(role_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_role_policies myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_role_policies(role_name) _list = response.list_role_policies_response.list_role_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def get_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.get_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: _policy = conn.get_role_policy(role_name, policy_name) # I _hate_ you for not giving me an object boto. _policy = _policy.get_role_policy_response.policy_document # Policy is url encoded _policy = _unquote(_policy) _policy = salt.utils.json.loads(_policy, object_pairs_hook=odict.OrderedDict) return _policy except boto.exception.BotoServerError: return {} def create_role_policy(role_name, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Create or modify a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role_policy myirole mypolicy '{"MyPolicy": "Statement": [{"Action": ["sqs:*"], "Effect": "Allow", "Resource": ["arn:aws:sqs:*:*:*"], "Sid": "MyPolicySqs1"}]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) mode = 'create' if _policy: if _policy == policy: return True mode = 'modify' if isinstance(policy, six.string_types): policy = salt.utils.json.loads(policy, object_pairs_hook=odict.OrderedDict) try: _policy = salt.utils.json.dumps(policy) conn.put_role_policy(role_name, policy_name, _policy) if mode == 'create': msg = 'Successfully added policy %s to IAM role %s.' else: msg = 'Successfully modified policy %s for IAM role %s.' log.info(msg, policy_name, role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to %s policy %s for IAM role %s.', mode, policy_name, role_name) return False def update_assume_role_policy(role_name, policy_document, region=None, key=None, keyid=None, profile=None): ''' Update an assume role policy for a role. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_assume_role_policy myrole '{"Statement":"..."}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(policy_document, six.string_types): policy_document = salt.utils.json.loads(policy_document, object_pairs_hook=odict.OrderedDict) try: _policy_document = salt.utils.json.dumps(policy_document) conn.update_assume_role_policy(role_name, _policy_document) log.info('Successfully updated assume role policy for IAM role %s.', role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to update assume role policy for IAM role %s.', role_name) return False def build_policy(region=None, key=None, keyid=None, profile=None): ''' Build a default assume role policy. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.build_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if hasattr(conn, 'build_policy'): policy = salt.utils.json.loads(conn.build_policy()) elif hasattr(conn, '_build_policy'): policy = salt.utils.json.loads(conn._build_policy()) else: return {} # The format we get from build_policy isn't going to be what we get back # from AWS for the exact same policy. AWS converts single item list values # into strings, so let's do the same here. for key, policy_val in policy.items(): for statement in policy_val: if (isinstance(statement['Action'], list) and len(statement['Action']) == 1): statement['Action'] = statement['Action'][0] if (isinstance(statement['Principal']['Service'], list) and len(statement['Principal']['Service']) == 1): statement['Principal']['Service'] = statement['Principal']['Service'][0] # build_policy doesn't add a version field, which AWS is going to set to a # default value, when we get it back, so let's set it. policy['Version'] = '2008-10-17' return policy def get_account_id(region=None, key=None, keyid=None, profile=None): ''' Get a the AWS account id associated with the used credentials. CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_id ''' cache_key = 'boto_iam.account_id' if cache_key not in __context__: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_user() # The get_user call returns an user ARN: # arn:aws:iam::027050522557:user/salt-test arn = ret['get_user_response']['get_user_result']['user']['arn'] account_id = arn.split(':')[4] except boto.exception.BotoServerError: # If call failed, then let's try to get the ARN from the metadata timeout = boto.config.getfloat( 'Boto', 'metadata_service_timeout', 1.0 ) attempts = boto.config.getint( 'Boto', 'metadata_service_num_attempts', 1 ) identity = boto.utils.get_instance_identity( timeout=timeout, num_retries=attempts ) try: account_id = identity['document']['accountId'] except KeyError: log.error('Failed to get account id from instance_identity in' ' boto_iam.get_account_id.') __context__[cache_key] = account_id return __context__[cache_key] def get_all_roles(path_prefix=None, region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM role details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_roles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _roles = conn.list_roles(path_prefix=path_prefix) roles = _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) while marker: _roles = conn.list_roles(path_prefix=path_prefix, marker=marker) roles = roles + _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) return roles def get_all_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM user details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_users ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _users = conn.get_all_users(path_prefix=path_prefix) users = _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) while marker: _users = conn.get_all_users(path_prefix=path_prefix, marker=marker) users = users + _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) return users def get_all_user_policies(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all user policies. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_user_policies myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_all_user_policies(user_name, marker, max_items) if not info: return False _list = info.list_user_policies_response.list_user_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policies for user %s.', user_name) return False def get_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user_policy myuser mypolicyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user_policy(user_name, policy_name) log.debug('Info for IAM user %s policy %s: %s.', user_name, policy_name, info) if not info: return False info = info.get_user_policy_response.get_user_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policy %s for IAM user %s.', policy_name, user_name) return False def put_user_policy(user_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_user_policy myuser policyname policyrules ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_user_policy(user_name, policy_name, policy_json) if created: log.info('Created policy %s for IAM user %s.', policy_name, user_name) return True log.error('Could not create policy %s for IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy %s for IAM user %s.', policy_name, user_name) return False def delete_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user_policy myuser mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_user_policy( user_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_user_policy(user_name, policy_name) log.info('Successfully deleted policy %s for IAM user %s.', policy_name, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM user %s.', policy_name, user_name) return False def upload_server_cert(cert_name, cert_body, private_key, cert_chain=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Upload a certificate to Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.upload_server_cert mycert_name crt priv_key :param cert_name: The name for the server certificate. Do not include the path in this value. :param cert_body: The contents of the public key certificate in PEM-encoded format. :param private_key: The contents of the private key in PEM-encoded format. :param cert_chain: The contents of the certificate chain. This is typically a concatenation of the PEM-encoded public key certificates of the chain. :param path: The path for the server certificate. :param region: The name of the region to connect to. :param key: The key to be used in order to connect :param keyid: The keyid to be used in order to connect :param profile: The profile that contains a dict of region, key, keyid :return: True / False ''' exists = get_server_certificate(cert_name, region, key, keyid, profile) if exists: return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.upload_server_cert(cert_name, cert_body, private_key, cert_chain) log.info('Created certificate %s.', cert_name) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to failed to create certificate %s.', cert_name) return False def list_server_certificates(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Lists the server certificates stored in IAM that have the specified path prefix. .. versionadded:: ??? :param path_prefix: The path prefix for filtering the results. For example: /company/servercerts would get all server certificates for which the path starts with /company/servercerts . This parameter is optional. If it is not included, it defaults to a slash (/), listing all server certificates. This parameter allows (per its regex pattern) a string of characters consisting of either a forward slash (/) by itself or a string that must begin and end with forward slashes. In addition, it can contain any ASCII character from the ! (u0021) through the DEL character (u007F), including most punctuation characters, digits, and upper and lowercased letters. CLI Example: .. code-block:: bash salt myminion boto_iam.list_server_certificates path_prefix=/somepath/ ''' retries = 10 sleep = 6 conn = __utils__['boto3.get_connection']('iam', region=region, key=key, keyid=keyid, profile=profile) Items = [] while retries: try: log.debug('Garnering list of IAM Server Certificates') IsTruncated = True while IsTruncated: kwargs = {'PathPrefix': path_prefix} ret = conn.list_server_certificates(**kwargs) Items += ret.get('ServerCertificateMetadataList', []) IsTruncated = ret.get('IsTruncated') kwargs.update({'Marker': ret.get('Marker')}) return Items except botocore.exceptions.ParamValidationError as err: raise SaltInvocationError(str(err)) except botocore.exceptions.ClientError as err: if retries and jmespath.search('Error.Code', err.response) == 'Throttling': retries -= 1 log.debug('Throttled by AWS API, retrying in %s seconds...', sleep) time.sleep(sleep) continue log.error('Failed to list IAM Server Certificates: %s', err.message) return None def get_server_certificate(cert_name, region=None, key=None, keyid=None, profile=None): ''' Returns certificate information from Amazon .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_server_certificate mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_server_certificate(cert_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get certificate %s information.', cert_name) return False def delete_server_cert(cert_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a certificate from Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_server_cert mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_server_cert(cert_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete certificate %s.', cert_name) return False def export_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM user details. Produces results that can be used to create an sls file. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.export_users --out=txt | sed "s/local: //" > iam_users.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() users = get_all_users(path_prefix, region, key, keyid, profile) for user in users: name = user.user_name _policies = conn.get_all_user_policies(name, max_items=100) _policies = _policies.list_user_policies_response.list_user_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_user_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_user_policy_response.get_user_policy_result.policy_document )) policies[policy_name] = _policy user_sls = [] user_sls.append({"name": name}) user_sls.append({"policies": policies}) user_sls.append({"path": user.path}) results["manage user " + name] = {"boto_iam.user_present": user_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def export_roles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM role details. Produces results that can be used to create an sls file. CLI Example: salt-call boto_iam.export_roles --out=txt | sed "s/local: //" > iam_roles.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() roles = get_all_roles(path_prefix, region, key, keyid, profile) for role in roles: name = role.role_name _policies = conn.list_role_policies(name, max_items=100) _policies = _policies.list_role_policies_response.list_role_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_role_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_role_policy_response.get_role_policy_result.policy_document )) policies[policy_name] = _policy role_sls = [] role_sls.append({"name": name}) role_sls.append({"policies": policies}) role_sls.append({'policy_document': salt.utils.json.loads(_unquote(role.assume_role_policy_document))}) role_sls.append({"path": role.path}) results["manage role " + name] = {"boto_iam_role.present": role_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def _get_policy_arn(name, region=None, key=None, keyid=None, profile=None): if name.startswith('arn:aws:iam:'): return name account_id = get_account_id( region=region, key=key, keyid=keyid, profile=profile ) return 'arn:aws:iam::{0}:policy/{1}'.format(account_id, name) def policy_exists(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return True except boto.exception.BotoServerError: return False def get_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return ret.get('get_policy_response', {}).get('get_policy_result', {}) except boto.exception.BotoServerError: return None def create_policy(policy_name, policy_document, path=None, description=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in 'path', 'description': if locals()[arg] is not None: params[arg] = locals()[arg] if policy_exists(policy_name, region, key, keyid, profile): return True try: conn.create_policy(policy_name, policy_document, **params) log.info('Created IAM policy %s.', policy_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s.', policy_name) return False return True def delete_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_exists(policy_arn, region, key, keyid, profile): return True try: conn.delete_policy(policy_arn) log.info('Deleted %s policy.', policy_name) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete %s policy: %s.', policy_name, aws.get('message')) return False return True def list_policies(region=None, key=None, keyid=None, profile=None): ''' List policies. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policies ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: policies = [] for ret in __utils__['boto.paged_call'](conn.list_policies): policies.append(ret.get('list_policies_response', {}).get('list_policies_result', {}).get('policies')) return policies except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to list policy versions.' log.error(msg) return [] def policy_version_exists(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.get_policy_version(policy_arn, version_id) return True except boto.exception.BotoServerError: return False def get_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy_version(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile), version_id) retval = ret.get('get_policy_version_response', {}).get('get_policy_version_result', {}).get('policy_version', {}) retval['document'] = _unquote(retval.get('document')) return {'policy_version': retval} except boto.exception.BotoServerError: return None def create_policy_version(policy_name, policy_document, set_as_default=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy version. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy_version mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in ('set_as_default',): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.create_policy_version(policy_arn, policy_document, **params) vid = ret.get('create_policy_version_response', {}).get('create_policy_version_result', {}).get('policy_version', {}).get('version_id') log.info('Created IAM policy %s version %s.', policy_name, vid) return {'created': True, 'version_id': vid} except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s version %s.', policy_name, vid) return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Delete a policy version. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_version_exists(policy_arn, version_id, region, key, keyid, profile): return True try: conn.delete_policy_version(policy_arn, version_id) log.info('Deleted IAM policy %s version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete IAM policy %s version %s: %s', policy_name, version_id, aws.get('message')) return False return True def list_policy_versions(policy_name, region=None, key=None, keyid=None, profile=None): ''' List versions of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policy_versions mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.list_policy_versions(policy_arn) return ret.get('list_policy_versions_response', {}).get('list_policy_versions_result', {}).get('versions') except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list versions for IAM policy %s.', policy_name) return [] def set_default_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Set the default version of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.set_default_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.set_default_policy_version(policy_arn, version_id) log.info('Set %s policy to version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to set %s policy to version %s: %s', policy_name, version_id, aws.get('message')) return False return True def attach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_user_policy(policy_arn, user_name) log.info('Attached policy %s to IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach %s policy to IAM user %s.', policy_name, user_name) return False return True def detach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_user_policy(policy_arn, user_name) log.info('Detached %s policy from IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach %s policy from IAM user %s.', policy_name, user_name) return False return True def attach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_group_policy(policy_arn, group_name) log.info('Attached policy %s to IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM group %s.', policy_name, group_name) return False return True def detach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_group_policy(policy_arn, group_name) log.info('Detached policy %s from IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM group %s.', policy_name, group_name) return False return True def attach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_role_policy(policy_arn, role_name) log.info('Attached policy %s to IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM role %s.', policy_name, role_name) return False return True def detach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_role_policy(policy_arn, role_name) log.info('Detached policy %s from IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM role %s.', policy_name, role_name) return False return True def list_entities_for_policy(policy_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities that a policy is attached to. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 params = {} for arg in ('path_prefix', 'entity_filter'): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) while retries: try: allret = { 'policy_groups': [], 'policy_users': [], 'policy_roles': [], } for ret in __utils__['boto.paged_call'](conn.list_entities_for_policy, policy_arn=policy_arn, **params): for k, v in six.iteritems(allret): v.extend(ret.get('list_entities_for_policy_response', {}).get('list_entities_for_policy_result', {}).get(k)) return allret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('Failed to list entities for IAM policy %s: %s', policy_name, e.message) return {} return {} def list_attached_user_policies(user_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given user. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'UserName': user_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedUserPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_user_policies_response', {}).get('list_attached_user_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM user %s.', user_name) return [] def list_attached_group_policies(group_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given group. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'GroupName': group_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedGroupPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_group_policies_response', {}).get('list_attached_group_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM group %s.', group_name) return [] def list_attached_role_policies(role_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'RoleName': role_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedRolePolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_role_policies_response', {}).get('list_attached_role_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM role %s.', role_name) return [] def create_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Create SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.create_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_saml_provider(saml_metadata_document, name) log.info('Successfully created %s SAML provider.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to create SAML provider %s.', name) return False def get_saml_provider_arn(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider_arn my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_saml_providers() for saml_provider in response.list_saml_providers_response.list_saml_providers_result.saml_provider_list: if saml_provider['arn'].endswith(':saml-provider/' + name): return saml_provider['arn'] return False except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to get ARN of SAML provider %s.', name) return False def delete_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Delete SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.delete_saml_provider my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return True conn.delete_saml_provider(saml_provider_arn) log.info('Successfully deleted SAML provider %s.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete SAML provider %s.', name) return False def list_saml_providers(region=None, key=None, keyid=None, profile=None): ''' List SAML providers. CLI Example: .. code-block:: bash salt myminion boto_iam.list_saml_providers ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: providers = [] info = conn.list_saml_providers() for arn in info['list_saml_providers_response']['list_saml_providers_result']['saml_provider_list']: providers.append(arn['arn'].rsplit('/', 1)[1]) return providers except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get list of SAML providers.') return False def get_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider document. CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider arn ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: provider = conn.get_saml_provider(name) return provider['get_saml_provider_response']['get_saml_provider_result']['saml_metadata_document'] except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get SAML provider document %s.', name) return False def update_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Update SAML provider. CLI Example: .. code-block:: bash salt myminion boto_iam.update_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return False if conn.update_saml_provider(name, saml_metadata_document): return True return False except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to update SAML provider %s.', name) return False
saltstack/salt
salt/modules/boto_iam.py
update_assume_role_policy
python
def update_assume_role_policy(role_name, policy_document, region=None, key=None, keyid=None, profile=None): ''' Update an assume role policy for a role. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_assume_role_policy myrole '{"Statement":"..."}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(policy_document, six.string_types): policy_document = salt.utils.json.loads(policy_document, object_pairs_hook=odict.OrderedDict) try: _policy_document = salt.utils.json.dumps(policy_document) conn.update_assume_role_policy(role_name, _policy_document) log.info('Successfully updated assume role policy for IAM role %s.', role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to update assume role policy for IAM role %s.', role_name) return False
Update an assume role policy for a role. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_assume_role_policy myrole '{"Statement":"..."}'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iam.py#L1213-L1239
[ "def loads(s, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.loads and prevents a traceback in the event that a bytestring is\n passed to the function. (Python < 3.6 cannot load bytestrings)\n\n You can pass an alternate json module (loaded via import_json() above)\n using the _json_module argument)\n '''\n json_module = kwargs.pop('_json_module', json)\n try:\n return json_module.loads(s, **kwargs)\n except TypeError as exc:\n # json.loads cannot load bytestrings in Python < 3.6\n if six.PY3 and isinstance(s, bytes):\n return json_module.loads(salt.utils.stringutils.to_unicode(s), **kwargs)\n else:\n raise exc\n", "def dumps(obj, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.dumps, and assumes that ensure_ascii is False (unless explicitly\n passed as True) for unicode compatibility. Note that setting it to True\n will mess up any unicode characters, as they will be dumped as the string\n literal version of the unicode code point.\n\n On Python 2, encodes the result to a str since json.dumps does not want\n unicode types.\n\n You can pass an alternate json module (loaded via import_json() above)\n using the _json_module argument)\n '''\n json_module = kwargs.pop('_json_module', json)\n orig_enc_func = kwargs.pop('default', lambda x: x)\n\n def _enc_func(obj):\n obj = ThreadLocalProxy.unproxy(obj)\n return orig_enc_func(obj)\n\n if 'ensure_ascii' not in kwargs:\n kwargs['ensure_ascii'] = False\n if six.PY2:\n obj = salt.utils.data.encode(obj)\n return json_module.dumps(obj, default=_enc_func, **kwargs) # future lint: blacklisted-function\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon IAM .. versionadded:: 2014.7.0 :configuration: This module accepts explicit iam 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 iam.keyid: GKTADJGHEIQSXMKKRBJ08H iam.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs iam.region: 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: boto ''' # keep lint from choking on _get_conn and _cache_id #pylint: disable=E0602 # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import salt libs from salt.ext import six import salt.utils.compat import salt.utils.json import salt.utils.odict as odict import salt.utils.versions from salt.exceptions import SaltInvocationError # Import third party libs # pylint: disable=unused-import from salt.ext.six.moves.urllib.parse import unquote as _unquote # pylint: disable=no-name-in-module try: import boto import boto.iam import boto3 import botocore logging.getLogger('boto').setLevel(logging.CRITICAL) logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=unused-import log = logging.getLogger(__name__) def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'iam', pack=__salt__) def instance_profile_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an instance profile exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: # Boto weirdly returns an exception here if an instance profile doesn't # exist. conn.get_instance_profile(name) return True except boto.exception.BotoServerError: return False def create_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Create an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.create_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if instance_profile_exists(name, region, key, keyid, profile): return True try: # This call returns an instance profile if successful and an exception # if not. It's annoying. conn.create_instance_profile(name) log.info('Created %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create %s instance profile.', name) return False return True def delete_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Delete an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not instance_profile_exists(name, region, key, keyid, profile): return True try: conn.delete_instance_profile(name) log.info('Deleted %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s instance profile.', name) return False return True def role_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an IAM role exists. CLI Example: .. code-block:: bash salt myminion boto_iam.role_exists myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_role(name) return True except boto.exception.BotoServerError: return False def describe_role(name, region=None, key=None, keyid=None, profile=None): ''' Get information for a role. CLI Example: .. code-block:: bash salt myminion boto_iam.describe_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_role(name) if not info: return False role = info.get_role_response.get_role_result.role role['assume_role_policy_document'] = salt.utils.json.loads(_unquote( role.assume_role_policy_document )) # If Sid wasn't defined by the user, boto will still return a Sid in # each policy. To properly check idempotently, let's remove the Sid # from the return if it's not actually set. for policy_key, policy in role['assume_role_policy_document'].items(): if policy_key == 'Statement': for val in policy: if 'Sid' in val and not val['Sid']: del val['Sid'] return role except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get %s information.', name) return False def create_user(user_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_user myuser ''' if not path: path = '/' if get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_user(user_name, path) log.info('Created IAM user : %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM user %s.', user_name) return False def get_all_access_keys(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all access keys from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_access_keys myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.get_all_access_keys(user_name, marker, max_items) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get access keys for IAM user %s.', user_name) return six.text_type(e) def create_access_key(user_name, region=None, key=None, keyid=None, profile=None): ''' Create access key id for a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.create_access_key(user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create access key.') return six.text_type(e) def delete_access_key(access_key_id, user_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete access key id from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_access_key(access_key_id, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete access key id %s.', access_key_id) return six.text_type(e) def delete_user(user_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user myuser ''' if not get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.delete_user(user_name) log.info('Deleted IAM user : %s .', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM user %s', user_name) return six.text_type(e) def get_user(user_name=None, region=None, key=None, keyid=None, profile=None): ''' Get user information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user(user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM user %s info.', user_name) return False def create_group(group_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_group group ''' if not path: path = '/' if get_group(group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_group(group_name, path) log.info('Created IAM group : %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM group %s.', group_name) return False def get_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group(group_name, max_items=1) if not info: return False return info['get_group_response']['get_group_result']['group'] except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_group_members(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: marker = None truncated = True users = [] while truncated: info = conn.get_group(group_name, marker=marker, max_items=1000) if not info: return False truncated = bool(info['get_group_response']['get_group_result']['is_truncated']) if truncated and 'marker' in info['get_group_response']['get_group_result']: marker = info['get_group_response']['get_group_result']['marker'] else: marker = None truncated = False users += info['get_group_response']['get_group_result']['users'] return users except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get members for IAM group %s.', group_name) return False def add_user_to_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Add user to group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.add_user_to_group myuser mygroup ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('Username : %s does not exist.', user_name) return False if user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.add_user_to_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add IAM user %s to group %s.', user_name, group_name) return False def user_exists_in_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Check if user exists in group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.user_exists_in_group myuser mygroup ''' # TODO this should probably use boto.iam.get_groups_for_user users = get_group_members( group_name=group_name, region=region, key=key, keyid=keyid, profile=profile ) if users: for _user in users: if user_name == _user['user_name']: log.debug('IAM user %s is already in IAM group %s.', user_name, group_name) return True return False def remove_user_from_group(group_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Remove user from group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.remove_user_from_group mygroup myuser ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist.', user_name) return False if not user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.remove_user_from_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove IAM user %s from group %s', user_name, group_name) return False def put_group_policy(group_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_group_policy mygroup policyname policyrules ''' group = get_group(group_name, region=region, key=key, keyid=keyid, profile=profile) if not group: log.error('Group %s does not exist', group_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_group_policy(group_name, policy_name, policy_json) if created: log.info('Created policy for IAM group %s.', group_name) return True log.error('Could not create policy for IAM group %s', group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy for IAM group %s', group_name) return False def delete_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group_policy mygroup mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_group_policy( group_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_group_policy(group_name, policy_name) log.info('Successfully deleted policy %s for IAM group %s.', policy_name, group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM group %s.', policy_name, group_name) return False def get_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group_policy mygroup policyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group_policy(group_name, policy_name) log.debug('info for group policy is : %s', info) if not info: return False info = info.get_group_policy_response.get_group_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_all_groups(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM group details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_groups ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _groups = conn.get_all_groups(path_prefix=path_prefix) groups = _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) while marker: _groups = conn.get_all_groups(path_prefix=path_prefix, marker=marker) groups = groups + _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) return groups def get_all_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.get_all_instance_profiles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) marker = False profiles = [] while marker is not None: marker = marker if marker else None p = conn.list_instance_profiles(path_prefix=path_prefix, marker=marker) res = p.list_instance_profiles_response.list_instance_profiles_result profiles += res.instance_profiles marker = getattr(res, 'marker', None) return profiles def list_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' List all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.list_instance_profiles ''' p = get_all_instance_profiles(path_prefix, region, key, keyid, profile) return [i['instance_profile_name'] for i in p] def get_all_group_policies(group_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a group. CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_group_policies mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False try: response = conn.get_all_group_policies(group_name) _list = response.list_group_policies_response.list_group_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def delete_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _group = get_group( group_name, region, key, keyid, profile ) if not _group: return True try: conn.delete_group(group_name) log.info('Successfully deleted IAM group %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM group %s.', group_name) return False def create_login_profile(user_name, password, region=None, key=None, keyid=None, profile=None): ''' Creates a login profile for the specified user, give the user the ability to access AWS services and the AWS Management Console. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_login_profile user_name password ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.create_login_profile(user_name, password) log.info('Created profile for IAM user %s.', user_name) return info except boto.exception.BotoServerError as e: log.debug(e) if 'Conflict' in e: log.info('Profile already exists for IAM user %s.', user_name) return 'Conflict' log.error('Failed to update profile for IAM user %s.', user_name) return False def delete_login_profile(user_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a login profile for the specified user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_login_profile user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.delete_login_profile(user_name) log.info('Deleted login profile for IAM user %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Login profile already deleted for IAM user %s.', user_name) return True log.error('Failed to delete login profile for IAM user %s.', user_name) return False def get_all_mfa_devices(user_name, region=None, key=None, keyid=None, profile=None): ''' Get all MFA devices associated with an IAM user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_mfa_devices user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: result = conn.get_all_mfa_devices(user_name) devices = result['list_mfa_devices_response']['list_mfa_devices_result']['mfa_devices'] return devices except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Could not find IAM user %s.', user_name) return [] log.error('Failed to get all MFA devices for IAM user %s.', user_name) return False def deactivate_mfa_device(user_name, serial, region=None, key=None, keyid=None, profile=None): ''' Deactivates the specified MFA device and removes it from association with the user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.deactivate_mfa_device user_name serial_num ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.deactivate_mfa_device(user_name, serial) log.info('Deactivated MFA device %s for IAM user %s.', serial, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('MFA device %s not associated with IAM user %s.', serial, user_name) return True log.error('Failed to deactivate MFA device %s for IAM user %s.', serial, user_name) return False def delete_virtual_mfa_device(serial, region=None, key=None, keyid=None, profile=None): ''' Deletes the specified virtual MFA device. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_virtual_mfa_device serial_num ''' conn = __utils__['boto3.get_connection_func']('iam')() try: conn.delete_virtual_mfa_device(SerialNumber=serial) log.info('Deleted virtual MFA device %s.', serial) return True except botocore.exceptions.ClientError as e: log.debug(e) if 'NoSuchEntity' in six.text_type(e): log.info('Virtual MFA device %s not found.', serial) return True log.error('Failed to delete virtual MFA device %s.', serial) return False def update_account_password_policy(allow_users_to_change_password=None, hard_expiry=None, max_password_age=None, minimum_password_length=None, password_reuse_prevention=None, require_lowercase_characters=None, require_numbers=None, require_symbols=None, require_uppercase_characters=None, region=None, key=None, keyid=None, profile=None): ''' Update the password policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_account_password_policy True ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.update_account_password_policy(allow_users_to_change_password, hard_expiry, max_password_age, minimum_password_length, password_reuse_prevention, require_lowercase_characters, require_numbers, require_symbols, require_uppercase_characters) log.info('The password policy has been updated.') return True except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy' log.error(msg) return False def get_account_policy(region=None, key=None, keyid=None, profile=None): ''' Get account policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_account_password_policy() return info.get_account_password_policy_response.get_account_password_policy_result.password_policy except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy.' log.error(msg) return False def create_role(name, policy_document=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Create an instance role. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if role_exists(name, region, key, keyid, profile): return True if not policy_document: policy_document = None try: conn.create_role(name, assume_role_policy_document=policy_document, path=path) log.info('Created IAM role %s.', name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to create IAM role %s.', name) return False def delete_role(name, region=None, key=None, keyid=None, profile=None): ''' Delete an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(name, region, key, keyid, profile): return True try: conn.delete_role(name) log.info('Deleted %s IAM role.', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s IAM role.', name) return False def profile_associated(role_name, profile_name, region, key, keyid, profile): ''' Check to see if an instance profile is associated with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.profile_associated myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # The IAM module of boto doesn't return objects. Instead you need to grab # values through its properties. Sigh. try: profiles = conn.list_instance_profiles_for_role(role_name) except boto.exception.BotoServerError as e: log.debug(e) return False profiles = profiles.list_instance_profiles_for_role_response profiles = profiles.list_instance_profiles_for_role_result profiles = profiles.instance_profiles for profile in profiles: if profile.instance_profile_name == profile_name: return True return False def associate_profile_to_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Associate an instance profile with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.associate_profile_to_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if associated: return True else: try: conn.add_role_to_instance_profile(profile_name, role_name) log.info('Added %s instance profile to IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add %s instance profile to IAM role %s', profile_name, role_name) return False def disassociate_profile_from_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Disassociate an instance profile from an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.disassociate_profile_from_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if not associated: return True else: try: conn.remove_role_from_instance_profile(profile_name, role_name) log.info('Removed %s instance profile from IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove %s instance profile from IAM role %s.', profile_name, role_name) return False def list_role_policies(role_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_role_policies myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_role_policies(role_name) _list = response.list_role_policies_response.list_role_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def get_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.get_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: _policy = conn.get_role_policy(role_name, policy_name) # I _hate_ you for not giving me an object boto. _policy = _policy.get_role_policy_response.policy_document # Policy is url encoded _policy = _unquote(_policy) _policy = salt.utils.json.loads(_policy, object_pairs_hook=odict.OrderedDict) return _policy except boto.exception.BotoServerError: return {} def create_role_policy(role_name, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Create or modify a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role_policy myirole mypolicy '{"MyPolicy": "Statement": [{"Action": ["sqs:*"], "Effect": "Allow", "Resource": ["arn:aws:sqs:*:*:*"], "Sid": "MyPolicySqs1"}]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) mode = 'create' if _policy: if _policy == policy: return True mode = 'modify' if isinstance(policy, six.string_types): policy = salt.utils.json.loads(policy, object_pairs_hook=odict.OrderedDict) try: _policy = salt.utils.json.dumps(policy) conn.put_role_policy(role_name, policy_name, _policy) if mode == 'create': msg = 'Successfully added policy %s to IAM role %s.' else: msg = 'Successfully modified policy %s for IAM role %s.' log.info(msg, policy_name, role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to %s policy %s for IAM role %s.', mode, policy_name, role_name) return False def delete_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) if not _policy: return True try: conn.delete_role_policy(role_name, policy_name) log.info('Successfully deleted policy %s for IAM role %s.', policy_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM role %s.', policy_name, role_name) return False def build_policy(region=None, key=None, keyid=None, profile=None): ''' Build a default assume role policy. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.build_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if hasattr(conn, 'build_policy'): policy = salt.utils.json.loads(conn.build_policy()) elif hasattr(conn, '_build_policy'): policy = salt.utils.json.loads(conn._build_policy()) else: return {} # The format we get from build_policy isn't going to be what we get back # from AWS for the exact same policy. AWS converts single item list values # into strings, so let's do the same here. for key, policy_val in policy.items(): for statement in policy_val: if (isinstance(statement['Action'], list) and len(statement['Action']) == 1): statement['Action'] = statement['Action'][0] if (isinstance(statement['Principal']['Service'], list) and len(statement['Principal']['Service']) == 1): statement['Principal']['Service'] = statement['Principal']['Service'][0] # build_policy doesn't add a version field, which AWS is going to set to a # default value, when we get it back, so let's set it. policy['Version'] = '2008-10-17' return policy def get_account_id(region=None, key=None, keyid=None, profile=None): ''' Get a the AWS account id associated with the used credentials. CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_id ''' cache_key = 'boto_iam.account_id' if cache_key not in __context__: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_user() # The get_user call returns an user ARN: # arn:aws:iam::027050522557:user/salt-test arn = ret['get_user_response']['get_user_result']['user']['arn'] account_id = arn.split(':')[4] except boto.exception.BotoServerError: # If call failed, then let's try to get the ARN from the metadata timeout = boto.config.getfloat( 'Boto', 'metadata_service_timeout', 1.0 ) attempts = boto.config.getint( 'Boto', 'metadata_service_num_attempts', 1 ) identity = boto.utils.get_instance_identity( timeout=timeout, num_retries=attempts ) try: account_id = identity['document']['accountId'] except KeyError: log.error('Failed to get account id from instance_identity in' ' boto_iam.get_account_id.') __context__[cache_key] = account_id return __context__[cache_key] def get_all_roles(path_prefix=None, region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM role details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_roles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _roles = conn.list_roles(path_prefix=path_prefix) roles = _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) while marker: _roles = conn.list_roles(path_prefix=path_prefix, marker=marker) roles = roles + _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) return roles def get_all_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM user details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_users ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _users = conn.get_all_users(path_prefix=path_prefix) users = _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) while marker: _users = conn.get_all_users(path_prefix=path_prefix, marker=marker) users = users + _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) return users def get_all_user_policies(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all user policies. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_user_policies myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_all_user_policies(user_name, marker, max_items) if not info: return False _list = info.list_user_policies_response.list_user_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policies for user %s.', user_name) return False def get_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user_policy myuser mypolicyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user_policy(user_name, policy_name) log.debug('Info for IAM user %s policy %s: %s.', user_name, policy_name, info) if not info: return False info = info.get_user_policy_response.get_user_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policy %s for IAM user %s.', policy_name, user_name) return False def put_user_policy(user_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_user_policy myuser policyname policyrules ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_user_policy(user_name, policy_name, policy_json) if created: log.info('Created policy %s for IAM user %s.', policy_name, user_name) return True log.error('Could not create policy %s for IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy %s for IAM user %s.', policy_name, user_name) return False def delete_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user_policy myuser mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_user_policy( user_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_user_policy(user_name, policy_name) log.info('Successfully deleted policy %s for IAM user %s.', policy_name, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM user %s.', policy_name, user_name) return False def upload_server_cert(cert_name, cert_body, private_key, cert_chain=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Upload a certificate to Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.upload_server_cert mycert_name crt priv_key :param cert_name: The name for the server certificate. Do not include the path in this value. :param cert_body: The contents of the public key certificate in PEM-encoded format. :param private_key: The contents of the private key in PEM-encoded format. :param cert_chain: The contents of the certificate chain. This is typically a concatenation of the PEM-encoded public key certificates of the chain. :param path: The path for the server certificate. :param region: The name of the region to connect to. :param key: The key to be used in order to connect :param keyid: The keyid to be used in order to connect :param profile: The profile that contains a dict of region, key, keyid :return: True / False ''' exists = get_server_certificate(cert_name, region, key, keyid, profile) if exists: return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.upload_server_cert(cert_name, cert_body, private_key, cert_chain) log.info('Created certificate %s.', cert_name) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to failed to create certificate %s.', cert_name) return False def list_server_certificates(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Lists the server certificates stored in IAM that have the specified path prefix. .. versionadded:: ??? :param path_prefix: The path prefix for filtering the results. For example: /company/servercerts would get all server certificates for which the path starts with /company/servercerts . This parameter is optional. If it is not included, it defaults to a slash (/), listing all server certificates. This parameter allows (per its regex pattern) a string of characters consisting of either a forward slash (/) by itself or a string that must begin and end with forward slashes. In addition, it can contain any ASCII character from the ! (u0021) through the DEL character (u007F), including most punctuation characters, digits, and upper and lowercased letters. CLI Example: .. code-block:: bash salt myminion boto_iam.list_server_certificates path_prefix=/somepath/ ''' retries = 10 sleep = 6 conn = __utils__['boto3.get_connection']('iam', region=region, key=key, keyid=keyid, profile=profile) Items = [] while retries: try: log.debug('Garnering list of IAM Server Certificates') IsTruncated = True while IsTruncated: kwargs = {'PathPrefix': path_prefix} ret = conn.list_server_certificates(**kwargs) Items += ret.get('ServerCertificateMetadataList', []) IsTruncated = ret.get('IsTruncated') kwargs.update({'Marker': ret.get('Marker')}) return Items except botocore.exceptions.ParamValidationError as err: raise SaltInvocationError(str(err)) except botocore.exceptions.ClientError as err: if retries and jmespath.search('Error.Code', err.response) == 'Throttling': retries -= 1 log.debug('Throttled by AWS API, retrying in %s seconds...', sleep) time.sleep(sleep) continue log.error('Failed to list IAM Server Certificates: %s', err.message) return None def get_server_certificate(cert_name, region=None, key=None, keyid=None, profile=None): ''' Returns certificate information from Amazon .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_server_certificate mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_server_certificate(cert_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get certificate %s information.', cert_name) return False def delete_server_cert(cert_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a certificate from Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_server_cert mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_server_cert(cert_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete certificate %s.', cert_name) return False def export_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM user details. Produces results that can be used to create an sls file. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.export_users --out=txt | sed "s/local: //" > iam_users.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() users = get_all_users(path_prefix, region, key, keyid, profile) for user in users: name = user.user_name _policies = conn.get_all_user_policies(name, max_items=100) _policies = _policies.list_user_policies_response.list_user_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_user_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_user_policy_response.get_user_policy_result.policy_document )) policies[policy_name] = _policy user_sls = [] user_sls.append({"name": name}) user_sls.append({"policies": policies}) user_sls.append({"path": user.path}) results["manage user " + name] = {"boto_iam.user_present": user_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def export_roles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM role details. Produces results that can be used to create an sls file. CLI Example: salt-call boto_iam.export_roles --out=txt | sed "s/local: //" > iam_roles.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() roles = get_all_roles(path_prefix, region, key, keyid, profile) for role in roles: name = role.role_name _policies = conn.list_role_policies(name, max_items=100) _policies = _policies.list_role_policies_response.list_role_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_role_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_role_policy_response.get_role_policy_result.policy_document )) policies[policy_name] = _policy role_sls = [] role_sls.append({"name": name}) role_sls.append({"policies": policies}) role_sls.append({'policy_document': salt.utils.json.loads(_unquote(role.assume_role_policy_document))}) role_sls.append({"path": role.path}) results["manage role " + name] = {"boto_iam_role.present": role_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def _get_policy_arn(name, region=None, key=None, keyid=None, profile=None): if name.startswith('arn:aws:iam:'): return name account_id = get_account_id( region=region, key=key, keyid=keyid, profile=profile ) return 'arn:aws:iam::{0}:policy/{1}'.format(account_id, name) def policy_exists(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return True except boto.exception.BotoServerError: return False def get_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return ret.get('get_policy_response', {}).get('get_policy_result', {}) except boto.exception.BotoServerError: return None def create_policy(policy_name, policy_document, path=None, description=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in 'path', 'description': if locals()[arg] is not None: params[arg] = locals()[arg] if policy_exists(policy_name, region, key, keyid, profile): return True try: conn.create_policy(policy_name, policy_document, **params) log.info('Created IAM policy %s.', policy_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s.', policy_name) return False return True def delete_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_exists(policy_arn, region, key, keyid, profile): return True try: conn.delete_policy(policy_arn) log.info('Deleted %s policy.', policy_name) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete %s policy: %s.', policy_name, aws.get('message')) return False return True def list_policies(region=None, key=None, keyid=None, profile=None): ''' List policies. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policies ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: policies = [] for ret in __utils__['boto.paged_call'](conn.list_policies): policies.append(ret.get('list_policies_response', {}).get('list_policies_result', {}).get('policies')) return policies except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to list policy versions.' log.error(msg) return [] def policy_version_exists(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.get_policy_version(policy_arn, version_id) return True except boto.exception.BotoServerError: return False def get_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy_version(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile), version_id) retval = ret.get('get_policy_version_response', {}).get('get_policy_version_result', {}).get('policy_version', {}) retval['document'] = _unquote(retval.get('document')) return {'policy_version': retval} except boto.exception.BotoServerError: return None def create_policy_version(policy_name, policy_document, set_as_default=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy version. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy_version mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in ('set_as_default',): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.create_policy_version(policy_arn, policy_document, **params) vid = ret.get('create_policy_version_response', {}).get('create_policy_version_result', {}).get('policy_version', {}).get('version_id') log.info('Created IAM policy %s version %s.', policy_name, vid) return {'created': True, 'version_id': vid} except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s version %s.', policy_name, vid) return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Delete a policy version. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_version_exists(policy_arn, version_id, region, key, keyid, profile): return True try: conn.delete_policy_version(policy_arn, version_id) log.info('Deleted IAM policy %s version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete IAM policy %s version %s: %s', policy_name, version_id, aws.get('message')) return False return True def list_policy_versions(policy_name, region=None, key=None, keyid=None, profile=None): ''' List versions of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policy_versions mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.list_policy_versions(policy_arn) return ret.get('list_policy_versions_response', {}).get('list_policy_versions_result', {}).get('versions') except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list versions for IAM policy %s.', policy_name) return [] def set_default_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Set the default version of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.set_default_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.set_default_policy_version(policy_arn, version_id) log.info('Set %s policy to version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to set %s policy to version %s: %s', policy_name, version_id, aws.get('message')) return False return True def attach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_user_policy(policy_arn, user_name) log.info('Attached policy %s to IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach %s policy to IAM user %s.', policy_name, user_name) return False return True def detach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_user_policy(policy_arn, user_name) log.info('Detached %s policy from IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach %s policy from IAM user %s.', policy_name, user_name) return False return True def attach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_group_policy(policy_arn, group_name) log.info('Attached policy %s to IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM group %s.', policy_name, group_name) return False return True def detach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_group_policy(policy_arn, group_name) log.info('Detached policy %s from IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM group %s.', policy_name, group_name) return False return True def attach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_role_policy(policy_arn, role_name) log.info('Attached policy %s to IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM role %s.', policy_name, role_name) return False return True def detach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_role_policy(policy_arn, role_name) log.info('Detached policy %s from IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM role %s.', policy_name, role_name) return False return True def list_entities_for_policy(policy_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities that a policy is attached to. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 params = {} for arg in ('path_prefix', 'entity_filter'): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) while retries: try: allret = { 'policy_groups': [], 'policy_users': [], 'policy_roles': [], } for ret in __utils__['boto.paged_call'](conn.list_entities_for_policy, policy_arn=policy_arn, **params): for k, v in six.iteritems(allret): v.extend(ret.get('list_entities_for_policy_response', {}).get('list_entities_for_policy_result', {}).get(k)) return allret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('Failed to list entities for IAM policy %s: %s', policy_name, e.message) return {} return {} def list_attached_user_policies(user_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given user. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'UserName': user_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedUserPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_user_policies_response', {}).get('list_attached_user_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM user %s.', user_name) return [] def list_attached_group_policies(group_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given group. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'GroupName': group_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedGroupPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_group_policies_response', {}).get('list_attached_group_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM group %s.', group_name) return [] def list_attached_role_policies(role_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'RoleName': role_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedRolePolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_role_policies_response', {}).get('list_attached_role_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM role %s.', role_name) return [] def create_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Create SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.create_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_saml_provider(saml_metadata_document, name) log.info('Successfully created %s SAML provider.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to create SAML provider %s.', name) return False def get_saml_provider_arn(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider_arn my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_saml_providers() for saml_provider in response.list_saml_providers_response.list_saml_providers_result.saml_provider_list: if saml_provider['arn'].endswith(':saml-provider/' + name): return saml_provider['arn'] return False except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to get ARN of SAML provider %s.', name) return False def delete_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Delete SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.delete_saml_provider my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return True conn.delete_saml_provider(saml_provider_arn) log.info('Successfully deleted SAML provider %s.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete SAML provider %s.', name) return False def list_saml_providers(region=None, key=None, keyid=None, profile=None): ''' List SAML providers. CLI Example: .. code-block:: bash salt myminion boto_iam.list_saml_providers ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: providers = [] info = conn.list_saml_providers() for arn in info['list_saml_providers_response']['list_saml_providers_result']['saml_provider_list']: providers.append(arn['arn'].rsplit('/', 1)[1]) return providers except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get list of SAML providers.') return False def get_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider document. CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider arn ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: provider = conn.get_saml_provider(name) return provider['get_saml_provider_response']['get_saml_provider_result']['saml_metadata_document'] except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get SAML provider document %s.', name) return False def update_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Update SAML provider. CLI Example: .. code-block:: bash salt myminion boto_iam.update_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return False if conn.update_saml_provider(name, saml_metadata_document): return True return False except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to update SAML provider %s.', name) return False
saltstack/salt
salt/modules/boto_iam.py
build_policy
python
def build_policy(region=None, key=None, keyid=None, profile=None): ''' Build a default assume role policy. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.build_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if hasattr(conn, 'build_policy'): policy = salt.utils.json.loads(conn.build_policy()) elif hasattr(conn, '_build_policy'): policy = salt.utils.json.loads(conn._build_policy()) else: return {} # The format we get from build_policy isn't going to be what we get back # from AWS for the exact same policy. AWS converts single item list values # into strings, so let's do the same here. for key, policy_val in policy.items(): for statement in policy_val: if (isinstance(statement['Action'], list) and len(statement['Action']) == 1): statement['Action'] = statement['Action'][0] if (isinstance(statement['Principal']['Service'], list) and len(statement['Principal']['Service']) == 1): statement['Principal']['Service'] = statement['Principal']['Service'][0] # build_policy doesn't add a version field, which AWS is going to set to a # default value, when we get it back, so let's set it. policy['Version'] = '2008-10-17' return policy
Build a default assume role policy. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.build_policy
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iam.py#L1242-L1275
[ "def loads(s, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.loads and prevents a traceback in the event that a bytestring is\n passed to the function. (Python < 3.6 cannot load bytestrings)\n\n You can pass an alternate json module (loaded via import_json() above)\n using the _json_module argument)\n '''\n json_module = kwargs.pop('_json_module', json)\n try:\n return json_module.loads(s, **kwargs)\n except TypeError as exc:\n # json.loads cannot load bytestrings in Python < 3.6\n if six.PY3 and isinstance(s, bytes):\n return json_module.loads(salt.utils.stringutils.to_unicode(s), **kwargs)\n else:\n raise exc\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon IAM .. versionadded:: 2014.7.0 :configuration: This module accepts explicit iam 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 iam.keyid: GKTADJGHEIQSXMKKRBJ08H iam.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs iam.region: 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: boto ''' # keep lint from choking on _get_conn and _cache_id #pylint: disable=E0602 # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import salt libs from salt.ext import six import salt.utils.compat import salt.utils.json import salt.utils.odict as odict import salt.utils.versions from salt.exceptions import SaltInvocationError # Import third party libs # pylint: disable=unused-import from salt.ext.six.moves.urllib.parse import unquote as _unquote # pylint: disable=no-name-in-module try: import boto import boto.iam import boto3 import botocore logging.getLogger('boto').setLevel(logging.CRITICAL) logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=unused-import log = logging.getLogger(__name__) def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'iam', pack=__salt__) def instance_profile_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an instance profile exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: # Boto weirdly returns an exception here if an instance profile doesn't # exist. conn.get_instance_profile(name) return True except boto.exception.BotoServerError: return False def create_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Create an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.create_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if instance_profile_exists(name, region, key, keyid, profile): return True try: # This call returns an instance profile if successful and an exception # if not. It's annoying. conn.create_instance_profile(name) log.info('Created %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create %s instance profile.', name) return False return True def delete_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Delete an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not instance_profile_exists(name, region, key, keyid, profile): return True try: conn.delete_instance_profile(name) log.info('Deleted %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s instance profile.', name) return False return True def role_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an IAM role exists. CLI Example: .. code-block:: bash salt myminion boto_iam.role_exists myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_role(name) return True except boto.exception.BotoServerError: return False def describe_role(name, region=None, key=None, keyid=None, profile=None): ''' Get information for a role. CLI Example: .. code-block:: bash salt myminion boto_iam.describe_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_role(name) if not info: return False role = info.get_role_response.get_role_result.role role['assume_role_policy_document'] = salt.utils.json.loads(_unquote( role.assume_role_policy_document )) # If Sid wasn't defined by the user, boto will still return a Sid in # each policy. To properly check idempotently, let's remove the Sid # from the return if it's not actually set. for policy_key, policy in role['assume_role_policy_document'].items(): if policy_key == 'Statement': for val in policy: if 'Sid' in val and not val['Sid']: del val['Sid'] return role except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get %s information.', name) return False def create_user(user_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_user myuser ''' if not path: path = '/' if get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_user(user_name, path) log.info('Created IAM user : %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM user %s.', user_name) return False def get_all_access_keys(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all access keys from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_access_keys myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.get_all_access_keys(user_name, marker, max_items) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get access keys for IAM user %s.', user_name) return six.text_type(e) def create_access_key(user_name, region=None, key=None, keyid=None, profile=None): ''' Create access key id for a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.create_access_key(user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create access key.') return six.text_type(e) def delete_access_key(access_key_id, user_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete access key id from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_access_key(access_key_id, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete access key id %s.', access_key_id) return six.text_type(e) def delete_user(user_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user myuser ''' if not get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.delete_user(user_name) log.info('Deleted IAM user : %s .', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM user %s', user_name) return six.text_type(e) def get_user(user_name=None, region=None, key=None, keyid=None, profile=None): ''' Get user information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user(user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM user %s info.', user_name) return False def create_group(group_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_group group ''' if not path: path = '/' if get_group(group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_group(group_name, path) log.info('Created IAM group : %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM group %s.', group_name) return False def get_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group(group_name, max_items=1) if not info: return False return info['get_group_response']['get_group_result']['group'] except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_group_members(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: marker = None truncated = True users = [] while truncated: info = conn.get_group(group_name, marker=marker, max_items=1000) if not info: return False truncated = bool(info['get_group_response']['get_group_result']['is_truncated']) if truncated and 'marker' in info['get_group_response']['get_group_result']: marker = info['get_group_response']['get_group_result']['marker'] else: marker = None truncated = False users += info['get_group_response']['get_group_result']['users'] return users except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get members for IAM group %s.', group_name) return False def add_user_to_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Add user to group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.add_user_to_group myuser mygroup ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('Username : %s does not exist.', user_name) return False if user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.add_user_to_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add IAM user %s to group %s.', user_name, group_name) return False def user_exists_in_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Check if user exists in group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.user_exists_in_group myuser mygroup ''' # TODO this should probably use boto.iam.get_groups_for_user users = get_group_members( group_name=group_name, region=region, key=key, keyid=keyid, profile=profile ) if users: for _user in users: if user_name == _user['user_name']: log.debug('IAM user %s is already in IAM group %s.', user_name, group_name) return True return False def remove_user_from_group(group_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Remove user from group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.remove_user_from_group mygroup myuser ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist.', user_name) return False if not user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.remove_user_from_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove IAM user %s from group %s', user_name, group_name) return False def put_group_policy(group_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_group_policy mygroup policyname policyrules ''' group = get_group(group_name, region=region, key=key, keyid=keyid, profile=profile) if not group: log.error('Group %s does not exist', group_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_group_policy(group_name, policy_name, policy_json) if created: log.info('Created policy for IAM group %s.', group_name) return True log.error('Could not create policy for IAM group %s', group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy for IAM group %s', group_name) return False def delete_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group_policy mygroup mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_group_policy( group_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_group_policy(group_name, policy_name) log.info('Successfully deleted policy %s for IAM group %s.', policy_name, group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM group %s.', policy_name, group_name) return False def get_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group_policy mygroup policyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group_policy(group_name, policy_name) log.debug('info for group policy is : %s', info) if not info: return False info = info.get_group_policy_response.get_group_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_all_groups(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM group details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_groups ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _groups = conn.get_all_groups(path_prefix=path_prefix) groups = _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) while marker: _groups = conn.get_all_groups(path_prefix=path_prefix, marker=marker) groups = groups + _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) return groups def get_all_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.get_all_instance_profiles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) marker = False profiles = [] while marker is not None: marker = marker if marker else None p = conn.list_instance_profiles(path_prefix=path_prefix, marker=marker) res = p.list_instance_profiles_response.list_instance_profiles_result profiles += res.instance_profiles marker = getattr(res, 'marker', None) return profiles def list_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' List all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.list_instance_profiles ''' p = get_all_instance_profiles(path_prefix, region, key, keyid, profile) return [i['instance_profile_name'] for i in p] def get_all_group_policies(group_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a group. CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_group_policies mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False try: response = conn.get_all_group_policies(group_name) _list = response.list_group_policies_response.list_group_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def delete_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _group = get_group( group_name, region, key, keyid, profile ) if not _group: return True try: conn.delete_group(group_name) log.info('Successfully deleted IAM group %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM group %s.', group_name) return False def create_login_profile(user_name, password, region=None, key=None, keyid=None, profile=None): ''' Creates a login profile for the specified user, give the user the ability to access AWS services and the AWS Management Console. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_login_profile user_name password ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.create_login_profile(user_name, password) log.info('Created profile for IAM user %s.', user_name) return info except boto.exception.BotoServerError as e: log.debug(e) if 'Conflict' in e: log.info('Profile already exists for IAM user %s.', user_name) return 'Conflict' log.error('Failed to update profile for IAM user %s.', user_name) return False def delete_login_profile(user_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a login profile for the specified user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_login_profile user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.delete_login_profile(user_name) log.info('Deleted login profile for IAM user %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Login profile already deleted for IAM user %s.', user_name) return True log.error('Failed to delete login profile for IAM user %s.', user_name) return False def get_all_mfa_devices(user_name, region=None, key=None, keyid=None, profile=None): ''' Get all MFA devices associated with an IAM user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_mfa_devices user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: result = conn.get_all_mfa_devices(user_name) devices = result['list_mfa_devices_response']['list_mfa_devices_result']['mfa_devices'] return devices except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Could not find IAM user %s.', user_name) return [] log.error('Failed to get all MFA devices for IAM user %s.', user_name) return False def deactivate_mfa_device(user_name, serial, region=None, key=None, keyid=None, profile=None): ''' Deactivates the specified MFA device and removes it from association with the user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.deactivate_mfa_device user_name serial_num ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.deactivate_mfa_device(user_name, serial) log.info('Deactivated MFA device %s for IAM user %s.', serial, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('MFA device %s not associated with IAM user %s.', serial, user_name) return True log.error('Failed to deactivate MFA device %s for IAM user %s.', serial, user_name) return False def delete_virtual_mfa_device(serial, region=None, key=None, keyid=None, profile=None): ''' Deletes the specified virtual MFA device. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_virtual_mfa_device serial_num ''' conn = __utils__['boto3.get_connection_func']('iam')() try: conn.delete_virtual_mfa_device(SerialNumber=serial) log.info('Deleted virtual MFA device %s.', serial) return True except botocore.exceptions.ClientError as e: log.debug(e) if 'NoSuchEntity' in six.text_type(e): log.info('Virtual MFA device %s not found.', serial) return True log.error('Failed to delete virtual MFA device %s.', serial) return False def update_account_password_policy(allow_users_to_change_password=None, hard_expiry=None, max_password_age=None, minimum_password_length=None, password_reuse_prevention=None, require_lowercase_characters=None, require_numbers=None, require_symbols=None, require_uppercase_characters=None, region=None, key=None, keyid=None, profile=None): ''' Update the password policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_account_password_policy True ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.update_account_password_policy(allow_users_to_change_password, hard_expiry, max_password_age, minimum_password_length, password_reuse_prevention, require_lowercase_characters, require_numbers, require_symbols, require_uppercase_characters) log.info('The password policy has been updated.') return True except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy' log.error(msg) return False def get_account_policy(region=None, key=None, keyid=None, profile=None): ''' Get account policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_account_password_policy() return info.get_account_password_policy_response.get_account_password_policy_result.password_policy except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy.' log.error(msg) return False def create_role(name, policy_document=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Create an instance role. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if role_exists(name, region, key, keyid, profile): return True if not policy_document: policy_document = None try: conn.create_role(name, assume_role_policy_document=policy_document, path=path) log.info('Created IAM role %s.', name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to create IAM role %s.', name) return False def delete_role(name, region=None, key=None, keyid=None, profile=None): ''' Delete an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(name, region, key, keyid, profile): return True try: conn.delete_role(name) log.info('Deleted %s IAM role.', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s IAM role.', name) return False def profile_associated(role_name, profile_name, region, key, keyid, profile): ''' Check to see if an instance profile is associated with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.profile_associated myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # The IAM module of boto doesn't return objects. Instead you need to grab # values through its properties. Sigh. try: profiles = conn.list_instance_profiles_for_role(role_name) except boto.exception.BotoServerError as e: log.debug(e) return False profiles = profiles.list_instance_profiles_for_role_response profiles = profiles.list_instance_profiles_for_role_result profiles = profiles.instance_profiles for profile in profiles: if profile.instance_profile_name == profile_name: return True return False def associate_profile_to_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Associate an instance profile with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.associate_profile_to_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if associated: return True else: try: conn.add_role_to_instance_profile(profile_name, role_name) log.info('Added %s instance profile to IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add %s instance profile to IAM role %s', profile_name, role_name) return False def disassociate_profile_from_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Disassociate an instance profile from an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.disassociate_profile_from_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if not associated: return True else: try: conn.remove_role_from_instance_profile(profile_name, role_name) log.info('Removed %s instance profile from IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove %s instance profile from IAM role %s.', profile_name, role_name) return False def list_role_policies(role_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_role_policies myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_role_policies(role_name) _list = response.list_role_policies_response.list_role_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def get_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.get_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: _policy = conn.get_role_policy(role_name, policy_name) # I _hate_ you for not giving me an object boto. _policy = _policy.get_role_policy_response.policy_document # Policy is url encoded _policy = _unquote(_policy) _policy = salt.utils.json.loads(_policy, object_pairs_hook=odict.OrderedDict) return _policy except boto.exception.BotoServerError: return {} def create_role_policy(role_name, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Create or modify a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role_policy myirole mypolicy '{"MyPolicy": "Statement": [{"Action": ["sqs:*"], "Effect": "Allow", "Resource": ["arn:aws:sqs:*:*:*"], "Sid": "MyPolicySqs1"}]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) mode = 'create' if _policy: if _policy == policy: return True mode = 'modify' if isinstance(policy, six.string_types): policy = salt.utils.json.loads(policy, object_pairs_hook=odict.OrderedDict) try: _policy = salt.utils.json.dumps(policy) conn.put_role_policy(role_name, policy_name, _policy) if mode == 'create': msg = 'Successfully added policy %s to IAM role %s.' else: msg = 'Successfully modified policy %s for IAM role %s.' log.info(msg, policy_name, role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to %s policy %s for IAM role %s.', mode, policy_name, role_name) return False def delete_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) if not _policy: return True try: conn.delete_role_policy(role_name, policy_name) log.info('Successfully deleted policy %s for IAM role %s.', policy_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM role %s.', policy_name, role_name) return False def update_assume_role_policy(role_name, policy_document, region=None, key=None, keyid=None, profile=None): ''' Update an assume role policy for a role. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_assume_role_policy myrole '{"Statement":"..."}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(policy_document, six.string_types): policy_document = salt.utils.json.loads(policy_document, object_pairs_hook=odict.OrderedDict) try: _policy_document = salt.utils.json.dumps(policy_document) conn.update_assume_role_policy(role_name, _policy_document) log.info('Successfully updated assume role policy for IAM role %s.', role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to update assume role policy for IAM role %s.', role_name) return False def get_account_id(region=None, key=None, keyid=None, profile=None): ''' Get a the AWS account id associated with the used credentials. CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_id ''' cache_key = 'boto_iam.account_id' if cache_key not in __context__: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_user() # The get_user call returns an user ARN: # arn:aws:iam::027050522557:user/salt-test arn = ret['get_user_response']['get_user_result']['user']['arn'] account_id = arn.split(':')[4] except boto.exception.BotoServerError: # If call failed, then let's try to get the ARN from the metadata timeout = boto.config.getfloat( 'Boto', 'metadata_service_timeout', 1.0 ) attempts = boto.config.getint( 'Boto', 'metadata_service_num_attempts', 1 ) identity = boto.utils.get_instance_identity( timeout=timeout, num_retries=attempts ) try: account_id = identity['document']['accountId'] except KeyError: log.error('Failed to get account id from instance_identity in' ' boto_iam.get_account_id.') __context__[cache_key] = account_id return __context__[cache_key] def get_all_roles(path_prefix=None, region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM role details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_roles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _roles = conn.list_roles(path_prefix=path_prefix) roles = _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) while marker: _roles = conn.list_roles(path_prefix=path_prefix, marker=marker) roles = roles + _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) return roles def get_all_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM user details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_users ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _users = conn.get_all_users(path_prefix=path_prefix) users = _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) while marker: _users = conn.get_all_users(path_prefix=path_prefix, marker=marker) users = users + _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) return users def get_all_user_policies(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all user policies. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_user_policies myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_all_user_policies(user_name, marker, max_items) if not info: return False _list = info.list_user_policies_response.list_user_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policies for user %s.', user_name) return False def get_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user_policy myuser mypolicyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user_policy(user_name, policy_name) log.debug('Info for IAM user %s policy %s: %s.', user_name, policy_name, info) if not info: return False info = info.get_user_policy_response.get_user_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policy %s for IAM user %s.', policy_name, user_name) return False def put_user_policy(user_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_user_policy myuser policyname policyrules ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_user_policy(user_name, policy_name, policy_json) if created: log.info('Created policy %s for IAM user %s.', policy_name, user_name) return True log.error('Could not create policy %s for IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy %s for IAM user %s.', policy_name, user_name) return False def delete_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user_policy myuser mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_user_policy( user_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_user_policy(user_name, policy_name) log.info('Successfully deleted policy %s for IAM user %s.', policy_name, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM user %s.', policy_name, user_name) return False def upload_server_cert(cert_name, cert_body, private_key, cert_chain=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Upload a certificate to Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.upload_server_cert mycert_name crt priv_key :param cert_name: The name for the server certificate. Do not include the path in this value. :param cert_body: The contents of the public key certificate in PEM-encoded format. :param private_key: The contents of the private key in PEM-encoded format. :param cert_chain: The contents of the certificate chain. This is typically a concatenation of the PEM-encoded public key certificates of the chain. :param path: The path for the server certificate. :param region: The name of the region to connect to. :param key: The key to be used in order to connect :param keyid: The keyid to be used in order to connect :param profile: The profile that contains a dict of region, key, keyid :return: True / False ''' exists = get_server_certificate(cert_name, region, key, keyid, profile) if exists: return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.upload_server_cert(cert_name, cert_body, private_key, cert_chain) log.info('Created certificate %s.', cert_name) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to failed to create certificate %s.', cert_name) return False def list_server_certificates(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Lists the server certificates stored in IAM that have the specified path prefix. .. versionadded:: ??? :param path_prefix: The path prefix for filtering the results. For example: /company/servercerts would get all server certificates for which the path starts with /company/servercerts . This parameter is optional. If it is not included, it defaults to a slash (/), listing all server certificates. This parameter allows (per its regex pattern) a string of characters consisting of either a forward slash (/) by itself or a string that must begin and end with forward slashes. In addition, it can contain any ASCII character from the ! (u0021) through the DEL character (u007F), including most punctuation characters, digits, and upper and lowercased letters. CLI Example: .. code-block:: bash salt myminion boto_iam.list_server_certificates path_prefix=/somepath/ ''' retries = 10 sleep = 6 conn = __utils__['boto3.get_connection']('iam', region=region, key=key, keyid=keyid, profile=profile) Items = [] while retries: try: log.debug('Garnering list of IAM Server Certificates') IsTruncated = True while IsTruncated: kwargs = {'PathPrefix': path_prefix} ret = conn.list_server_certificates(**kwargs) Items += ret.get('ServerCertificateMetadataList', []) IsTruncated = ret.get('IsTruncated') kwargs.update({'Marker': ret.get('Marker')}) return Items except botocore.exceptions.ParamValidationError as err: raise SaltInvocationError(str(err)) except botocore.exceptions.ClientError as err: if retries and jmespath.search('Error.Code', err.response) == 'Throttling': retries -= 1 log.debug('Throttled by AWS API, retrying in %s seconds...', sleep) time.sleep(sleep) continue log.error('Failed to list IAM Server Certificates: %s', err.message) return None def get_server_certificate(cert_name, region=None, key=None, keyid=None, profile=None): ''' Returns certificate information from Amazon .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_server_certificate mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_server_certificate(cert_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get certificate %s information.', cert_name) return False def delete_server_cert(cert_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a certificate from Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_server_cert mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_server_cert(cert_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete certificate %s.', cert_name) return False def export_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM user details. Produces results that can be used to create an sls file. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.export_users --out=txt | sed "s/local: //" > iam_users.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() users = get_all_users(path_prefix, region, key, keyid, profile) for user in users: name = user.user_name _policies = conn.get_all_user_policies(name, max_items=100) _policies = _policies.list_user_policies_response.list_user_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_user_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_user_policy_response.get_user_policy_result.policy_document )) policies[policy_name] = _policy user_sls = [] user_sls.append({"name": name}) user_sls.append({"policies": policies}) user_sls.append({"path": user.path}) results["manage user " + name] = {"boto_iam.user_present": user_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def export_roles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM role details. Produces results that can be used to create an sls file. CLI Example: salt-call boto_iam.export_roles --out=txt | sed "s/local: //" > iam_roles.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() roles = get_all_roles(path_prefix, region, key, keyid, profile) for role in roles: name = role.role_name _policies = conn.list_role_policies(name, max_items=100) _policies = _policies.list_role_policies_response.list_role_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_role_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_role_policy_response.get_role_policy_result.policy_document )) policies[policy_name] = _policy role_sls = [] role_sls.append({"name": name}) role_sls.append({"policies": policies}) role_sls.append({'policy_document': salt.utils.json.loads(_unquote(role.assume_role_policy_document))}) role_sls.append({"path": role.path}) results["manage role " + name] = {"boto_iam_role.present": role_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def _get_policy_arn(name, region=None, key=None, keyid=None, profile=None): if name.startswith('arn:aws:iam:'): return name account_id = get_account_id( region=region, key=key, keyid=keyid, profile=profile ) return 'arn:aws:iam::{0}:policy/{1}'.format(account_id, name) def policy_exists(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return True except boto.exception.BotoServerError: return False def get_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return ret.get('get_policy_response', {}).get('get_policy_result', {}) except boto.exception.BotoServerError: return None def create_policy(policy_name, policy_document, path=None, description=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in 'path', 'description': if locals()[arg] is not None: params[arg] = locals()[arg] if policy_exists(policy_name, region, key, keyid, profile): return True try: conn.create_policy(policy_name, policy_document, **params) log.info('Created IAM policy %s.', policy_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s.', policy_name) return False return True def delete_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_exists(policy_arn, region, key, keyid, profile): return True try: conn.delete_policy(policy_arn) log.info('Deleted %s policy.', policy_name) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete %s policy: %s.', policy_name, aws.get('message')) return False return True def list_policies(region=None, key=None, keyid=None, profile=None): ''' List policies. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policies ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: policies = [] for ret in __utils__['boto.paged_call'](conn.list_policies): policies.append(ret.get('list_policies_response', {}).get('list_policies_result', {}).get('policies')) return policies except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to list policy versions.' log.error(msg) return [] def policy_version_exists(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.get_policy_version(policy_arn, version_id) return True except boto.exception.BotoServerError: return False def get_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy_version(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile), version_id) retval = ret.get('get_policy_version_response', {}).get('get_policy_version_result', {}).get('policy_version', {}) retval['document'] = _unquote(retval.get('document')) return {'policy_version': retval} except boto.exception.BotoServerError: return None def create_policy_version(policy_name, policy_document, set_as_default=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy version. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy_version mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in ('set_as_default',): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.create_policy_version(policy_arn, policy_document, **params) vid = ret.get('create_policy_version_response', {}).get('create_policy_version_result', {}).get('policy_version', {}).get('version_id') log.info('Created IAM policy %s version %s.', policy_name, vid) return {'created': True, 'version_id': vid} except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s version %s.', policy_name, vid) return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Delete a policy version. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_version_exists(policy_arn, version_id, region, key, keyid, profile): return True try: conn.delete_policy_version(policy_arn, version_id) log.info('Deleted IAM policy %s version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete IAM policy %s version %s: %s', policy_name, version_id, aws.get('message')) return False return True def list_policy_versions(policy_name, region=None, key=None, keyid=None, profile=None): ''' List versions of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policy_versions mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.list_policy_versions(policy_arn) return ret.get('list_policy_versions_response', {}).get('list_policy_versions_result', {}).get('versions') except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list versions for IAM policy %s.', policy_name) return [] def set_default_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Set the default version of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.set_default_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.set_default_policy_version(policy_arn, version_id) log.info('Set %s policy to version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to set %s policy to version %s: %s', policy_name, version_id, aws.get('message')) return False return True def attach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_user_policy(policy_arn, user_name) log.info('Attached policy %s to IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach %s policy to IAM user %s.', policy_name, user_name) return False return True def detach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_user_policy(policy_arn, user_name) log.info('Detached %s policy from IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach %s policy from IAM user %s.', policy_name, user_name) return False return True def attach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_group_policy(policy_arn, group_name) log.info('Attached policy %s to IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM group %s.', policy_name, group_name) return False return True def detach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_group_policy(policy_arn, group_name) log.info('Detached policy %s from IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM group %s.', policy_name, group_name) return False return True def attach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_role_policy(policy_arn, role_name) log.info('Attached policy %s to IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM role %s.', policy_name, role_name) return False return True def detach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_role_policy(policy_arn, role_name) log.info('Detached policy %s from IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM role %s.', policy_name, role_name) return False return True def list_entities_for_policy(policy_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities that a policy is attached to. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 params = {} for arg in ('path_prefix', 'entity_filter'): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) while retries: try: allret = { 'policy_groups': [], 'policy_users': [], 'policy_roles': [], } for ret in __utils__['boto.paged_call'](conn.list_entities_for_policy, policy_arn=policy_arn, **params): for k, v in six.iteritems(allret): v.extend(ret.get('list_entities_for_policy_response', {}).get('list_entities_for_policy_result', {}).get(k)) return allret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('Failed to list entities for IAM policy %s: %s', policy_name, e.message) return {} return {} def list_attached_user_policies(user_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given user. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'UserName': user_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedUserPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_user_policies_response', {}).get('list_attached_user_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM user %s.', user_name) return [] def list_attached_group_policies(group_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given group. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'GroupName': group_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedGroupPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_group_policies_response', {}).get('list_attached_group_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM group %s.', group_name) return [] def list_attached_role_policies(role_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'RoleName': role_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedRolePolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_role_policies_response', {}).get('list_attached_role_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM role %s.', role_name) return [] def create_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Create SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.create_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_saml_provider(saml_metadata_document, name) log.info('Successfully created %s SAML provider.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to create SAML provider %s.', name) return False def get_saml_provider_arn(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider_arn my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_saml_providers() for saml_provider in response.list_saml_providers_response.list_saml_providers_result.saml_provider_list: if saml_provider['arn'].endswith(':saml-provider/' + name): return saml_provider['arn'] return False except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to get ARN of SAML provider %s.', name) return False def delete_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Delete SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.delete_saml_provider my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return True conn.delete_saml_provider(saml_provider_arn) log.info('Successfully deleted SAML provider %s.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete SAML provider %s.', name) return False def list_saml_providers(region=None, key=None, keyid=None, profile=None): ''' List SAML providers. CLI Example: .. code-block:: bash salt myminion boto_iam.list_saml_providers ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: providers = [] info = conn.list_saml_providers() for arn in info['list_saml_providers_response']['list_saml_providers_result']['saml_provider_list']: providers.append(arn['arn'].rsplit('/', 1)[1]) return providers except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get list of SAML providers.') return False def get_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider document. CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider arn ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: provider = conn.get_saml_provider(name) return provider['get_saml_provider_response']['get_saml_provider_result']['saml_metadata_document'] except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get SAML provider document %s.', name) return False def update_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Update SAML provider. CLI Example: .. code-block:: bash salt myminion boto_iam.update_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return False if conn.update_saml_provider(name, saml_metadata_document): return True return False except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to update SAML provider %s.', name) return False
saltstack/salt
salt/modules/boto_iam.py
get_account_id
python
def get_account_id(region=None, key=None, keyid=None, profile=None): ''' Get a the AWS account id associated with the used credentials. CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_id ''' cache_key = 'boto_iam.account_id' if cache_key not in __context__: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_user() # The get_user call returns an user ARN: # arn:aws:iam::027050522557:user/salt-test arn = ret['get_user_response']['get_user_result']['user']['arn'] account_id = arn.split(':')[4] except boto.exception.BotoServerError: # If call failed, then let's try to get the ARN from the metadata timeout = boto.config.getfloat( 'Boto', 'metadata_service_timeout', 1.0 ) attempts = boto.config.getint( 'Boto', 'metadata_service_num_attempts', 1 ) identity = boto.utils.get_instance_identity( timeout=timeout, num_retries=attempts ) try: account_id = identity['document']['accountId'] except KeyError: log.error('Failed to get account id from instance_identity in' ' boto_iam.get_account_id.') __context__[cache_key] = account_id return __context__[cache_key]
Get a the AWS account id associated with the used credentials. CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_id
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iam.py#L1278-L1314
null
# -*- coding: utf-8 -*- ''' Connection module for Amazon IAM .. versionadded:: 2014.7.0 :configuration: This module accepts explicit iam 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 iam.keyid: GKTADJGHEIQSXMKKRBJ08H iam.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs iam.region: 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: boto ''' # keep lint from choking on _get_conn and _cache_id #pylint: disable=E0602 # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import salt libs from salt.ext import six import salt.utils.compat import salt.utils.json import salt.utils.odict as odict import salt.utils.versions from salt.exceptions import SaltInvocationError # Import third party libs # pylint: disable=unused-import from salt.ext.six.moves.urllib.parse import unquote as _unquote # pylint: disable=no-name-in-module try: import boto import boto.iam import boto3 import botocore logging.getLogger('boto').setLevel(logging.CRITICAL) logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=unused-import log = logging.getLogger(__name__) def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'iam', pack=__salt__) def instance_profile_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an instance profile exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: # Boto weirdly returns an exception here if an instance profile doesn't # exist. conn.get_instance_profile(name) return True except boto.exception.BotoServerError: return False def create_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Create an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.create_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if instance_profile_exists(name, region, key, keyid, profile): return True try: # This call returns an instance profile if successful and an exception # if not. It's annoying. conn.create_instance_profile(name) log.info('Created %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create %s instance profile.', name) return False return True def delete_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Delete an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not instance_profile_exists(name, region, key, keyid, profile): return True try: conn.delete_instance_profile(name) log.info('Deleted %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s instance profile.', name) return False return True def role_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an IAM role exists. CLI Example: .. code-block:: bash salt myminion boto_iam.role_exists myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_role(name) return True except boto.exception.BotoServerError: return False def describe_role(name, region=None, key=None, keyid=None, profile=None): ''' Get information for a role. CLI Example: .. code-block:: bash salt myminion boto_iam.describe_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_role(name) if not info: return False role = info.get_role_response.get_role_result.role role['assume_role_policy_document'] = salt.utils.json.loads(_unquote( role.assume_role_policy_document )) # If Sid wasn't defined by the user, boto will still return a Sid in # each policy. To properly check idempotently, let's remove the Sid # from the return if it's not actually set. for policy_key, policy in role['assume_role_policy_document'].items(): if policy_key == 'Statement': for val in policy: if 'Sid' in val and not val['Sid']: del val['Sid'] return role except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get %s information.', name) return False def create_user(user_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_user myuser ''' if not path: path = '/' if get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_user(user_name, path) log.info('Created IAM user : %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM user %s.', user_name) return False def get_all_access_keys(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all access keys from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_access_keys myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.get_all_access_keys(user_name, marker, max_items) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get access keys for IAM user %s.', user_name) return six.text_type(e) def create_access_key(user_name, region=None, key=None, keyid=None, profile=None): ''' Create access key id for a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.create_access_key(user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create access key.') return six.text_type(e) def delete_access_key(access_key_id, user_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete access key id from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_access_key(access_key_id, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete access key id %s.', access_key_id) return six.text_type(e) def delete_user(user_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user myuser ''' if not get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.delete_user(user_name) log.info('Deleted IAM user : %s .', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM user %s', user_name) return six.text_type(e) def get_user(user_name=None, region=None, key=None, keyid=None, profile=None): ''' Get user information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user(user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM user %s info.', user_name) return False def create_group(group_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_group group ''' if not path: path = '/' if get_group(group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_group(group_name, path) log.info('Created IAM group : %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM group %s.', group_name) return False def get_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group(group_name, max_items=1) if not info: return False return info['get_group_response']['get_group_result']['group'] except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_group_members(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: marker = None truncated = True users = [] while truncated: info = conn.get_group(group_name, marker=marker, max_items=1000) if not info: return False truncated = bool(info['get_group_response']['get_group_result']['is_truncated']) if truncated and 'marker' in info['get_group_response']['get_group_result']: marker = info['get_group_response']['get_group_result']['marker'] else: marker = None truncated = False users += info['get_group_response']['get_group_result']['users'] return users except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get members for IAM group %s.', group_name) return False def add_user_to_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Add user to group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.add_user_to_group myuser mygroup ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('Username : %s does not exist.', user_name) return False if user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.add_user_to_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add IAM user %s to group %s.', user_name, group_name) return False def user_exists_in_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Check if user exists in group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.user_exists_in_group myuser mygroup ''' # TODO this should probably use boto.iam.get_groups_for_user users = get_group_members( group_name=group_name, region=region, key=key, keyid=keyid, profile=profile ) if users: for _user in users: if user_name == _user['user_name']: log.debug('IAM user %s is already in IAM group %s.', user_name, group_name) return True return False def remove_user_from_group(group_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Remove user from group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.remove_user_from_group mygroup myuser ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist.', user_name) return False if not user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.remove_user_from_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove IAM user %s from group %s', user_name, group_name) return False def put_group_policy(group_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_group_policy mygroup policyname policyrules ''' group = get_group(group_name, region=region, key=key, keyid=keyid, profile=profile) if not group: log.error('Group %s does not exist', group_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_group_policy(group_name, policy_name, policy_json) if created: log.info('Created policy for IAM group %s.', group_name) return True log.error('Could not create policy for IAM group %s', group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy for IAM group %s', group_name) return False def delete_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group_policy mygroup mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_group_policy( group_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_group_policy(group_name, policy_name) log.info('Successfully deleted policy %s for IAM group %s.', policy_name, group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM group %s.', policy_name, group_name) return False def get_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group_policy mygroup policyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group_policy(group_name, policy_name) log.debug('info for group policy is : %s', info) if not info: return False info = info.get_group_policy_response.get_group_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_all_groups(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM group details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_groups ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _groups = conn.get_all_groups(path_prefix=path_prefix) groups = _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) while marker: _groups = conn.get_all_groups(path_prefix=path_prefix, marker=marker) groups = groups + _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) return groups def get_all_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.get_all_instance_profiles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) marker = False profiles = [] while marker is not None: marker = marker if marker else None p = conn.list_instance_profiles(path_prefix=path_prefix, marker=marker) res = p.list_instance_profiles_response.list_instance_profiles_result profiles += res.instance_profiles marker = getattr(res, 'marker', None) return profiles def list_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' List all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.list_instance_profiles ''' p = get_all_instance_profiles(path_prefix, region, key, keyid, profile) return [i['instance_profile_name'] for i in p] def get_all_group_policies(group_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a group. CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_group_policies mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False try: response = conn.get_all_group_policies(group_name) _list = response.list_group_policies_response.list_group_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def delete_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _group = get_group( group_name, region, key, keyid, profile ) if not _group: return True try: conn.delete_group(group_name) log.info('Successfully deleted IAM group %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM group %s.', group_name) return False def create_login_profile(user_name, password, region=None, key=None, keyid=None, profile=None): ''' Creates a login profile for the specified user, give the user the ability to access AWS services and the AWS Management Console. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_login_profile user_name password ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.create_login_profile(user_name, password) log.info('Created profile for IAM user %s.', user_name) return info except boto.exception.BotoServerError as e: log.debug(e) if 'Conflict' in e: log.info('Profile already exists for IAM user %s.', user_name) return 'Conflict' log.error('Failed to update profile for IAM user %s.', user_name) return False def delete_login_profile(user_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a login profile for the specified user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_login_profile user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.delete_login_profile(user_name) log.info('Deleted login profile for IAM user %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Login profile already deleted for IAM user %s.', user_name) return True log.error('Failed to delete login profile for IAM user %s.', user_name) return False def get_all_mfa_devices(user_name, region=None, key=None, keyid=None, profile=None): ''' Get all MFA devices associated with an IAM user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_mfa_devices user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: result = conn.get_all_mfa_devices(user_name) devices = result['list_mfa_devices_response']['list_mfa_devices_result']['mfa_devices'] return devices except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Could not find IAM user %s.', user_name) return [] log.error('Failed to get all MFA devices for IAM user %s.', user_name) return False def deactivate_mfa_device(user_name, serial, region=None, key=None, keyid=None, profile=None): ''' Deactivates the specified MFA device and removes it from association with the user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.deactivate_mfa_device user_name serial_num ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.deactivate_mfa_device(user_name, serial) log.info('Deactivated MFA device %s for IAM user %s.', serial, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('MFA device %s not associated with IAM user %s.', serial, user_name) return True log.error('Failed to deactivate MFA device %s for IAM user %s.', serial, user_name) return False def delete_virtual_mfa_device(serial, region=None, key=None, keyid=None, profile=None): ''' Deletes the specified virtual MFA device. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_virtual_mfa_device serial_num ''' conn = __utils__['boto3.get_connection_func']('iam')() try: conn.delete_virtual_mfa_device(SerialNumber=serial) log.info('Deleted virtual MFA device %s.', serial) return True except botocore.exceptions.ClientError as e: log.debug(e) if 'NoSuchEntity' in six.text_type(e): log.info('Virtual MFA device %s not found.', serial) return True log.error('Failed to delete virtual MFA device %s.', serial) return False def update_account_password_policy(allow_users_to_change_password=None, hard_expiry=None, max_password_age=None, minimum_password_length=None, password_reuse_prevention=None, require_lowercase_characters=None, require_numbers=None, require_symbols=None, require_uppercase_characters=None, region=None, key=None, keyid=None, profile=None): ''' Update the password policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_account_password_policy True ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.update_account_password_policy(allow_users_to_change_password, hard_expiry, max_password_age, minimum_password_length, password_reuse_prevention, require_lowercase_characters, require_numbers, require_symbols, require_uppercase_characters) log.info('The password policy has been updated.') return True except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy' log.error(msg) return False def get_account_policy(region=None, key=None, keyid=None, profile=None): ''' Get account policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_account_password_policy() return info.get_account_password_policy_response.get_account_password_policy_result.password_policy except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy.' log.error(msg) return False def create_role(name, policy_document=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Create an instance role. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if role_exists(name, region, key, keyid, profile): return True if not policy_document: policy_document = None try: conn.create_role(name, assume_role_policy_document=policy_document, path=path) log.info('Created IAM role %s.', name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to create IAM role %s.', name) return False def delete_role(name, region=None, key=None, keyid=None, profile=None): ''' Delete an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(name, region, key, keyid, profile): return True try: conn.delete_role(name) log.info('Deleted %s IAM role.', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s IAM role.', name) return False def profile_associated(role_name, profile_name, region, key, keyid, profile): ''' Check to see if an instance profile is associated with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.profile_associated myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # The IAM module of boto doesn't return objects. Instead you need to grab # values through its properties. Sigh. try: profiles = conn.list_instance_profiles_for_role(role_name) except boto.exception.BotoServerError as e: log.debug(e) return False profiles = profiles.list_instance_profiles_for_role_response profiles = profiles.list_instance_profiles_for_role_result profiles = profiles.instance_profiles for profile in profiles: if profile.instance_profile_name == profile_name: return True return False def associate_profile_to_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Associate an instance profile with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.associate_profile_to_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if associated: return True else: try: conn.add_role_to_instance_profile(profile_name, role_name) log.info('Added %s instance profile to IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add %s instance profile to IAM role %s', profile_name, role_name) return False def disassociate_profile_from_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Disassociate an instance profile from an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.disassociate_profile_from_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if not associated: return True else: try: conn.remove_role_from_instance_profile(profile_name, role_name) log.info('Removed %s instance profile from IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove %s instance profile from IAM role %s.', profile_name, role_name) return False def list_role_policies(role_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_role_policies myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_role_policies(role_name) _list = response.list_role_policies_response.list_role_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def get_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.get_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: _policy = conn.get_role_policy(role_name, policy_name) # I _hate_ you for not giving me an object boto. _policy = _policy.get_role_policy_response.policy_document # Policy is url encoded _policy = _unquote(_policy) _policy = salt.utils.json.loads(_policy, object_pairs_hook=odict.OrderedDict) return _policy except boto.exception.BotoServerError: return {} def create_role_policy(role_name, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Create or modify a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role_policy myirole mypolicy '{"MyPolicy": "Statement": [{"Action": ["sqs:*"], "Effect": "Allow", "Resource": ["arn:aws:sqs:*:*:*"], "Sid": "MyPolicySqs1"}]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) mode = 'create' if _policy: if _policy == policy: return True mode = 'modify' if isinstance(policy, six.string_types): policy = salt.utils.json.loads(policy, object_pairs_hook=odict.OrderedDict) try: _policy = salt.utils.json.dumps(policy) conn.put_role_policy(role_name, policy_name, _policy) if mode == 'create': msg = 'Successfully added policy %s to IAM role %s.' else: msg = 'Successfully modified policy %s for IAM role %s.' log.info(msg, policy_name, role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to %s policy %s for IAM role %s.', mode, policy_name, role_name) return False def delete_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) if not _policy: return True try: conn.delete_role_policy(role_name, policy_name) log.info('Successfully deleted policy %s for IAM role %s.', policy_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM role %s.', policy_name, role_name) return False def update_assume_role_policy(role_name, policy_document, region=None, key=None, keyid=None, profile=None): ''' Update an assume role policy for a role. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_assume_role_policy myrole '{"Statement":"..."}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(policy_document, six.string_types): policy_document = salt.utils.json.loads(policy_document, object_pairs_hook=odict.OrderedDict) try: _policy_document = salt.utils.json.dumps(policy_document) conn.update_assume_role_policy(role_name, _policy_document) log.info('Successfully updated assume role policy for IAM role %s.', role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to update assume role policy for IAM role %s.', role_name) return False def build_policy(region=None, key=None, keyid=None, profile=None): ''' Build a default assume role policy. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.build_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if hasattr(conn, 'build_policy'): policy = salt.utils.json.loads(conn.build_policy()) elif hasattr(conn, '_build_policy'): policy = salt.utils.json.loads(conn._build_policy()) else: return {} # The format we get from build_policy isn't going to be what we get back # from AWS for the exact same policy. AWS converts single item list values # into strings, so let's do the same here. for key, policy_val in policy.items(): for statement in policy_val: if (isinstance(statement['Action'], list) and len(statement['Action']) == 1): statement['Action'] = statement['Action'][0] if (isinstance(statement['Principal']['Service'], list) and len(statement['Principal']['Service']) == 1): statement['Principal']['Service'] = statement['Principal']['Service'][0] # build_policy doesn't add a version field, which AWS is going to set to a # default value, when we get it back, so let's set it. policy['Version'] = '2008-10-17' return policy def get_all_roles(path_prefix=None, region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM role details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_roles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _roles = conn.list_roles(path_prefix=path_prefix) roles = _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) while marker: _roles = conn.list_roles(path_prefix=path_prefix, marker=marker) roles = roles + _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) return roles def get_all_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM user details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_users ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _users = conn.get_all_users(path_prefix=path_prefix) users = _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) while marker: _users = conn.get_all_users(path_prefix=path_prefix, marker=marker) users = users + _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) return users def get_all_user_policies(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all user policies. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_user_policies myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_all_user_policies(user_name, marker, max_items) if not info: return False _list = info.list_user_policies_response.list_user_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policies for user %s.', user_name) return False def get_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user_policy myuser mypolicyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user_policy(user_name, policy_name) log.debug('Info for IAM user %s policy %s: %s.', user_name, policy_name, info) if not info: return False info = info.get_user_policy_response.get_user_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policy %s for IAM user %s.', policy_name, user_name) return False def put_user_policy(user_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_user_policy myuser policyname policyrules ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_user_policy(user_name, policy_name, policy_json) if created: log.info('Created policy %s for IAM user %s.', policy_name, user_name) return True log.error('Could not create policy %s for IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy %s for IAM user %s.', policy_name, user_name) return False def delete_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user_policy myuser mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_user_policy( user_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_user_policy(user_name, policy_name) log.info('Successfully deleted policy %s for IAM user %s.', policy_name, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM user %s.', policy_name, user_name) return False def upload_server_cert(cert_name, cert_body, private_key, cert_chain=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Upload a certificate to Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.upload_server_cert mycert_name crt priv_key :param cert_name: The name for the server certificate. Do not include the path in this value. :param cert_body: The contents of the public key certificate in PEM-encoded format. :param private_key: The contents of the private key in PEM-encoded format. :param cert_chain: The contents of the certificate chain. This is typically a concatenation of the PEM-encoded public key certificates of the chain. :param path: The path for the server certificate. :param region: The name of the region to connect to. :param key: The key to be used in order to connect :param keyid: The keyid to be used in order to connect :param profile: The profile that contains a dict of region, key, keyid :return: True / False ''' exists = get_server_certificate(cert_name, region, key, keyid, profile) if exists: return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.upload_server_cert(cert_name, cert_body, private_key, cert_chain) log.info('Created certificate %s.', cert_name) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to failed to create certificate %s.', cert_name) return False def list_server_certificates(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Lists the server certificates stored in IAM that have the specified path prefix. .. versionadded:: ??? :param path_prefix: The path prefix for filtering the results. For example: /company/servercerts would get all server certificates for which the path starts with /company/servercerts . This parameter is optional. If it is not included, it defaults to a slash (/), listing all server certificates. This parameter allows (per its regex pattern) a string of characters consisting of either a forward slash (/) by itself or a string that must begin and end with forward slashes. In addition, it can contain any ASCII character from the ! (u0021) through the DEL character (u007F), including most punctuation characters, digits, and upper and lowercased letters. CLI Example: .. code-block:: bash salt myminion boto_iam.list_server_certificates path_prefix=/somepath/ ''' retries = 10 sleep = 6 conn = __utils__['boto3.get_connection']('iam', region=region, key=key, keyid=keyid, profile=profile) Items = [] while retries: try: log.debug('Garnering list of IAM Server Certificates') IsTruncated = True while IsTruncated: kwargs = {'PathPrefix': path_prefix} ret = conn.list_server_certificates(**kwargs) Items += ret.get('ServerCertificateMetadataList', []) IsTruncated = ret.get('IsTruncated') kwargs.update({'Marker': ret.get('Marker')}) return Items except botocore.exceptions.ParamValidationError as err: raise SaltInvocationError(str(err)) except botocore.exceptions.ClientError as err: if retries and jmespath.search('Error.Code', err.response) == 'Throttling': retries -= 1 log.debug('Throttled by AWS API, retrying in %s seconds...', sleep) time.sleep(sleep) continue log.error('Failed to list IAM Server Certificates: %s', err.message) return None def get_server_certificate(cert_name, region=None, key=None, keyid=None, profile=None): ''' Returns certificate information from Amazon .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_server_certificate mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_server_certificate(cert_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get certificate %s information.', cert_name) return False def delete_server_cert(cert_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a certificate from Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_server_cert mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_server_cert(cert_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete certificate %s.', cert_name) return False def export_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM user details. Produces results that can be used to create an sls file. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.export_users --out=txt | sed "s/local: //" > iam_users.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() users = get_all_users(path_prefix, region, key, keyid, profile) for user in users: name = user.user_name _policies = conn.get_all_user_policies(name, max_items=100) _policies = _policies.list_user_policies_response.list_user_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_user_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_user_policy_response.get_user_policy_result.policy_document )) policies[policy_name] = _policy user_sls = [] user_sls.append({"name": name}) user_sls.append({"policies": policies}) user_sls.append({"path": user.path}) results["manage user " + name] = {"boto_iam.user_present": user_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def export_roles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM role details. Produces results that can be used to create an sls file. CLI Example: salt-call boto_iam.export_roles --out=txt | sed "s/local: //" > iam_roles.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() roles = get_all_roles(path_prefix, region, key, keyid, profile) for role in roles: name = role.role_name _policies = conn.list_role_policies(name, max_items=100) _policies = _policies.list_role_policies_response.list_role_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_role_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_role_policy_response.get_role_policy_result.policy_document )) policies[policy_name] = _policy role_sls = [] role_sls.append({"name": name}) role_sls.append({"policies": policies}) role_sls.append({'policy_document': salt.utils.json.loads(_unquote(role.assume_role_policy_document))}) role_sls.append({"path": role.path}) results["manage role " + name] = {"boto_iam_role.present": role_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def _get_policy_arn(name, region=None, key=None, keyid=None, profile=None): if name.startswith('arn:aws:iam:'): return name account_id = get_account_id( region=region, key=key, keyid=keyid, profile=profile ) return 'arn:aws:iam::{0}:policy/{1}'.format(account_id, name) def policy_exists(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return True except boto.exception.BotoServerError: return False def get_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return ret.get('get_policy_response', {}).get('get_policy_result', {}) except boto.exception.BotoServerError: return None def create_policy(policy_name, policy_document, path=None, description=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in 'path', 'description': if locals()[arg] is not None: params[arg] = locals()[arg] if policy_exists(policy_name, region, key, keyid, profile): return True try: conn.create_policy(policy_name, policy_document, **params) log.info('Created IAM policy %s.', policy_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s.', policy_name) return False return True def delete_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_exists(policy_arn, region, key, keyid, profile): return True try: conn.delete_policy(policy_arn) log.info('Deleted %s policy.', policy_name) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete %s policy: %s.', policy_name, aws.get('message')) return False return True def list_policies(region=None, key=None, keyid=None, profile=None): ''' List policies. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policies ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: policies = [] for ret in __utils__['boto.paged_call'](conn.list_policies): policies.append(ret.get('list_policies_response', {}).get('list_policies_result', {}).get('policies')) return policies except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to list policy versions.' log.error(msg) return [] def policy_version_exists(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.get_policy_version(policy_arn, version_id) return True except boto.exception.BotoServerError: return False def get_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy_version(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile), version_id) retval = ret.get('get_policy_version_response', {}).get('get_policy_version_result', {}).get('policy_version', {}) retval['document'] = _unquote(retval.get('document')) return {'policy_version': retval} except boto.exception.BotoServerError: return None def create_policy_version(policy_name, policy_document, set_as_default=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy version. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy_version mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in ('set_as_default',): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.create_policy_version(policy_arn, policy_document, **params) vid = ret.get('create_policy_version_response', {}).get('create_policy_version_result', {}).get('policy_version', {}).get('version_id') log.info('Created IAM policy %s version %s.', policy_name, vid) return {'created': True, 'version_id': vid} except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s version %s.', policy_name, vid) return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Delete a policy version. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_version_exists(policy_arn, version_id, region, key, keyid, profile): return True try: conn.delete_policy_version(policy_arn, version_id) log.info('Deleted IAM policy %s version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete IAM policy %s version %s: %s', policy_name, version_id, aws.get('message')) return False return True def list_policy_versions(policy_name, region=None, key=None, keyid=None, profile=None): ''' List versions of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policy_versions mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.list_policy_versions(policy_arn) return ret.get('list_policy_versions_response', {}).get('list_policy_versions_result', {}).get('versions') except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list versions for IAM policy %s.', policy_name) return [] def set_default_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Set the default version of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.set_default_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.set_default_policy_version(policy_arn, version_id) log.info('Set %s policy to version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to set %s policy to version %s: %s', policy_name, version_id, aws.get('message')) return False return True def attach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_user_policy(policy_arn, user_name) log.info('Attached policy %s to IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach %s policy to IAM user %s.', policy_name, user_name) return False return True def detach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_user_policy(policy_arn, user_name) log.info('Detached %s policy from IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach %s policy from IAM user %s.', policy_name, user_name) return False return True def attach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_group_policy(policy_arn, group_name) log.info('Attached policy %s to IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM group %s.', policy_name, group_name) return False return True def detach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_group_policy(policy_arn, group_name) log.info('Detached policy %s from IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM group %s.', policy_name, group_name) return False return True def attach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_role_policy(policy_arn, role_name) log.info('Attached policy %s to IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM role %s.', policy_name, role_name) return False return True def detach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_role_policy(policy_arn, role_name) log.info('Detached policy %s from IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM role %s.', policy_name, role_name) return False return True def list_entities_for_policy(policy_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities that a policy is attached to. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 params = {} for arg in ('path_prefix', 'entity_filter'): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) while retries: try: allret = { 'policy_groups': [], 'policy_users': [], 'policy_roles': [], } for ret in __utils__['boto.paged_call'](conn.list_entities_for_policy, policy_arn=policy_arn, **params): for k, v in six.iteritems(allret): v.extend(ret.get('list_entities_for_policy_response', {}).get('list_entities_for_policy_result', {}).get(k)) return allret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('Failed to list entities for IAM policy %s: %s', policy_name, e.message) return {} return {} def list_attached_user_policies(user_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given user. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'UserName': user_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedUserPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_user_policies_response', {}).get('list_attached_user_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM user %s.', user_name) return [] def list_attached_group_policies(group_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given group. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'GroupName': group_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedGroupPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_group_policies_response', {}).get('list_attached_group_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM group %s.', group_name) return [] def list_attached_role_policies(role_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'RoleName': role_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedRolePolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_role_policies_response', {}).get('list_attached_role_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM role %s.', role_name) return [] def create_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Create SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.create_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_saml_provider(saml_metadata_document, name) log.info('Successfully created %s SAML provider.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to create SAML provider %s.', name) return False def get_saml_provider_arn(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider_arn my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_saml_providers() for saml_provider in response.list_saml_providers_response.list_saml_providers_result.saml_provider_list: if saml_provider['arn'].endswith(':saml-provider/' + name): return saml_provider['arn'] return False except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to get ARN of SAML provider %s.', name) return False def delete_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Delete SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.delete_saml_provider my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return True conn.delete_saml_provider(saml_provider_arn) log.info('Successfully deleted SAML provider %s.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete SAML provider %s.', name) return False def list_saml_providers(region=None, key=None, keyid=None, profile=None): ''' List SAML providers. CLI Example: .. code-block:: bash salt myminion boto_iam.list_saml_providers ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: providers = [] info = conn.list_saml_providers() for arn in info['list_saml_providers_response']['list_saml_providers_result']['saml_provider_list']: providers.append(arn['arn'].rsplit('/', 1)[1]) return providers except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get list of SAML providers.') return False def get_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider document. CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider arn ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: provider = conn.get_saml_provider(name) return provider['get_saml_provider_response']['get_saml_provider_result']['saml_metadata_document'] except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get SAML provider document %s.', name) return False def update_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Update SAML provider. CLI Example: .. code-block:: bash salt myminion boto_iam.update_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return False if conn.update_saml_provider(name, saml_metadata_document): return True return False except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to update SAML provider %s.', name) return False
saltstack/salt
salt/modules/boto_iam.py
get_all_roles
python
def get_all_roles(path_prefix=None, region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM role details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_roles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _roles = conn.list_roles(path_prefix=path_prefix) roles = _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) while marker: _roles = conn.list_roles(path_prefix=path_prefix, marker=marker) roles = roles + _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) return roles
Get and return all IAM role details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_roles
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iam.py#L1317-L1342
null
# -*- coding: utf-8 -*- ''' Connection module for Amazon IAM .. versionadded:: 2014.7.0 :configuration: This module accepts explicit iam 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 iam.keyid: GKTADJGHEIQSXMKKRBJ08H iam.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs iam.region: 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: boto ''' # keep lint from choking on _get_conn and _cache_id #pylint: disable=E0602 # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import salt libs from salt.ext import six import salt.utils.compat import salt.utils.json import salt.utils.odict as odict import salt.utils.versions from salt.exceptions import SaltInvocationError # Import third party libs # pylint: disable=unused-import from salt.ext.six.moves.urllib.parse import unquote as _unquote # pylint: disable=no-name-in-module try: import boto import boto.iam import boto3 import botocore logging.getLogger('boto').setLevel(logging.CRITICAL) logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=unused-import log = logging.getLogger(__name__) def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'iam', pack=__salt__) def instance_profile_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an instance profile exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: # Boto weirdly returns an exception here if an instance profile doesn't # exist. conn.get_instance_profile(name) return True except boto.exception.BotoServerError: return False def create_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Create an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.create_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if instance_profile_exists(name, region, key, keyid, profile): return True try: # This call returns an instance profile if successful and an exception # if not. It's annoying. conn.create_instance_profile(name) log.info('Created %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create %s instance profile.', name) return False return True def delete_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Delete an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not instance_profile_exists(name, region, key, keyid, profile): return True try: conn.delete_instance_profile(name) log.info('Deleted %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s instance profile.', name) return False return True def role_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an IAM role exists. CLI Example: .. code-block:: bash salt myminion boto_iam.role_exists myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_role(name) return True except boto.exception.BotoServerError: return False def describe_role(name, region=None, key=None, keyid=None, profile=None): ''' Get information for a role. CLI Example: .. code-block:: bash salt myminion boto_iam.describe_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_role(name) if not info: return False role = info.get_role_response.get_role_result.role role['assume_role_policy_document'] = salt.utils.json.loads(_unquote( role.assume_role_policy_document )) # If Sid wasn't defined by the user, boto will still return a Sid in # each policy. To properly check idempotently, let's remove the Sid # from the return if it's not actually set. for policy_key, policy in role['assume_role_policy_document'].items(): if policy_key == 'Statement': for val in policy: if 'Sid' in val and not val['Sid']: del val['Sid'] return role except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get %s information.', name) return False def create_user(user_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_user myuser ''' if not path: path = '/' if get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_user(user_name, path) log.info('Created IAM user : %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM user %s.', user_name) return False def get_all_access_keys(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all access keys from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_access_keys myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.get_all_access_keys(user_name, marker, max_items) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get access keys for IAM user %s.', user_name) return six.text_type(e) def create_access_key(user_name, region=None, key=None, keyid=None, profile=None): ''' Create access key id for a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.create_access_key(user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create access key.') return six.text_type(e) def delete_access_key(access_key_id, user_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete access key id from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_access_key(access_key_id, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete access key id %s.', access_key_id) return six.text_type(e) def delete_user(user_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user myuser ''' if not get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.delete_user(user_name) log.info('Deleted IAM user : %s .', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM user %s', user_name) return six.text_type(e) def get_user(user_name=None, region=None, key=None, keyid=None, profile=None): ''' Get user information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user(user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM user %s info.', user_name) return False def create_group(group_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_group group ''' if not path: path = '/' if get_group(group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_group(group_name, path) log.info('Created IAM group : %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM group %s.', group_name) return False def get_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group(group_name, max_items=1) if not info: return False return info['get_group_response']['get_group_result']['group'] except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_group_members(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: marker = None truncated = True users = [] while truncated: info = conn.get_group(group_name, marker=marker, max_items=1000) if not info: return False truncated = bool(info['get_group_response']['get_group_result']['is_truncated']) if truncated and 'marker' in info['get_group_response']['get_group_result']: marker = info['get_group_response']['get_group_result']['marker'] else: marker = None truncated = False users += info['get_group_response']['get_group_result']['users'] return users except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get members for IAM group %s.', group_name) return False def add_user_to_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Add user to group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.add_user_to_group myuser mygroup ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('Username : %s does not exist.', user_name) return False if user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.add_user_to_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add IAM user %s to group %s.', user_name, group_name) return False def user_exists_in_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Check if user exists in group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.user_exists_in_group myuser mygroup ''' # TODO this should probably use boto.iam.get_groups_for_user users = get_group_members( group_name=group_name, region=region, key=key, keyid=keyid, profile=profile ) if users: for _user in users: if user_name == _user['user_name']: log.debug('IAM user %s is already in IAM group %s.', user_name, group_name) return True return False def remove_user_from_group(group_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Remove user from group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.remove_user_from_group mygroup myuser ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist.', user_name) return False if not user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.remove_user_from_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove IAM user %s from group %s', user_name, group_name) return False def put_group_policy(group_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_group_policy mygroup policyname policyrules ''' group = get_group(group_name, region=region, key=key, keyid=keyid, profile=profile) if not group: log.error('Group %s does not exist', group_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_group_policy(group_name, policy_name, policy_json) if created: log.info('Created policy for IAM group %s.', group_name) return True log.error('Could not create policy for IAM group %s', group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy for IAM group %s', group_name) return False def delete_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group_policy mygroup mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_group_policy( group_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_group_policy(group_name, policy_name) log.info('Successfully deleted policy %s for IAM group %s.', policy_name, group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM group %s.', policy_name, group_name) return False def get_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group_policy mygroup policyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group_policy(group_name, policy_name) log.debug('info for group policy is : %s', info) if not info: return False info = info.get_group_policy_response.get_group_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_all_groups(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM group details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_groups ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _groups = conn.get_all_groups(path_prefix=path_prefix) groups = _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) while marker: _groups = conn.get_all_groups(path_prefix=path_prefix, marker=marker) groups = groups + _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) return groups def get_all_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.get_all_instance_profiles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) marker = False profiles = [] while marker is not None: marker = marker if marker else None p = conn.list_instance_profiles(path_prefix=path_prefix, marker=marker) res = p.list_instance_profiles_response.list_instance_profiles_result profiles += res.instance_profiles marker = getattr(res, 'marker', None) return profiles def list_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' List all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.list_instance_profiles ''' p = get_all_instance_profiles(path_prefix, region, key, keyid, profile) return [i['instance_profile_name'] for i in p] def get_all_group_policies(group_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a group. CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_group_policies mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False try: response = conn.get_all_group_policies(group_name) _list = response.list_group_policies_response.list_group_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def delete_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _group = get_group( group_name, region, key, keyid, profile ) if not _group: return True try: conn.delete_group(group_name) log.info('Successfully deleted IAM group %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM group %s.', group_name) return False def create_login_profile(user_name, password, region=None, key=None, keyid=None, profile=None): ''' Creates a login profile for the specified user, give the user the ability to access AWS services and the AWS Management Console. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_login_profile user_name password ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.create_login_profile(user_name, password) log.info('Created profile for IAM user %s.', user_name) return info except boto.exception.BotoServerError as e: log.debug(e) if 'Conflict' in e: log.info('Profile already exists for IAM user %s.', user_name) return 'Conflict' log.error('Failed to update profile for IAM user %s.', user_name) return False def delete_login_profile(user_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a login profile for the specified user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_login_profile user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.delete_login_profile(user_name) log.info('Deleted login profile for IAM user %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Login profile already deleted for IAM user %s.', user_name) return True log.error('Failed to delete login profile for IAM user %s.', user_name) return False def get_all_mfa_devices(user_name, region=None, key=None, keyid=None, profile=None): ''' Get all MFA devices associated with an IAM user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_mfa_devices user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: result = conn.get_all_mfa_devices(user_name) devices = result['list_mfa_devices_response']['list_mfa_devices_result']['mfa_devices'] return devices except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Could not find IAM user %s.', user_name) return [] log.error('Failed to get all MFA devices for IAM user %s.', user_name) return False def deactivate_mfa_device(user_name, serial, region=None, key=None, keyid=None, profile=None): ''' Deactivates the specified MFA device and removes it from association with the user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.deactivate_mfa_device user_name serial_num ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.deactivate_mfa_device(user_name, serial) log.info('Deactivated MFA device %s for IAM user %s.', serial, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('MFA device %s not associated with IAM user %s.', serial, user_name) return True log.error('Failed to deactivate MFA device %s for IAM user %s.', serial, user_name) return False def delete_virtual_mfa_device(serial, region=None, key=None, keyid=None, profile=None): ''' Deletes the specified virtual MFA device. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_virtual_mfa_device serial_num ''' conn = __utils__['boto3.get_connection_func']('iam')() try: conn.delete_virtual_mfa_device(SerialNumber=serial) log.info('Deleted virtual MFA device %s.', serial) return True except botocore.exceptions.ClientError as e: log.debug(e) if 'NoSuchEntity' in six.text_type(e): log.info('Virtual MFA device %s not found.', serial) return True log.error('Failed to delete virtual MFA device %s.', serial) return False def update_account_password_policy(allow_users_to_change_password=None, hard_expiry=None, max_password_age=None, minimum_password_length=None, password_reuse_prevention=None, require_lowercase_characters=None, require_numbers=None, require_symbols=None, require_uppercase_characters=None, region=None, key=None, keyid=None, profile=None): ''' Update the password policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_account_password_policy True ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.update_account_password_policy(allow_users_to_change_password, hard_expiry, max_password_age, minimum_password_length, password_reuse_prevention, require_lowercase_characters, require_numbers, require_symbols, require_uppercase_characters) log.info('The password policy has been updated.') return True except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy' log.error(msg) return False def get_account_policy(region=None, key=None, keyid=None, profile=None): ''' Get account policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_account_password_policy() return info.get_account_password_policy_response.get_account_password_policy_result.password_policy except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy.' log.error(msg) return False def create_role(name, policy_document=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Create an instance role. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if role_exists(name, region, key, keyid, profile): return True if not policy_document: policy_document = None try: conn.create_role(name, assume_role_policy_document=policy_document, path=path) log.info('Created IAM role %s.', name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to create IAM role %s.', name) return False def delete_role(name, region=None, key=None, keyid=None, profile=None): ''' Delete an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(name, region, key, keyid, profile): return True try: conn.delete_role(name) log.info('Deleted %s IAM role.', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s IAM role.', name) return False def profile_associated(role_name, profile_name, region, key, keyid, profile): ''' Check to see if an instance profile is associated with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.profile_associated myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # The IAM module of boto doesn't return objects. Instead you need to grab # values through its properties. Sigh. try: profiles = conn.list_instance_profiles_for_role(role_name) except boto.exception.BotoServerError as e: log.debug(e) return False profiles = profiles.list_instance_profiles_for_role_response profiles = profiles.list_instance_profiles_for_role_result profiles = profiles.instance_profiles for profile in profiles: if profile.instance_profile_name == profile_name: return True return False def associate_profile_to_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Associate an instance profile with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.associate_profile_to_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if associated: return True else: try: conn.add_role_to_instance_profile(profile_name, role_name) log.info('Added %s instance profile to IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add %s instance profile to IAM role %s', profile_name, role_name) return False def disassociate_profile_from_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Disassociate an instance profile from an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.disassociate_profile_from_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if not associated: return True else: try: conn.remove_role_from_instance_profile(profile_name, role_name) log.info('Removed %s instance profile from IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove %s instance profile from IAM role %s.', profile_name, role_name) return False def list_role_policies(role_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_role_policies myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_role_policies(role_name) _list = response.list_role_policies_response.list_role_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def get_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.get_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: _policy = conn.get_role_policy(role_name, policy_name) # I _hate_ you for not giving me an object boto. _policy = _policy.get_role_policy_response.policy_document # Policy is url encoded _policy = _unquote(_policy) _policy = salt.utils.json.loads(_policy, object_pairs_hook=odict.OrderedDict) return _policy except boto.exception.BotoServerError: return {} def create_role_policy(role_name, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Create or modify a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role_policy myirole mypolicy '{"MyPolicy": "Statement": [{"Action": ["sqs:*"], "Effect": "Allow", "Resource": ["arn:aws:sqs:*:*:*"], "Sid": "MyPolicySqs1"}]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) mode = 'create' if _policy: if _policy == policy: return True mode = 'modify' if isinstance(policy, six.string_types): policy = salt.utils.json.loads(policy, object_pairs_hook=odict.OrderedDict) try: _policy = salt.utils.json.dumps(policy) conn.put_role_policy(role_name, policy_name, _policy) if mode == 'create': msg = 'Successfully added policy %s to IAM role %s.' else: msg = 'Successfully modified policy %s for IAM role %s.' log.info(msg, policy_name, role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to %s policy %s for IAM role %s.', mode, policy_name, role_name) return False def delete_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) if not _policy: return True try: conn.delete_role_policy(role_name, policy_name) log.info('Successfully deleted policy %s for IAM role %s.', policy_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM role %s.', policy_name, role_name) return False def update_assume_role_policy(role_name, policy_document, region=None, key=None, keyid=None, profile=None): ''' Update an assume role policy for a role. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_assume_role_policy myrole '{"Statement":"..."}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(policy_document, six.string_types): policy_document = salt.utils.json.loads(policy_document, object_pairs_hook=odict.OrderedDict) try: _policy_document = salt.utils.json.dumps(policy_document) conn.update_assume_role_policy(role_name, _policy_document) log.info('Successfully updated assume role policy for IAM role %s.', role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to update assume role policy for IAM role %s.', role_name) return False def build_policy(region=None, key=None, keyid=None, profile=None): ''' Build a default assume role policy. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.build_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if hasattr(conn, 'build_policy'): policy = salt.utils.json.loads(conn.build_policy()) elif hasattr(conn, '_build_policy'): policy = salt.utils.json.loads(conn._build_policy()) else: return {} # The format we get from build_policy isn't going to be what we get back # from AWS for the exact same policy. AWS converts single item list values # into strings, so let's do the same here. for key, policy_val in policy.items(): for statement in policy_val: if (isinstance(statement['Action'], list) and len(statement['Action']) == 1): statement['Action'] = statement['Action'][0] if (isinstance(statement['Principal']['Service'], list) and len(statement['Principal']['Service']) == 1): statement['Principal']['Service'] = statement['Principal']['Service'][0] # build_policy doesn't add a version field, which AWS is going to set to a # default value, when we get it back, so let's set it. policy['Version'] = '2008-10-17' return policy def get_account_id(region=None, key=None, keyid=None, profile=None): ''' Get a the AWS account id associated with the used credentials. CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_id ''' cache_key = 'boto_iam.account_id' if cache_key not in __context__: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_user() # The get_user call returns an user ARN: # arn:aws:iam::027050522557:user/salt-test arn = ret['get_user_response']['get_user_result']['user']['arn'] account_id = arn.split(':')[4] except boto.exception.BotoServerError: # If call failed, then let's try to get the ARN from the metadata timeout = boto.config.getfloat( 'Boto', 'metadata_service_timeout', 1.0 ) attempts = boto.config.getint( 'Boto', 'metadata_service_num_attempts', 1 ) identity = boto.utils.get_instance_identity( timeout=timeout, num_retries=attempts ) try: account_id = identity['document']['accountId'] except KeyError: log.error('Failed to get account id from instance_identity in' ' boto_iam.get_account_id.') __context__[cache_key] = account_id return __context__[cache_key] def get_all_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM user details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_users ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _users = conn.get_all_users(path_prefix=path_prefix) users = _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) while marker: _users = conn.get_all_users(path_prefix=path_prefix, marker=marker) users = users + _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) return users def get_all_user_policies(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all user policies. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_user_policies myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_all_user_policies(user_name, marker, max_items) if not info: return False _list = info.list_user_policies_response.list_user_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policies for user %s.', user_name) return False def get_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user_policy myuser mypolicyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user_policy(user_name, policy_name) log.debug('Info for IAM user %s policy %s: %s.', user_name, policy_name, info) if not info: return False info = info.get_user_policy_response.get_user_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policy %s for IAM user %s.', policy_name, user_name) return False def put_user_policy(user_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_user_policy myuser policyname policyrules ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_user_policy(user_name, policy_name, policy_json) if created: log.info('Created policy %s for IAM user %s.', policy_name, user_name) return True log.error('Could not create policy %s for IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy %s for IAM user %s.', policy_name, user_name) return False def delete_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user_policy myuser mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_user_policy( user_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_user_policy(user_name, policy_name) log.info('Successfully deleted policy %s for IAM user %s.', policy_name, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM user %s.', policy_name, user_name) return False def upload_server_cert(cert_name, cert_body, private_key, cert_chain=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Upload a certificate to Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.upload_server_cert mycert_name crt priv_key :param cert_name: The name for the server certificate. Do not include the path in this value. :param cert_body: The contents of the public key certificate in PEM-encoded format. :param private_key: The contents of the private key in PEM-encoded format. :param cert_chain: The contents of the certificate chain. This is typically a concatenation of the PEM-encoded public key certificates of the chain. :param path: The path for the server certificate. :param region: The name of the region to connect to. :param key: The key to be used in order to connect :param keyid: The keyid to be used in order to connect :param profile: The profile that contains a dict of region, key, keyid :return: True / False ''' exists = get_server_certificate(cert_name, region, key, keyid, profile) if exists: return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.upload_server_cert(cert_name, cert_body, private_key, cert_chain) log.info('Created certificate %s.', cert_name) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to failed to create certificate %s.', cert_name) return False def list_server_certificates(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Lists the server certificates stored in IAM that have the specified path prefix. .. versionadded:: ??? :param path_prefix: The path prefix for filtering the results. For example: /company/servercerts would get all server certificates for which the path starts with /company/servercerts . This parameter is optional. If it is not included, it defaults to a slash (/), listing all server certificates. This parameter allows (per its regex pattern) a string of characters consisting of either a forward slash (/) by itself or a string that must begin and end with forward slashes. In addition, it can contain any ASCII character from the ! (u0021) through the DEL character (u007F), including most punctuation characters, digits, and upper and lowercased letters. CLI Example: .. code-block:: bash salt myminion boto_iam.list_server_certificates path_prefix=/somepath/ ''' retries = 10 sleep = 6 conn = __utils__['boto3.get_connection']('iam', region=region, key=key, keyid=keyid, profile=profile) Items = [] while retries: try: log.debug('Garnering list of IAM Server Certificates') IsTruncated = True while IsTruncated: kwargs = {'PathPrefix': path_prefix} ret = conn.list_server_certificates(**kwargs) Items += ret.get('ServerCertificateMetadataList', []) IsTruncated = ret.get('IsTruncated') kwargs.update({'Marker': ret.get('Marker')}) return Items except botocore.exceptions.ParamValidationError as err: raise SaltInvocationError(str(err)) except botocore.exceptions.ClientError as err: if retries and jmespath.search('Error.Code', err.response) == 'Throttling': retries -= 1 log.debug('Throttled by AWS API, retrying in %s seconds...', sleep) time.sleep(sleep) continue log.error('Failed to list IAM Server Certificates: %s', err.message) return None def get_server_certificate(cert_name, region=None, key=None, keyid=None, profile=None): ''' Returns certificate information from Amazon .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_server_certificate mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_server_certificate(cert_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get certificate %s information.', cert_name) return False def delete_server_cert(cert_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a certificate from Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_server_cert mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_server_cert(cert_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete certificate %s.', cert_name) return False def export_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM user details. Produces results that can be used to create an sls file. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.export_users --out=txt | sed "s/local: //" > iam_users.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() users = get_all_users(path_prefix, region, key, keyid, profile) for user in users: name = user.user_name _policies = conn.get_all_user_policies(name, max_items=100) _policies = _policies.list_user_policies_response.list_user_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_user_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_user_policy_response.get_user_policy_result.policy_document )) policies[policy_name] = _policy user_sls = [] user_sls.append({"name": name}) user_sls.append({"policies": policies}) user_sls.append({"path": user.path}) results["manage user " + name] = {"boto_iam.user_present": user_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def export_roles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM role details. Produces results that can be used to create an sls file. CLI Example: salt-call boto_iam.export_roles --out=txt | sed "s/local: //" > iam_roles.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() roles = get_all_roles(path_prefix, region, key, keyid, profile) for role in roles: name = role.role_name _policies = conn.list_role_policies(name, max_items=100) _policies = _policies.list_role_policies_response.list_role_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_role_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_role_policy_response.get_role_policy_result.policy_document )) policies[policy_name] = _policy role_sls = [] role_sls.append({"name": name}) role_sls.append({"policies": policies}) role_sls.append({'policy_document': salt.utils.json.loads(_unquote(role.assume_role_policy_document))}) role_sls.append({"path": role.path}) results["manage role " + name] = {"boto_iam_role.present": role_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def _get_policy_arn(name, region=None, key=None, keyid=None, profile=None): if name.startswith('arn:aws:iam:'): return name account_id = get_account_id( region=region, key=key, keyid=keyid, profile=profile ) return 'arn:aws:iam::{0}:policy/{1}'.format(account_id, name) def policy_exists(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return True except boto.exception.BotoServerError: return False def get_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return ret.get('get_policy_response', {}).get('get_policy_result', {}) except boto.exception.BotoServerError: return None def create_policy(policy_name, policy_document, path=None, description=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in 'path', 'description': if locals()[arg] is not None: params[arg] = locals()[arg] if policy_exists(policy_name, region, key, keyid, profile): return True try: conn.create_policy(policy_name, policy_document, **params) log.info('Created IAM policy %s.', policy_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s.', policy_name) return False return True def delete_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_exists(policy_arn, region, key, keyid, profile): return True try: conn.delete_policy(policy_arn) log.info('Deleted %s policy.', policy_name) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete %s policy: %s.', policy_name, aws.get('message')) return False return True def list_policies(region=None, key=None, keyid=None, profile=None): ''' List policies. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policies ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: policies = [] for ret in __utils__['boto.paged_call'](conn.list_policies): policies.append(ret.get('list_policies_response', {}).get('list_policies_result', {}).get('policies')) return policies except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to list policy versions.' log.error(msg) return [] def policy_version_exists(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.get_policy_version(policy_arn, version_id) return True except boto.exception.BotoServerError: return False def get_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy_version(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile), version_id) retval = ret.get('get_policy_version_response', {}).get('get_policy_version_result', {}).get('policy_version', {}) retval['document'] = _unquote(retval.get('document')) return {'policy_version': retval} except boto.exception.BotoServerError: return None def create_policy_version(policy_name, policy_document, set_as_default=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy version. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy_version mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in ('set_as_default',): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.create_policy_version(policy_arn, policy_document, **params) vid = ret.get('create_policy_version_response', {}).get('create_policy_version_result', {}).get('policy_version', {}).get('version_id') log.info('Created IAM policy %s version %s.', policy_name, vid) return {'created': True, 'version_id': vid} except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s version %s.', policy_name, vid) return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Delete a policy version. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_version_exists(policy_arn, version_id, region, key, keyid, profile): return True try: conn.delete_policy_version(policy_arn, version_id) log.info('Deleted IAM policy %s version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete IAM policy %s version %s: %s', policy_name, version_id, aws.get('message')) return False return True def list_policy_versions(policy_name, region=None, key=None, keyid=None, profile=None): ''' List versions of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policy_versions mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.list_policy_versions(policy_arn) return ret.get('list_policy_versions_response', {}).get('list_policy_versions_result', {}).get('versions') except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list versions for IAM policy %s.', policy_name) return [] def set_default_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Set the default version of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.set_default_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.set_default_policy_version(policy_arn, version_id) log.info('Set %s policy to version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to set %s policy to version %s: %s', policy_name, version_id, aws.get('message')) return False return True def attach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_user_policy(policy_arn, user_name) log.info('Attached policy %s to IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach %s policy to IAM user %s.', policy_name, user_name) return False return True def detach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_user_policy(policy_arn, user_name) log.info('Detached %s policy from IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach %s policy from IAM user %s.', policy_name, user_name) return False return True def attach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_group_policy(policy_arn, group_name) log.info('Attached policy %s to IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM group %s.', policy_name, group_name) return False return True def detach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_group_policy(policy_arn, group_name) log.info('Detached policy %s from IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM group %s.', policy_name, group_name) return False return True def attach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_role_policy(policy_arn, role_name) log.info('Attached policy %s to IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM role %s.', policy_name, role_name) return False return True def detach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_role_policy(policy_arn, role_name) log.info('Detached policy %s from IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM role %s.', policy_name, role_name) return False return True def list_entities_for_policy(policy_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities that a policy is attached to. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 params = {} for arg in ('path_prefix', 'entity_filter'): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) while retries: try: allret = { 'policy_groups': [], 'policy_users': [], 'policy_roles': [], } for ret in __utils__['boto.paged_call'](conn.list_entities_for_policy, policy_arn=policy_arn, **params): for k, v in six.iteritems(allret): v.extend(ret.get('list_entities_for_policy_response', {}).get('list_entities_for_policy_result', {}).get(k)) return allret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('Failed to list entities for IAM policy %s: %s', policy_name, e.message) return {} return {} def list_attached_user_policies(user_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given user. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'UserName': user_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedUserPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_user_policies_response', {}).get('list_attached_user_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM user %s.', user_name) return [] def list_attached_group_policies(group_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given group. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'GroupName': group_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedGroupPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_group_policies_response', {}).get('list_attached_group_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM group %s.', group_name) return [] def list_attached_role_policies(role_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'RoleName': role_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedRolePolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_role_policies_response', {}).get('list_attached_role_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM role %s.', role_name) return [] def create_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Create SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.create_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_saml_provider(saml_metadata_document, name) log.info('Successfully created %s SAML provider.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to create SAML provider %s.', name) return False def get_saml_provider_arn(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider_arn my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_saml_providers() for saml_provider in response.list_saml_providers_response.list_saml_providers_result.saml_provider_list: if saml_provider['arn'].endswith(':saml-provider/' + name): return saml_provider['arn'] return False except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to get ARN of SAML provider %s.', name) return False def delete_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Delete SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.delete_saml_provider my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return True conn.delete_saml_provider(saml_provider_arn) log.info('Successfully deleted SAML provider %s.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete SAML provider %s.', name) return False def list_saml_providers(region=None, key=None, keyid=None, profile=None): ''' List SAML providers. CLI Example: .. code-block:: bash salt myminion boto_iam.list_saml_providers ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: providers = [] info = conn.list_saml_providers() for arn in info['list_saml_providers_response']['list_saml_providers_result']['saml_provider_list']: providers.append(arn['arn'].rsplit('/', 1)[1]) return providers except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get list of SAML providers.') return False def get_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider document. CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider arn ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: provider = conn.get_saml_provider(name) return provider['get_saml_provider_response']['get_saml_provider_result']['saml_metadata_document'] except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get SAML provider document %s.', name) return False def update_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Update SAML provider. CLI Example: .. code-block:: bash salt myminion boto_iam.update_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return False if conn.update_saml_provider(name, saml_metadata_document): return True return False except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to update SAML provider %s.', name) return False
saltstack/salt
salt/modules/boto_iam.py
get_all_users
python
def get_all_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM user details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_users ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _users = conn.get_all_users(path_prefix=path_prefix) users = _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) while marker: _users = conn.get_all_users(path_prefix=path_prefix, marker=marker) users = users + _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) return users
Get and return all IAM user details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_users
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iam.py#L1345-L1370
null
# -*- coding: utf-8 -*- ''' Connection module for Amazon IAM .. versionadded:: 2014.7.0 :configuration: This module accepts explicit iam 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 iam.keyid: GKTADJGHEIQSXMKKRBJ08H iam.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs iam.region: 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: boto ''' # keep lint from choking on _get_conn and _cache_id #pylint: disable=E0602 # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import salt libs from salt.ext import six import salt.utils.compat import salt.utils.json import salt.utils.odict as odict import salt.utils.versions from salt.exceptions import SaltInvocationError # Import third party libs # pylint: disable=unused-import from salt.ext.six.moves.urllib.parse import unquote as _unquote # pylint: disable=no-name-in-module try: import boto import boto.iam import boto3 import botocore logging.getLogger('boto').setLevel(logging.CRITICAL) logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=unused-import log = logging.getLogger(__name__) def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'iam', pack=__salt__) def instance_profile_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an instance profile exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: # Boto weirdly returns an exception here if an instance profile doesn't # exist. conn.get_instance_profile(name) return True except boto.exception.BotoServerError: return False def create_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Create an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.create_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if instance_profile_exists(name, region, key, keyid, profile): return True try: # This call returns an instance profile if successful and an exception # if not. It's annoying. conn.create_instance_profile(name) log.info('Created %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create %s instance profile.', name) return False return True def delete_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Delete an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not instance_profile_exists(name, region, key, keyid, profile): return True try: conn.delete_instance_profile(name) log.info('Deleted %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s instance profile.', name) return False return True def role_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an IAM role exists. CLI Example: .. code-block:: bash salt myminion boto_iam.role_exists myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_role(name) return True except boto.exception.BotoServerError: return False def describe_role(name, region=None, key=None, keyid=None, profile=None): ''' Get information for a role. CLI Example: .. code-block:: bash salt myminion boto_iam.describe_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_role(name) if not info: return False role = info.get_role_response.get_role_result.role role['assume_role_policy_document'] = salt.utils.json.loads(_unquote( role.assume_role_policy_document )) # If Sid wasn't defined by the user, boto will still return a Sid in # each policy. To properly check idempotently, let's remove the Sid # from the return if it's not actually set. for policy_key, policy in role['assume_role_policy_document'].items(): if policy_key == 'Statement': for val in policy: if 'Sid' in val and not val['Sid']: del val['Sid'] return role except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get %s information.', name) return False def create_user(user_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_user myuser ''' if not path: path = '/' if get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_user(user_name, path) log.info('Created IAM user : %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM user %s.', user_name) return False def get_all_access_keys(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all access keys from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_access_keys myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.get_all_access_keys(user_name, marker, max_items) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get access keys for IAM user %s.', user_name) return six.text_type(e) def create_access_key(user_name, region=None, key=None, keyid=None, profile=None): ''' Create access key id for a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.create_access_key(user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create access key.') return six.text_type(e) def delete_access_key(access_key_id, user_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete access key id from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_access_key(access_key_id, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete access key id %s.', access_key_id) return six.text_type(e) def delete_user(user_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user myuser ''' if not get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.delete_user(user_name) log.info('Deleted IAM user : %s .', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM user %s', user_name) return six.text_type(e) def get_user(user_name=None, region=None, key=None, keyid=None, profile=None): ''' Get user information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user(user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM user %s info.', user_name) return False def create_group(group_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_group group ''' if not path: path = '/' if get_group(group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_group(group_name, path) log.info('Created IAM group : %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM group %s.', group_name) return False def get_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group(group_name, max_items=1) if not info: return False return info['get_group_response']['get_group_result']['group'] except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_group_members(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: marker = None truncated = True users = [] while truncated: info = conn.get_group(group_name, marker=marker, max_items=1000) if not info: return False truncated = bool(info['get_group_response']['get_group_result']['is_truncated']) if truncated and 'marker' in info['get_group_response']['get_group_result']: marker = info['get_group_response']['get_group_result']['marker'] else: marker = None truncated = False users += info['get_group_response']['get_group_result']['users'] return users except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get members for IAM group %s.', group_name) return False def add_user_to_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Add user to group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.add_user_to_group myuser mygroup ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('Username : %s does not exist.', user_name) return False if user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.add_user_to_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add IAM user %s to group %s.', user_name, group_name) return False def user_exists_in_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Check if user exists in group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.user_exists_in_group myuser mygroup ''' # TODO this should probably use boto.iam.get_groups_for_user users = get_group_members( group_name=group_name, region=region, key=key, keyid=keyid, profile=profile ) if users: for _user in users: if user_name == _user['user_name']: log.debug('IAM user %s is already in IAM group %s.', user_name, group_name) return True return False def remove_user_from_group(group_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Remove user from group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.remove_user_from_group mygroup myuser ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist.', user_name) return False if not user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.remove_user_from_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove IAM user %s from group %s', user_name, group_name) return False def put_group_policy(group_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_group_policy mygroup policyname policyrules ''' group = get_group(group_name, region=region, key=key, keyid=keyid, profile=profile) if not group: log.error('Group %s does not exist', group_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_group_policy(group_name, policy_name, policy_json) if created: log.info('Created policy for IAM group %s.', group_name) return True log.error('Could not create policy for IAM group %s', group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy for IAM group %s', group_name) return False def delete_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group_policy mygroup mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_group_policy( group_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_group_policy(group_name, policy_name) log.info('Successfully deleted policy %s for IAM group %s.', policy_name, group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM group %s.', policy_name, group_name) return False def get_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group_policy mygroup policyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group_policy(group_name, policy_name) log.debug('info for group policy is : %s', info) if not info: return False info = info.get_group_policy_response.get_group_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_all_groups(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM group details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_groups ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _groups = conn.get_all_groups(path_prefix=path_prefix) groups = _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) while marker: _groups = conn.get_all_groups(path_prefix=path_prefix, marker=marker) groups = groups + _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) return groups def get_all_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.get_all_instance_profiles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) marker = False profiles = [] while marker is not None: marker = marker if marker else None p = conn.list_instance_profiles(path_prefix=path_prefix, marker=marker) res = p.list_instance_profiles_response.list_instance_profiles_result profiles += res.instance_profiles marker = getattr(res, 'marker', None) return profiles def list_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' List all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.list_instance_profiles ''' p = get_all_instance_profiles(path_prefix, region, key, keyid, profile) return [i['instance_profile_name'] for i in p] def get_all_group_policies(group_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a group. CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_group_policies mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False try: response = conn.get_all_group_policies(group_name) _list = response.list_group_policies_response.list_group_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def delete_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _group = get_group( group_name, region, key, keyid, profile ) if not _group: return True try: conn.delete_group(group_name) log.info('Successfully deleted IAM group %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM group %s.', group_name) return False def create_login_profile(user_name, password, region=None, key=None, keyid=None, profile=None): ''' Creates a login profile for the specified user, give the user the ability to access AWS services and the AWS Management Console. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_login_profile user_name password ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.create_login_profile(user_name, password) log.info('Created profile for IAM user %s.', user_name) return info except boto.exception.BotoServerError as e: log.debug(e) if 'Conflict' in e: log.info('Profile already exists for IAM user %s.', user_name) return 'Conflict' log.error('Failed to update profile for IAM user %s.', user_name) return False def delete_login_profile(user_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a login profile for the specified user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_login_profile user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.delete_login_profile(user_name) log.info('Deleted login profile for IAM user %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Login profile already deleted for IAM user %s.', user_name) return True log.error('Failed to delete login profile for IAM user %s.', user_name) return False def get_all_mfa_devices(user_name, region=None, key=None, keyid=None, profile=None): ''' Get all MFA devices associated with an IAM user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_mfa_devices user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: result = conn.get_all_mfa_devices(user_name) devices = result['list_mfa_devices_response']['list_mfa_devices_result']['mfa_devices'] return devices except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Could not find IAM user %s.', user_name) return [] log.error('Failed to get all MFA devices for IAM user %s.', user_name) return False def deactivate_mfa_device(user_name, serial, region=None, key=None, keyid=None, profile=None): ''' Deactivates the specified MFA device and removes it from association with the user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.deactivate_mfa_device user_name serial_num ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.deactivate_mfa_device(user_name, serial) log.info('Deactivated MFA device %s for IAM user %s.', serial, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('MFA device %s not associated with IAM user %s.', serial, user_name) return True log.error('Failed to deactivate MFA device %s for IAM user %s.', serial, user_name) return False def delete_virtual_mfa_device(serial, region=None, key=None, keyid=None, profile=None): ''' Deletes the specified virtual MFA device. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_virtual_mfa_device serial_num ''' conn = __utils__['boto3.get_connection_func']('iam')() try: conn.delete_virtual_mfa_device(SerialNumber=serial) log.info('Deleted virtual MFA device %s.', serial) return True except botocore.exceptions.ClientError as e: log.debug(e) if 'NoSuchEntity' in six.text_type(e): log.info('Virtual MFA device %s not found.', serial) return True log.error('Failed to delete virtual MFA device %s.', serial) return False def update_account_password_policy(allow_users_to_change_password=None, hard_expiry=None, max_password_age=None, minimum_password_length=None, password_reuse_prevention=None, require_lowercase_characters=None, require_numbers=None, require_symbols=None, require_uppercase_characters=None, region=None, key=None, keyid=None, profile=None): ''' Update the password policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_account_password_policy True ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.update_account_password_policy(allow_users_to_change_password, hard_expiry, max_password_age, minimum_password_length, password_reuse_prevention, require_lowercase_characters, require_numbers, require_symbols, require_uppercase_characters) log.info('The password policy has been updated.') return True except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy' log.error(msg) return False def get_account_policy(region=None, key=None, keyid=None, profile=None): ''' Get account policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_account_password_policy() return info.get_account_password_policy_response.get_account_password_policy_result.password_policy except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy.' log.error(msg) return False def create_role(name, policy_document=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Create an instance role. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if role_exists(name, region, key, keyid, profile): return True if not policy_document: policy_document = None try: conn.create_role(name, assume_role_policy_document=policy_document, path=path) log.info('Created IAM role %s.', name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to create IAM role %s.', name) return False def delete_role(name, region=None, key=None, keyid=None, profile=None): ''' Delete an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(name, region, key, keyid, profile): return True try: conn.delete_role(name) log.info('Deleted %s IAM role.', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s IAM role.', name) return False def profile_associated(role_name, profile_name, region, key, keyid, profile): ''' Check to see if an instance profile is associated with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.profile_associated myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # The IAM module of boto doesn't return objects. Instead you need to grab # values through its properties. Sigh. try: profiles = conn.list_instance_profiles_for_role(role_name) except boto.exception.BotoServerError as e: log.debug(e) return False profiles = profiles.list_instance_profiles_for_role_response profiles = profiles.list_instance_profiles_for_role_result profiles = profiles.instance_profiles for profile in profiles: if profile.instance_profile_name == profile_name: return True return False def associate_profile_to_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Associate an instance profile with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.associate_profile_to_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if associated: return True else: try: conn.add_role_to_instance_profile(profile_name, role_name) log.info('Added %s instance profile to IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add %s instance profile to IAM role %s', profile_name, role_name) return False def disassociate_profile_from_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Disassociate an instance profile from an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.disassociate_profile_from_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if not associated: return True else: try: conn.remove_role_from_instance_profile(profile_name, role_name) log.info('Removed %s instance profile from IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove %s instance profile from IAM role %s.', profile_name, role_name) return False def list_role_policies(role_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_role_policies myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_role_policies(role_name) _list = response.list_role_policies_response.list_role_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def get_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.get_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: _policy = conn.get_role_policy(role_name, policy_name) # I _hate_ you for not giving me an object boto. _policy = _policy.get_role_policy_response.policy_document # Policy is url encoded _policy = _unquote(_policy) _policy = salt.utils.json.loads(_policy, object_pairs_hook=odict.OrderedDict) return _policy except boto.exception.BotoServerError: return {} def create_role_policy(role_name, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Create or modify a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role_policy myirole mypolicy '{"MyPolicy": "Statement": [{"Action": ["sqs:*"], "Effect": "Allow", "Resource": ["arn:aws:sqs:*:*:*"], "Sid": "MyPolicySqs1"}]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) mode = 'create' if _policy: if _policy == policy: return True mode = 'modify' if isinstance(policy, six.string_types): policy = salt.utils.json.loads(policy, object_pairs_hook=odict.OrderedDict) try: _policy = salt.utils.json.dumps(policy) conn.put_role_policy(role_name, policy_name, _policy) if mode == 'create': msg = 'Successfully added policy %s to IAM role %s.' else: msg = 'Successfully modified policy %s for IAM role %s.' log.info(msg, policy_name, role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to %s policy %s for IAM role %s.', mode, policy_name, role_name) return False def delete_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) if not _policy: return True try: conn.delete_role_policy(role_name, policy_name) log.info('Successfully deleted policy %s for IAM role %s.', policy_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM role %s.', policy_name, role_name) return False def update_assume_role_policy(role_name, policy_document, region=None, key=None, keyid=None, profile=None): ''' Update an assume role policy for a role. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_assume_role_policy myrole '{"Statement":"..."}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(policy_document, six.string_types): policy_document = salt.utils.json.loads(policy_document, object_pairs_hook=odict.OrderedDict) try: _policy_document = salt.utils.json.dumps(policy_document) conn.update_assume_role_policy(role_name, _policy_document) log.info('Successfully updated assume role policy for IAM role %s.', role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to update assume role policy for IAM role %s.', role_name) return False def build_policy(region=None, key=None, keyid=None, profile=None): ''' Build a default assume role policy. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.build_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if hasattr(conn, 'build_policy'): policy = salt.utils.json.loads(conn.build_policy()) elif hasattr(conn, '_build_policy'): policy = salt.utils.json.loads(conn._build_policy()) else: return {} # The format we get from build_policy isn't going to be what we get back # from AWS for the exact same policy. AWS converts single item list values # into strings, so let's do the same here. for key, policy_val in policy.items(): for statement in policy_val: if (isinstance(statement['Action'], list) and len(statement['Action']) == 1): statement['Action'] = statement['Action'][0] if (isinstance(statement['Principal']['Service'], list) and len(statement['Principal']['Service']) == 1): statement['Principal']['Service'] = statement['Principal']['Service'][0] # build_policy doesn't add a version field, which AWS is going to set to a # default value, when we get it back, so let's set it. policy['Version'] = '2008-10-17' return policy def get_account_id(region=None, key=None, keyid=None, profile=None): ''' Get a the AWS account id associated with the used credentials. CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_id ''' cache_key = 'boto_iam.account_id' if cache_key not in __context__: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_user() # The get_user call returns an user ARN: # arn:aws:iam::027050522557:user/salt-test arn = ret['get_user_response']['get_user_result']['user']['arn'] account_id = arn.split(':')[4] except boto.exception.BotoServerError: # If call failed, then let's try to get the ARN from the metadata timeout = boto.config.getfloat( 'Boto', 'metadata_service_timeout', 1.0 ) attempts = boto.config.getint( 'Boto', 'metadata_service_num_attempts', 1 ) identity = boto.utils.get_instance_identity( timeout=timeout, num_retries=attempts ) try: account_id = identity['document']['accountId'] except KeyError: log.error('Failed to get account id from instance_identity in' ' boto_iam.get_account_id.') __context__[cache_key] = account_id return __context__[cache_key] def get_all_roles(path_prefix=None, region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM role details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_roles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _roles = conn.list_roles(path_prefix=path_prefix) roles = _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) while marker: _roles = conn.list_roles(path_prefix=path_prefix, marker=marker) roles = roles + _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) return roles def get_all_user_policies(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all user policies. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_user_policies myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_all_user_policies(user_name, marker, max_items) if not info: return False _list = info.list_user_policies_response.list_user_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policies for user %s.', user_name) return False def get_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user_policy myuser mypolicyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user_policy(user_name, policy_name) log.debug('Info for IAM user %s policy %s: %s.', user_name, policy_name, info) if not info: return False info = info.get_user_policy_response.get_user_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policy %s for IAM user %s.', policy_name, user_name) return False def put_user_policy(user_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_user_policy myuser policyname policyrules ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_user_policy(user_name, policy_name, policy_json) if created: log.info('Created policy %s for IAM user %s.', policy_name, user_name) return True log.error('Could not create policy %s for IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy %s for IAM user %s.', policy_name, user_name) return False def delete_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user_policy myuser mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_user_policy( user_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_user_policy(user_name, policy_name) log.info('Successfully deleted policy %s for IAM user %s.', policy_name, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM user %s.', policy_name, user_name) return False def upload_server_cert(cert_name, cert_body, private_key, cert_chain=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Upload a certificate to Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.upload_server_cert mycert_name crt priv_key :param cert_name: The name for the server certificate. Do not include the path in this value. :param cert_body: The contents of the public key certificate in PEM-encoded format. :param private_key: The contents of the private key in PEM-encoded format. :param cert_chain: The contents of the certificate chain. This is typically a concatenation of the PEM-encoded public key certificates of the chain. :param path: The path for the server certificate. :param region: The name of the region to connect to. :param key: The key to be used in order to connect :param keyid: The keyid to be used in order to connect :param profile: The profile that contains a dict of region, key, keyid :return: True / False ''' exists = get_server_certificate(cert_name, region, key, keyid, profile) if exists: return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.upload_server_cert(cert_name, cert_body, private_key, cert_chain) log.info('Created certificate %s.', cert_name) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to failed to create certificate %s.', cert_name) return False def list_server_certificates(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Lists the server certificates stored in IAM that have the specified path prefix. .. versionadded:: ??? :param path_prefix: The path prefix for filtering the results. For example: /company/servercerts would get all server certificates for which the path starts with /company/servercerts . This parameter is optional. If it is not included, it defaults to a slash (/), listing all server certificates. This parameter allows (per its regex pattern) a string of characters consisting of either a forward slash (/) by itself or a string that must begin and end with forward slashes. In addition, it can contain any ASCII character from the ! (u0021) through the DEL character (u007F), including most punctuation characters, digits, and upper and lowercased letters. CLI Example: .. code-block:: bash salt myminion boto_iam.list_server_certificates path_prefix=/somepath/ ''' retries = 10 sleep = 6 conn = __utils__['boto3.get_connection']('iam', region=region, key=key, keyid=keyid, profile=profile) Items = [] while retries: try: log.debug('Garnering list of IAM Server Certificates') IsTruncated = True while IsTruncated: kwargs = {'PathPrefix': path_prefix} ret = conn.list_server_certificates(**kwargs) Items += ret.get('ServerCertificateMetadataList', []) IsTruncated = ret.get('IsTruncated') kwargs.update({'Marker': ret.get('Marker')}) return Items except botocore.exceptions.ParamValidationError as err: raise SaltInvocationError(str(err)) except botocore.exceptions.ClientError as err: if retries and jmespath.search('Error.Code', err.response) == 'Throttling': retries -= 1 log.debug('Throttled by AWS API, retrying in %s seconds...', sleep) time.sleep(sleep) continue log.error('Failed to list IAM Server Certificates: %s', err.message) return None def get_server_certificate(cert_name, region=None, key=None, keyid=None, profile=None): ''' Returns certificate information from Amazon .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_server_certificate mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_server_certificate(cert_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get certificate %s information.', cert_name) return False def delete_server_cert(cert_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a certificate from Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_server_cert mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_server_cert(cert_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete certificate %s.', cert_name) return False def export_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM user details. Produces results that can be used to create an sls file. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.export_users --out=txt | sed "s/local: //" > iam_users.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() users = get_all_users(path_prefix, region, key, keyid, profile) for user in users: name = user.user_name _policies = conn.get_all_user_policies(name, max_items=100) _policies = _policies.list_user_policies_response.list_user_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_user_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_user_policy_response.get_user_policy_result.policy_document )) policies[policy_name] = _policy user_sls = [] user_sls.append({"name": name}) user_sls.append({"policies": policies}) user_sls.append({"path": user.path}) results["manage user " + name] = {"boto_iam.user_present": user_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def export_roles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM role details. Produces results that can be used to create an sls file. CLI Example: salt-call boto_iam.export_roles --out=txt | sed "s/local: //" > iam_roles.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() roles = get_all_roles(path_prefix, region, key, keyid, profile) for role in roles: name = role.role_name _policies = conn.list_role_policies(name, max_items=100) _policies = _policies.list_role_policies_response.list_role_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_role_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_role_policy_response.get_role_policy_result.policy_document )) policies[policy_name] = _policy role_sls = [] role_sls.append({"name": name}) role_sls.append({"policies": policies}) role_sls.append({'policy_document': salt.utils.json.loads(_unquote(role.assume_role_policy_document))}) role_sls.append({"path": role.path}) results["manage role " + name] = {"boto_iam_role.present": role_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def _get_policy_arn(name, region=None, key=None, keyid=None, profile=None): if name.startswith('arn:aws:iam:'): return name account_id = get_account_id( region=region, key=key, keyid=keyid, profile=profile ) return 'arn:aws:iam::{0}:policy/{1}'.format(account_id, name) def policy_exists(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return True except boto.exception.BotoServerError: return False def get_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return ret.get('get_policy_response', {}).get('get_policy_result', {}) except boto.exception.BotoServerError: return None def create_policy(policy_name, policy_document, path=None, description=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in 'path', 'description': if locals()[arg] is not None: params[arg] = locals()[arg] if policy_exists(policy_name, region, key, keyid, profile): return True try: conn.create_policy(policy_name, policy_document, **params) log.info('Created IAM policy %s.', policy_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s.', policy_name) return False return True def delete_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_exists(policy_arn, region, key, keyid, profile): return True try: conn.delete_policy(policy_arn) log.info('Deleted %s policy.', policy_name) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete %s policy: %s.', policy_name, aws.get('message')) return False return True def list_policies(region=None, key=None, keyid=None, profile=None): ''' List policies. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policies ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: policies = [] for ret in __utils__['boto.paged_call'](conn.list_policies): policies.append(ret.get('list_policies_response', {}).get('list_policies_result', {}).get('policies')) return policies except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to list policy versions.' log.error(msg) return [] def policy_version_exists(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.get_policy_version(policy_arn, version_id) return True except boto.exception.BotoServerError: return False def get_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy_version(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile), version_id) retval = ret.get('get_policy_version_response', {}).get('get_policy_version_result', {}).get('policy_version', {}) retval['document'] = _unquote(retval.get('document')) return {'policy_version': retval} except boto.exception.BotoServerError: return None def create_policy_version(policy_name, policy_document, set_as_default=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy version. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy_version mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in ('set_as_default',): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.create_policy_version(policy_arn, policy_document, **params) vid = ret.get('create_policy_version_response', {}).get('create_policy_version_result', {}).get('policy_version', {}).get('version_id') log.info('Created IAM policy %s version %s.', policy_name, vid) return {'created': True, 'version_id': vid} except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s version %s.', policy_name, vid) return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Delete a policy version. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_version_exists(policy_arn, version_id, region, key, keyid, profile): return True try: conn.delete_policy_version(policy_arn, version_id) log.info('Deleted IAM policy %s version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete IAM policy %s version %s: %s', policy_name, version_id, aws.get('message')) return False return True def list_policy_versions(policy_name, region=None, key=None, keyid=None, profile=None): ''' List versions of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policy_versions mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.list_policy_versions(policy_arn) return ret.get('list_policy_versions_response', {}).get('list_policy_versions_result', {}).get('versions') except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list versions for IAM policy %s.', policy_name) return [] def set_default_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Set the default version of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.set_default_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.set_default_policy_version(policy_arn, version_id) log.info('Set %s policy to version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to set %s policy to version %s: %s', policy_name, version_id, aws.get('message')) return False return True def attach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_user_policy(policy_arn, user_name) log.info('Attached policy %s to IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach %s policy to IAM user %s.', policy_name, user_name) return False return True def detach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_user_policy(policy_arn, user_name) log.info('Detached %s policy from IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach %s policy from IAM user %s.', policy_name, user_name) return False return True def attach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_group_policy(policy_arn, group_name) log.info('Attached policy %s to IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM group %s.', policy_name, group_name) return False return True def detach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_group_policy(policy_arn, group_name) log.info('Detached policy %s from IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM group %s.', policy_name, group_name) return False return True def attach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_role_policy(policy_arn, role_name) log.info('Attached policy %s to IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM role %s.', policy_name, role_name) return False return True def detach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_role_policy(policy_arn, role_name) log.info('Detached policy %s from IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM role %s.', policy_name, role_name) return False return True def list_entities_for_policy(policy_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities that a policy is attached to. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 params = {} for arg in ('path_prefix', 'entity_filter'): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) while retries: try: allret = { 'policy_groups': [], 'policy_users': [], 'policy_roles': [], } for ret in __utils__['boto.paged_call'](conn.list_entities_for_policy, policy_arn=policy_arn, **params): for k, v in six.iteritems(allret): v.extend(ret.get('list_entities_for_policy_response', {}).get('list_entities_for_policy_result', {}).get(k)) return allret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('Failed to list entities for IAM policy %s: %s', policy_name, e.message) return {} return {} def list_attached_user_policies(user_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given user. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'UserName': user_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedUserPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_user_policies_response', {}).get('list_attached_user_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM user %s.', user_name) return [] def list_attached_group_policies(group_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given group. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'GroupName': group_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedGroupPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_group_policies_response', {}).get('list_attached_group_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM group %s.', group_name) return [] def list_attached_role_policies(role_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'RoleName': role_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedRolePolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_role_policies_response', {}).get('list_attached_role_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM role %s.', role_name) return [] def create_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Create SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.create_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_saml_provider(saml_metadata_document, name) log.info('Successfully created %s SAML provider.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to create SAML provider %s.', name) return False def get_saml_provider_arn(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider_arn my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_saml_providers() for saml_provider in response.list_saml_providers_response.list_saml_providers_result.saml_provider_list: if saml_provider['arn'].endswith(':saml-provider/' + name): return saml_provider['arn'] return False except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to get ARN of SAML provider %s.', name) return False def delete_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Delete SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.delete_saml_provider my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return True conn.delete_saml_provider(saml_provider_arn) log.info('Successfully deleted SAML provider %s.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete SAML provider %s.', name) return False def list_saml_providers(region=None, key=None, keyid=None, profile=None): ''' List SAML providers. CLI Example: .. code-block:: bash salt myminion boto_iam.list_saml_providers ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: providers = [] info = conn.list_saml_providers() for arn in info['list_saml_providers_response']['list_saml_providers_result']['saml_provider_list']: providers.append(arn['arn'].rsplit('/', 1)[1]) return providers except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get list of SAML providers.') return False def get_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider document. CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider arn ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: provider = conn.get_saml_provider(name) return provider['get_saml_provider_response']['get_saml_provider_result']['saml_metadata_document'] except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get SAML provider document %s.', name) return False def update_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Update SAML provider. CLI Example: .. code-block:: bash salt myminion boto_iam.update_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return False if conn.update_saml_provider(name, saml_metadata_document): return True return False except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to update SAML provider %s.', name) return False
saltstack/salt
salt/modules/boto_iam.py
get_all_user_policies
python
def get_all_user_policies(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all user policies. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_user_policies myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_all_user_policies(user_name, marker, max_items) if not info: return False _list = info.list_user_policies_response.list_user_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policies for user %s.', user_name) return False
Get all user policies. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_user_policies myuser
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iam.py#L1373-L1395
null
# -*- coding: utf-8 -*- ''' Connection module for Amazon IAM .. versionadded:: 2014.7.0 :configuration: This module accepts explicit iam 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 iam.keyid: GKTADJGHEIQSXMKKRBJ08H iam.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs iam.region: 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: boto ''' # keep lint from choking on _get_conn and _cache_id #pylint: disable=E0602 # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import salt libs from salt.ext import six import salt.utils.compat import salt.utils.json import salt.utils.odict as odict import salt.utils.versions from salt.exceptions import SaltInvocationError # Import third party libs # pylint: disable=unused-import from salt.ext.six.moves.urllib.parse import unquote as _unquote # pylint: disable=no-name-in-module try: import boto import boto.iam import boto3 import botocore logging.getLogger('boto').setLevel(logging.CRITICAL) logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=unused-import log = logging.getLogger(__name__) def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'iam', pack=__salt__) def instance_profile_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an instance profile exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: # Boto weirdly returns an exception here if an instance profile doesn't # exist. conn.get_instance_profile(name) return True except boto.exception.BotoServerError: return False def create_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Create an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.create_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if instance_profile_exists(name, region, key, keyid, profile): return True try: # This call returns an instance profile if successful and an exception # if not. It's annoying. conn.create_instance_profile(name) log.info('Created %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create %s instance profile.', name) return False return True def delete_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Delete an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not instance_profile_exists(name, region, key, keyid, profile): return True try: conn.delete_instance_profile(name) log.info('Deleted %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s instance profile.', name) return False return True def role_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an IAM role exists. CLI Example: .. code-block:: bash salt myminion boto_iam.role_exists myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_role(name) return True except boto.exception.BotoServerError: return False def describe_role(name, region=None, key=None, keyid=None, profile=None): ''' Get information for a role. CLI Example: .. code-block:: bash salt myminion boto_iam.describe_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_role(name) if not info: return False role = info.get_role_response.get_role_result.role role['assume_role_policy_document'] = salt.utils.json.loads(_unquote( role.assume_role_policy_document )) # If Sid wasn't defined by the user, boto will still return a Sid in # each policy. To properly check idempotently, let's remove the Sid # from the return if it's not actually set. for policy_key, policy in role['assume_role_policy_document'].items(): if policy_key == 'Statement': for val in policy: if 'Sid' in val and not val['Sid']: del val['Sid'] return role except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get %s information.', name) return False def create_user(user_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_user myuser ''' if not path: path = '/' if get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_user(user_name, path) log.info('Created IAM user : %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM user %s.', user_name) return False def get_all_access_keys(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all access keys from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_access_keys myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.get_all_access_keys(user_name, marker, max_items) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get access keys for IAM user %s.', user_name) return six.text_type(e) def create_access_key(user_name, region=None, key=None, keyid=None, profile=None): ''' Create access key id for a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.create_access_key(user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create access key.') return six.text_type(e) def delete_access_key(access_key_id, user_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete access key id from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_access_key(access_key_id, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete access key id %s.', access_key_id) return six.text_type(e) def delete_user(user_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user myuser ''' if not get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.delete_user(user_name) log.info('Deleted IAM user : %s .', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM user %s', user_name) return six.text_type(e) def get_user(user_name=None, region=None, key=None, keyid=None, profile=None): ''' Get user information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user(user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM user %s info.', user_name) return False def create_group(group_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_group group ''' if not path: path = '/' if get_group(group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_group(group_name, path) log.info('Created IAM group : %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM group %s.', group_name) return False def get_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group(group_name, max_items=1) if not info: return False return info['get_group_response']['get_group_result']['group'] except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_group_members(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: marker = None truncated = True users = [] while truncated: info = conn.get_group(group_name, marker=marker, max_items=1000) if not info: return False truncated = bool(info['get_group_response']['get_group_result']['is_truncated']) if truncated and 'marker' in info['get_group_response']['get_group_result']: marker = info['get_group_response']['get_group_result']['marker'] else: marker = None truncated = False users += info['get_group_response']['get_group_result']['users'] return users except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get members for IAM group %s.', group_name) return False def add_user_to_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Add user to group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.add_user_to_group myuser mygroup ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('Username : %s does not exist.', user_name) return False if user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.add_user_to_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add IAM user %s to group %s.', user_name, group_name) return False def user_exists_in_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Check if user exists in group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.user_exists_in_group myuser mygroup ''' # TODO this should probably use boto.iam.get_groups_for_user users = get_group_members( group_name=group_name, region=region, key=key, keyid=keyid, profile=profile ) if users: for _user in users: if user_name == _user['user_name']: log.debug('IAM user %s is already in IAM group %s.', user_name, group_name) return True return False def remove_user_from_group(group_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Remove user from group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.remove_user_from_group mygroup myuser ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist.', user_name) return False if not user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.remove_user_from_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove IAM user %s from group %s', user_name, group_name) return False def put_group_policy(group_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_group_policy mygroup policyname policyrules ''' group = get_group(group_name, region=region, key=key, keyid=keyid, profile=profile) if not group: log.error('Group %s does not exist', group_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_group_policy(group_name, policy_name, policy_json) if created: log.info('Created policy for IAM group %s.', group_name) return True log.error('Could not create policy for IAM group %s', group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy for IAM group %s', group_name) return False def delete_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group_policy mygroup mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_group_policy( group_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_group_policy(group_name, policy_name) log.info('Successfully deleted policy %s for IAM group %s.', policy_name, group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM group %s.', policy_name, group_name) return False def get_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group_policy mygroup policyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group_policy(group_name, policy_name) log.debug('info for group policy is : %s', info) if not info: return False info = info.get_group_policy_response.get_group_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_all_groups(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM group details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_groups ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _groups = conn.get_all_groups(path_prefix=path_prefix) groups = _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) while marker: _groups = conn.get_all_groups(path_prefix=path_prefix, marker=marker) groups = groups + _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) return groups def get_all_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.get_all_instance_profiles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) marker = False profiles = [] while marker is not None: marker = marker if marker else None p = conn.list_instance_profiles(path_prefix=path_prefix, marker=marker) res = p.list_instance_profiles_response.list_instance_profiles_result profiles += res.instance_profiles marker = getattr(res, 'marker', None) return profiles def list_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' List all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.list_instance_profiles ''' p = get_all_instance_profiles(path_prefix, region, key, keyid, profile) return [i['instance_profile_name'] for i in p] def get_all_group_policies(group_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a group. CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_group_policies mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False try: response = conn.get_all_group_policies(group_name) _list = response.list_group_policies_response.list_group_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def delete_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _group = get_group( group_name, region, key, keyid, profile ) if not _group: return True try: conn.delete_group(group_name) log.info('Successfully deleted IAM group %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM group %s.', group_name) return False def create_login_profile(user_name, password, region=None, key=None, keyid=None, profile=None): ''' Creates a login profile for the specified user, give the user the ability to access AWS services and the AWS Management Console. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_login_profile user_name password ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.create_login_profile(user_name, password) log.info('Created profile for IAM user %s.', user_name) return info except boto.exception.BotoServerError as e: log.debug(e) if 'Conflict' in e: log.info('Profile already exists for IAM user %s.', user_name) return 'Conflict' log.error('Failed to update profile for IAM user %s.', user_name) return False def delete_login_profile(user_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a login profile for the specified user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_login_profile user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.delete_login_profile(user_name) log.info('Deleted login profile for IAM user %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Login profile already deleted for IAM user %s.', user_name) return True log.error('Failed to delete login profile for IAM user %s.', user_name) return False def get_all_mfa_devices(user_name, region=None, key=None, keyid=None, profile=None): ''' Get all MFA devices associated with an IAM user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_mfa_devices user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: result = conn.get_all_mfa_devices(user_name) devices = result['list_mfa_devices_response']['list_mfa_devices_result']['mfa_devices'] return devices except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Could not find IAM user %s.', user_name) return [] log.error('Failed to get all MFA devices for IAM user %s.', user_name) return False def deactivate_mfa_device(user_name, serial, region=None, key=None, keyid=None, profile=None): ''' Deactivates the specified MFA device and removes it from association with the user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.deactivate_mfa_device user_name serial_num ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.deactivate_mfa_device(user_name, serial) log.info('Deactivated MFA device %s for IAM user %s.', serial, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('MFA device %s not associated with IAM user %s.', serial, user_name) return True log.error('Failed to deactivate MFA device %s for IAM user %s.', serial, user_name) return False def delete_virtual_mfa_device(serial, region=None, key=None, keyid=None, profile=None): ''' Deletes the specified virtual MFA device. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_virtual_mfa_device serial_num ''' conn = __utils__['boto3.get_connection_func']('iam')() try: conn.delete_virtual_mfa_device(SerialNumber=serial) log.info('Deleted virtual MFA device %s.', serial) return True except botocore.exceptions.ClientError as e: log.debug(e) if 'NoSuchEntity' in six.text_type(e): log.info('Virtual MFA device %s not found.', serial) return True log.error('Failed to delete virtual MFA device %s.', serial) return False def update_account_password_policy(allow_users_to_change_password=None, hard_expiry=None, max_password_age=None, minimum_password_length=None, password_reuse_prevention=None, require_lowercase_characters=None, require_numbers=None, require_symbols=None, require_uppercase_characters=None, region=None, key=None, keyid=None, profile=None): ''' Update the password policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_account_password_policy True ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.update_account_password_policy(allow_users_to_change_password, hard_expiry, max_password_age, minimum_password_length, password_reuse_prevention, require_lowercase_characters, require_numbers, require_symbols, require_uppercase_characters) log.info('The password policy has been updated.') return True except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy' log.error(msg) return False def get_account_policy(region=None, key=None, keyid=None, profile=None): ''' Get account policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_account_password_policy() return info.get_account_password_policy_response.get_account_password_policy_result.password_policy except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy.' log.error(msg) return False def create_role(name, policy_document=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Create an instance role. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if role_exists(name, region, key, keyid, profile): return True if not policy_document: policy_document = None try: conn.create_role(name, assume_role_policy_document=policy_document, path=path) log.info('Created IAM role %s.', name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to create IAM role %s.', name) return False def delete_role(name, region=None, key=None, keyid=None, profile=None): ''' Delete an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(name, region, key, keyid, profile): return True try: conn.delete_role(name) log.info('Deleted %s IAM role.', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s IAM role.', name) return False def profile_associated(role_name, profile_name, region, key, keyid, profile): ''' Check to see if an instance profile is associated with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.profile_associated myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # The IAM module of boto doesn't return objects. Instead you need to grab # values through its properties. Sigh. try: profiles = conn.list_instance_profiles_for_role(role_name) except boto.exception.BotoServerError as e: log.debug(e) return False profiles = profiles.list_instance_profiles_for_role_response profiles = profiles.list_instance_profiles_for_role_result profiles = profiles.instance_profiles for profile in profiles: if profile.instance_profile_name == profile_name: return True return False def associate_profile_to_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Associate an instance profile with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.associate_profile_to_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if associated: return True else: try: conn.add_role_to_instance_profile(profile_name, role_name) log.info('Added %s instance profile to IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add %s instance profile to IAM role %s', profile_name, role_name) return False def disassociate_profile_from_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Disassociate an instance profile from an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.disassociate_profile_from_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if not associated: return True else: try: conn.remove_role_from_instance_profile(profile_name, role_name) log.info('Removed %s instance profile from IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove %s instance profile from IAM role %s.', profile_name, role_name) return False def list_role_policies(role_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_role_policies myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_role_policies(role_name) _list = response.list_role_policies_response.list_role_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def get_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.get_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: _policy = conn.get_role_policy(role_name, policy_name) # I _hate_ you for not giving me an object boto. _policy = _policy.get_role_policy_response.policy_document # Policy is url encoded _policy = _unquote(_policy) _policy = salt.utils.json.loads(_policy, object_pairs_hook=odict.OrderedDict) return _policy except boto.exception.BotoServerError: return {} def create_role_policy(role_name, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Create or modify a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role_policy myirole mypolicy '{"MyPolicy": "Statement": [{"Action": ["sqs:*"], "Effect": "Allow", "Resource": ["arn:aws:sqs:*:*:*"], "Sid": "MyPolicySqs1"}]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) mode = 'create' if _policy: if _policy == policy: return True mode = 'modify' if isinstance(policy, six.string_types): policy = salt.utils.json.loads(policy, object_pairs_hook=odict.OrderedDict) try: _policy = salt.utils.json.dumps(policy) conn.put_role_policy(role_name, policy_name, _policy) if mode == 'create': msg = 'Successfully added policy %s to IAM role %s.' else: msg = 'Successfully modified policy %s for IAM role %s.' log.info(msg, policy_name, role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to %s policy %s for IAM role %s.', mode, policy_name, role_name) return False def delete_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) if not _policy: return True try: conn.delete_role_policy(role_name, policy_name) log.info('Successfully deleted policy %s for IAM role %s.', policy_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM role %s.', policy_name, role_name) return False def update_assume_role_policy(role_name, policy_document, region=None, key=None, keyid=None, profile=None): ''' Update an assume role policy for a role. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_assume_role_policy myrole '{"Statement":"..."}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(policy_document, six.string_types): policy_document = salt.utils.json.loads(policy_document, object_pairs_hook=odict.OrderedDict) try: _policy_document = salt.utils.json.dumps(policy_document) conn.update_assume_role_policy(role_name, _policy_document) log.info('Successfully updated assume role policy for IAM role %s.', role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to update assume role policy for IAM role %s.', role_name) return False def build_policy(region=None, key=None, keyid=None, profile=None): ''' Build a default assume role policy. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.build_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if hasattr(conn, 'build_policy'): policy = salt.utils.json.loads(conn.build_policy()) elif hasattr(conn, '_build_policy'): policy = salt.utils.json.loads(conn._build_policy()) else: return {} # The format we get from build_policy isn't going to be what we get back # from AWS for the exact same policy. AWS converts single item list values # into strings, so let's do the same here. for key, policy_val in policy.items(): for statement in policy_val: if (isinstance(statement['Action'], list) and len(statement['Action']) == 1): statement['Action'] = statement['Action'][0] if (isinstance(statement['Principal']['Service'], list) and len(statement['Principal']['Service']) == 1): statement['Principal']['Service'] = statement['Principal']['Service'][0] # build_policy doesn't add a version field, which AWS is going to set to a # default value, when we get it back, so let's set it. policy['Version'] = '2008-10-17' return policy def get_account_id(region=None, key=None, keyid=None, profile=None): ''' Get a the AWS account id associated with the used credentials. CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_id ''' cache_key = 'boto_iam.account_id' if cache_key not in __context__: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_user() # The get_user call returns an user ARN: # arn:aws:iam::027050522557:user/salt-test arn = ret['get_user_response']['get_user_result']['user']['arn'] account_id = arn.split(':')[4] except boto.exception.BotoServerError: # If call failed, then let's try to get the ARN from the metadata timeout = boto.config.getfloat( 'Boto', 'metadata_service_timeout', 1.0 ) attempts = boto.config.getint( 'Boto', 'metadata_service_num_attempts', 1 ) identity = boto.utils.get_instance_identity( timeout=timeout, num_retries=attempts ) try: account_id = identity['document']['accountId'] except KeyError: log.error('Failed to get account id from instance_identity in' ' boto_iam.get_account_id.') __context__[cache_key] = account_id return __context__[cache_key] def get_all_roles(path_prefix=None, region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM role details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_roles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _roles = conn.list_roles(path_prefix=path_prefix) roles = _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) while marker: _roles = conn.list_roles(path_prefix=path_prefix, marker=marker) roles = roles + _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) return roles def get_all_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM user details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_users ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _users = conn.get_all_users(path_prefix=path_prefix) users = _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) while marker: _users = conn.get_all_users(path_prefix=path_prefix, marker=marker) users = users + _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) return users def get_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user_policy myuser mypolicyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user_policy(user_name, policy_name) log.debug('Info for IAM user %s policy %s: %s.', user_name, policy_name, info) if not info: return False info = info.get_user_policy_response.get_user_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policy %s for IAM user %s.', policy_name, user_name) return False def put_user_policy(user_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_user_policy myuser policyname policyrules ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_user_policy(user_name, policy_name, policy_json) if created: log.info('Created policy %s for IAM user %s.', policy_name, user_name) return True log.error('Could not create policy %s for IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy %s for IAM user %s.', policy_name, user_name) return False def delete_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user_policy myuser mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_user_policy( user_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_user_policy(user_name, policy_name) log.info('Successfully deleted policy %s for IAM user %s.', policy_name, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM user %s.', policy_name, user_name) return False def upload_server_cert(cert_name, cert_body, private_key, cert_chain=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Upload a certificate to Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.upload_server_cert mycert_name crt priv_key :param cert_name: The name for the server certificate. Do not include the path in this value. :param cert_body: The contents of the public key certificate in PEM-encoded format. :param private_key: The contents of the private key in PEM-encoded format. :param cert_chain: The contents of the certificate chain. This is typically a concatenation of the PEM-encoded public key certificates of the chain. :param path: The path for the server certificate. :param region: The name of the region to connect to. :param key: The key to be used in order to connect :param keyid: The keyid to be used in order to connect :param profile: The profile that contains a dict of region, key, keyid :return: True / False ''' exists = get_server_certificate(cert_name, region, key, keyid, profile) if exists: return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.upload_server_cert(cert_name, cert_body, private_key, cert_chain) log.info('Created certificate %s.', cert_name) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to failed to create certificate %s.', cert_name) return False def list_server_certificates(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Lists the server certificates stored in IAM that have the specified path prefix. .. versionadded:: ??? :param path_prefix: The path prefix for filtering the results. For example: /company/servercerts would get all server certificates for which the path starts with /company/servercerts . This parameter is optional. If it is not included, it defaults to a slash (/), listing all server certificates. This parameter allows (per its regex pattern) a string of characters consisting of either a forward slash (/) by itself or a string that must begin and end with forward slashes. In addition, it can contain any ASCII character from the ! (u0021) through the DEL character (u007F), including most punctuation characters, digits, and upper and lowercased letters. CLI Example: .. code-block:: bash salt myminion boto_iam.list_server_certificates path_prefix=/somepath/ ''' retries = 10 sleep = 6 conn = __utils__['boto3.get_connection']('iam', region=region, key=key, keyid=keyid, profile=profile) Items = [] while retries: try: log.debug('Garnering list of IAM Server Certificates') IsTruncated = True while IsTruncated: kwargs = {'PathPrefix': path_prefix} ret = conn.list_server_certificates(**kwargs) Items += ret.get('ServerCertificateMetadataList', []) IsTruncated = ret.get('IsTruncated') kwargs.update({'Marker': ret.get('Marker')}) return Items except botocore.exceptions.ParamValidationError as err: raise SaltInvocationError(str(err)) except botocore.exceptions.ClientError as err: if retries and jmespath.search('Error.Code', err.response) == 'Throttling': retries -= 1 log.debug('Throttled by AWS API, retrying in %s seconds...', sleep) time.sleep(sleep) continue log.error('Failed to list IAM Server Certificates: %s', err.message) return None def get_server_certificate(cert_name, region=None, key=None, keyid=None, profile=None): ''' Returns certificate information from Amazon .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_server_certificate mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_server_certificate(cert_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get certificate %s information.', cert_name) return False def delete_server_cert(cert_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a certificate from Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_server_cert mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_server_cert(cert_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete certificate %s.', cert_name) return False def export_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM user details. Produces results that can be used to create an sls file. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.export_users --out=txt | sed "s/local: //" > iam_users.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() users = get_all_users(path_prefix, region, key, keyid, profile) for user in users: name = user.user_name _policies = conn.get_all_user_policies(name, max_items=100) _policies = _policies.list_user_policies_response.list_user_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_user_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_user_policy_response.get_user_policy_result.policy_document )) policies[policy_name] = _policy user_sls = [] user_sls.append({"name": name}) user_sls.append({"policies": policies}) user_sls.append({"path": user.path}) results["manage user " + name] = {"boto_iam.user_present": user_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def export_roles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM role details. Produces results that can be used to create an sls file. CLI Example: salt-call boto_iam.export_roles --out=txt | sed "s/local: //" > iam_roles.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() roles = get_all_roles(path_prefix, region, key, keyid, profile) for role in roles: name = role.role_name _policies = conn.list_role_policies(name, max_items=100) _policies = _policies.list_role_policies_response.list_role_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_role_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_role_policy_response.get_role_policy_result.policy_document )) policies[policy_name] = _policy role_sls = [] role_sls.append({"name": name}) role_sls.append({"policies": policies}) role_sls.append({'policy_document': salt.utils.json.loads(_unquote(role.assume_role_policy_document))}) role_sls.append({"path": role.path}) results["manage role " + name] = {"boto_iam_role.present": role_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def _get_policy_arn(name, region=None, key=None, keyid=None, profile=None): if name.startswith('arn:aws:iam:'): return name account_id = get_account_id( region=region, key=key, keyid=keyid, profile=profile ) return 'arn:aws:iam::{0}:policy/{1}'.format(account_id, name) def policy_exists(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return True except boto.exception.BotoServerError: return False def get_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return ret.get('get_policy_response', {}).get('get_policy_result', {}) except boto.exception.BotoServerError: return None def create_policy(policy_name, policy_document, path=None, description=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in 'path', 'description': if locals()[arg] is not None: params[arg] = locals()[arg] if policy_exists(policy_name, region, key, keyid, profile): return True try: conn.create_policy(policy_name, policy_document, **params) log.info('Created IAM policy %s.', policy_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s.', policy_name) return False return True def delete_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_exists(policy_arn, region, key, keyid, profile): return True try: conn.delete_policy(policy_arn) log.info('Deleted %s policy.', policy_name) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete %s policy: %s.', policy_name, aws.get('message')) return False return True def list_policies(region=None, key=None, keyid=None, profile=None): ''' List policies. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policies ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: policies = [] for ret in __utils__['boto.paged_call'](conn.list_policies): policies.append(ret.get('list_policies_response', {}).get('list_policies_result', {}).get('policies')) return policies except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to list policy versions.' log.error(msg) return [] def policy_version_exists(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.get_policy_version(policy_arn, version_id) return True except boto.exception.BotoServerError: return False def get_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy_version(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile), version_id) retval = ret.get('get_policy_version_response', {}).get('get_policy_version_result', {}).get('policy_version', {}) retval['document'] = _unquote(retval.get('document')) return {'policy_version': retval} except boto.exception.BotoServerError: return None def create_policy_version(policy_name, policy_document, set_as_default=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy version. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy_version mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in ('set_as_default',): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.create_policy_version(policy_arn, policy_document, **params) vid = ret.get('create_policy_version_response', {}).get('create_policy_version_result', {}).get('policy_version', {}).get('version_id') log.info('Created IAM policy %s version %s.', policy_name, vid) return {'created': True, 'version_id': vid} except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s version %s.', policy_name, vid) return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Delete a policy version. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_version_exists(policy_arn, version_id, region, key, keyid, profile): return True try: conn.delete_policy_version(policy_arn, version_id) log.info('Deleted IAM policy %s version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete IAM policy %s version %s: %s', policy_name, version_id, aws.get('message')) return False return True def list_policy_versions(policy_name, region=None, key=None, keyid=None, profile=None): ''' List versions of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policy_versions mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.list_policy_versions(policy_arn) return ret.get('list_policy_versions_response', {}).get('list_policy_versions_result', {}).get('versions') except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list versions for IAM policy %s.', policy_name) return [] def set_default_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Set the default version of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.set_default_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.set_default_policy_version(policy_arn, version_id) log.info('Set %s policy to version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to set %s policy to version %s: %s', policy_name, version_id, aws.get('message')) return False return True def attach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_user_policy(policy_arn, user_name) log.info('Attached policy %s to IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach %s policy to IAM user %s.', policy_name, user_name) return False return True def detach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_user_policy(policy_arn, user_name) log.info('Detached %s policy from IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach %s policy from IAM user %s.', policy_name, user_name) return False return True def attach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_group_policy(policy_arn, group_name) log.info('Attached policy %s to IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM group %s.', policy_name, group_name) return False return True def detach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_group_policy(policy_arn, group_name) log.info('Detached policy %s from IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM group %s.', policy_name, group_name) return False return True def attach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_role_policy(policy_arn, role_name) log.info('Attached policy %s to IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM role %s.', policy_name, role_name) return False return True def detach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_role_policy(policy_arn, role_name) log.info('Detached policy %s from IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM role %s.', policy_name, role_name) return False return True def list_entities_for_policy(policy_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities that a policy is attached to. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 params = {} for arg in ('path_prefix', 'entity_filter'): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) while retries: try: allret = { 'policy_groups': [], 'policy_users': [], 'policy_roles': [], } for ret in __utils__['boto.paged_call'](conn.list_entities_for_policy, policy_arn=policy_arn, **params): for k, v in six.iteritems(allret): v.extend(ret.get('list_entities_for_policy_response', {}).get('list_entities_for_policy_result', {}).get(k)) return allret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('Failed to list entities for IAM policy %s: %s', policy_name, e.message) return {} return {} def list_attached_user_policies(user_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given user. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'UserName': user_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedUserPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_user_policies_response', {}).get('list_attached_user_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM user %s.', user_name) return [] def list_attached_group_policies(group_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given group. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'GroupName': group_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedGroupPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_group_policies_response', {}).get('list_attached_group_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM group %s.', group_name) return [] def list_attached_role_policies(role_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'RoleName': role_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedRolePolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_role_policies_response', {}).get('list_attached_role_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM role %s.', role_name) return [] def create_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Create SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.create_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_saml_provider(saml_metadata_document, name) log.info('Successfully created %s SAML provider.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to create SAML provider %s.', name) return False def get_saml_provider_arn(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider_arn my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_saml_providers() for saml_provider in response.list_saml_providers_response.list_saml_providers_result.saml_provider_list: if saml_provider['arn'].endswith(':saml-provider/' + name): return saml_provider['arn'] return False except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to get ARN of SAML provider %s.', name) return False def delete_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Delete SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.delete_saml_provider my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return True conn.delete_saml_provider(saml_provider_arn) log.info('Successfully deleted SAML provider %s.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete SAML provider %s.', name) return False def list_saml_providers(region=None, key=None, keyid=None, profile=None): ''' List SAML providers. CLI Example: .. code-block:: bash salt myminion boto_iam.list_saml_providers ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: providers = [] info = conn.list_saml_providers() for arn in info['list_saml_providers_response']['list_saml_providers_result']['saml_provider_list']: providers.append(arn['arn'].rsplit('/', 1)[1]) return providers except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get list of SAML providers.') return False def get_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider document. CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider arn ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: provider = conn.get_saml_provider(name) return provider['get_saml_provider_response']['get_saml_provider_result']['saml_metadata_document'] except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get SAML provider document %s.', name) return False def update_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Update SAML provider. CLI Example: .. code-block:: bash salt myminion boto_iam.update_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return False if conn.update_saml_provider(name, saml_metadata_document): return True return False except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to update SAML provider %s.', name) return False
saltstack/salt
salt/modules/boto_iam.py
get_user_policy
python
def get_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user_policy myuser mypolicyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user_policy(user_name, policy_name) log.debug('Info for IAM user %s policy %s: %s.', user_name, policy_name, info) if not info: return False info = info.get_user_policy_response.get_user_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policy %s for IAM user %s.', policy_name, user_name) return False
Retrieves the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user_policy myuser mypolicyname
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iam.py#L1398-L1423
[ "def loads(s, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.loads and prevents a traceback in the event that a bytestring is\n passed to the function. (Python < 3.6 cannot load bytestrings)\n\n You can pass an alternate json module (loaded via import_json() above)\n using the _json_module argument)\n '''\n json_module = kwargs.pop('_json_module', json)\n try:\n return json_module.loads(s, **kwargs)\n except TypeError as exc:\n # json.loads cannot load bytestrings in Python < 3.6\n if six.PY3 and isinstance(s, bytes):\n return json_module.loads(salt.utils.stringutils.to_unicode(s), **kwargs)\n else:\n raise exc\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon IAM .. versionadded:: 2014.7.0 :configuration: This module accepts explicit iam 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 iam.keyid: GKTADJGHEIQSXMKKRBJ08H iam.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs iam.region: 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: boto ''' # keep lint from choking on _get_conn and _cache_id #pylint: disable=E0602 # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import salt libs from salt.ext import six import salt.utils.compat import salt.utils.json import salt.utils.odict as odict import salt.utils.versions from salt.exceptions import SaltInvocationError # Import third party libs # pylint: disable=unused-import from salt.ext.six.moves.urllib.parse import unquote as _unquote # pylint: disable=no-name-in-module try: import boto import boto.iam import boto3 import botocore logging.getLogger('boto').setLevel(logging.CRITICAL) logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=unused-import log = logging.getLogger(__name__) def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'iam', pack=__salt__) def instance_profile_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an instance profile exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: # Boto weirdly returns an exception here if an instance profile doesn't # exist. conn.get_instance_profile(name) return True except boto.exception.BotoServerError: return False def create_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Create an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.create_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if instance_profile_exists(name, region, key, keyid, profile): return True try: # This call returns an instance profile if successful and an exception # if not. It's annoying. conn.create_instance_profile(name) log.info('Created %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create %s instance profile.', name) return False return True def delete_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Delete an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not instance_profile_exists(name, region, key, keyid, profile): return True try: conn.delete_instance_profile(name) log.info('Deleted %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s instance profile.', name) return False return True def role_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an IAM role exists. CLI Example: .. code-block:: bash salt myminion boto_iam.role_exists myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_role(name) return True except boto.exception.BotoServerError: return False def describe_role(name, region=None, key=None, keyid=None, profile=None): ''' Get information for a role. CLI Example: .. code-block:: bash salt myminion boto_iam.describe_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_role(name) if not info: return False role = info.get_role_response.get_role_result.role role['assume_role_policy_document'] = salt.utils.json.loads(_unquote( role.assume_role_policy_document )) # If Sid wasn't defined by the user, boto will still return a Sid in # each policy. To properly check idempotently, let's remove the Sid # from the return if it's not actually set. for policy_key, policy in role['assume_role_policy_document'].items(): if policy_key == 'Statement': for val in policy: if 'Sid' in val and not val['Sid']: del val['Sid'] return role except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get %s information.', name) return False def create_user(user_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_user myuser ''' if not path: path = '/' if get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_user(user_name, path) log.info('Created IAM user : %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM user %s.', user_name) return False def get_all_access_keys(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all access keys from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_access_keys myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.get_all_access_keys(user_name, marker, max_items) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get access keys for IAM user %s.', user_name) return six.text_type(e) def create_access_key(user_name, region=None, key=None, keyid=None, profile=None): ''' Create access key id for a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.create_access_key(user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create access key.') return six.text_type(e) def delete_access_key(access_key_id, user_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete access key id from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_access_key(access_key_id, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete access key id %s.', access_key_id) return six.text_type(e) def delete_user(user_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user myuser ''' if not get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.delete_user(user_name) log.info('Deleted IAM user : %s .', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM user %s', user_name) return six.text_type(e) def get_user(user_name=None, region=None, key=None, keyid=None, profile=None): ''' Get user information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user(user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM user %s info.', user_name) return False def create_group(group_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_group group ''' if not path: path = '/' if get_group(group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_group(group_name, path) log.info('Created IAM group : %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM group %s.', group_name) return False def get_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group(group_name, max_items=1) if not info: return False return info['get_group_response']['get_group_result']['group'] except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_group_members(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: marker = None truncated = True users = [] while truncated: info = conn.get_group(group_name, marker=marker, max_items=1000) if not info: return False truncated = bool(info['get_group_response']['get_group_result']['is_truncated']) if truncated and 'marker' in info['get_group_response']['get_group_result']: marker = info['get_group_response']['get_group_result']['marker'] else: marker = None truncated = False users += info['get_group_response']['get_group_result']['users'] return users except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get members for IAM group %s.', group_name) return False def add_user_to_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Add user to group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.add_user_to_group myuser mygroup ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('Username : %s does not exist.', user_name) return False if user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.add_user_to_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add IAM user %s to group %s.', user_name, group_name) return False def user_exists_in_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Check if user exists in group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.user_exists_in_group myuser mygroup ''' # TODO this should probably use boto.iam.get_groups_for_user users = get_group_members( group_name=group_name, region=region, key=key, keyid=keyid, profile=profile ) if users: for _user in users: if user_name == _user['user_name']: log.debug('IAM user %s is already in IAM group %s.', user_name, group_name) return True return False def remove_user_from_group(group_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Remove user from group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.remove_user_from_group mygroup myuser ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist.', user_name) return False if not user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.remove_user_from_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove IAM user %s from group %s', user_name, group_name) return False def put_group_policy(group_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_group_policy mygroup policyname policyrules ''' group = get_group(group_name, region=region, key=key, keyid=keyid, profile=profile) if not group: log.error('Group %s does not exist', group_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_group_policy(group_name, policy_name, policy_json) if created: log.info('Created policy for IAM group %s.', group_name) return True log.error('Could not create policy for IAM group %s', group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy for IAM group %s', group_name) return False def delete_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group_policy mygroup mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_group_policy( group_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_group_policy(group_name, policy_name) log.info('Successfully deleted policy %s for IAM group %s.', policy_name, group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM group %s.', policy_name, group_name) return False def get_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group_policy mygroup policyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group_policy(group_name, policy_name) log.debug('info for group policy is : %s', info) if not info: return False info = info.get_group_policy_response.get_group_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_all_groups(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM group details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_groups ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _groups = conn.get_all_groups(path_prefix=path_prefix) groups = _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) while marker: _groups = conn.get_all_groups(path_prefix=path_prefix, marker=marker) groups = groups + _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) return groups def get_all_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.get_all_instance_profiles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) marker = False profiles = [] while marker is not None: marker = marker if marker else None p = conn.list_instance_profiles(path_prefix=path_prefix, marker=marker) res = p.list_instance_profiles_response.list_instance_profiles_result profiles += res.instance_profiles marker = getattr(res, 'marker', None) return profiles def list_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' List all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.list_instance_profiles ''' p = get_all_instance_profiles(path_prefix, region, key, keyid, profile) return [i['instance_profile_name'] for i in p] def get_all_group_policies(group_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a group. CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_group_policies mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False try: response = conn.get_all_group_policies(group_name) _list = response.list_group_policies_response.list_group_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def delete_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _group = get_group( group_name, region, key, keyid, profile ) if not _group: return True try: conn.delete_group(group_name) log.info('Successfully deleted IAM group %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM group %s.', group_name) return False def create_login_profile(user_name, password, region=None, key=None, keyid=None, profile=None): ''' Creates a login profile for the specified user, give the user the ability to access AWS services and the AWS Management Console. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_login_profile user_name password ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.create_login_profile(user_name, password) log.info('Created profile for IAM user %s.', user_name) return info except boto.exception.BotoServerError as e: log.debug(e) if 'Conflict' in e: log.info('Profile already exists for IAM user %s.', user_name) return 'Conflict' log.error('Failed to update profile for IAM user %s.', user_name) return False def delete_login_profile(user_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a login profile for the specified user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_login_profile user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.delete_login_profile(user_name) log.info('Deleted login profile for IAM user %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Login profile already deleted for IAM user %s.', user_name) return True log.error('Failed to delete login profile for IAM user %s.', user_name) return False def get_all_mfa_devices(user_name, region=None, key=None, keyid=None, profile=None): ''' Get all MFA devices associated with an IAM user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_mfa_devices user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: result = conn.get_all_mfa_devices(user_name) devices = result['list_mfa_devices_response']['list_mfa_devices_result']['mfa_devices'] return devices except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Could not find IAM user %s.', user_name) return [] log.error('Failed to get all MFA devices for IAM user %s.', user_name) return False def deactivate_mfa_device(user_name, serial, region=None, key=None, keyid=None, profile=None): ''' Deactivates the specified MFA device and removes it from association with the user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.deactivate_mfa_device user_name serial_num ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.deactivate_mfa_device(user_name, serial) log.info('Deactivated MFA device %s for IAM user %s.', serial, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('MFA device %s not associated with IAM user %s.', serial, user_name) return True log.error('Failed to deactivate MFA device %s for IAM user %s.', serial, user_name) return False def delete_virtual_mfa_device(serial, region=None, key=None, keyid=None, profile=None): ''' Deletes the specified virtual MFA device. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_virtual_mfa_device serial_num ''' conn = __utils__['boto3.get_connection_func']('iam')() try: conn.delete_virtual_mfa_device(SerialNumber=serial) log.info('Deleted virtual MFA device %s.', serial) return True except botocore.exceptions.ClientError as e: log.debug(e) if 'NoSuchEntity' in six.text_type(e): log.info('Virtual MFA device %s not found.', serial) return True log.error('Failed to delete virtual MFA device %s.', serial) return False def update_account_password_policy(allow_users_to_change_password=None, hard_expiry=None, max_password_age=None, minimum_password_length=None, password_reuse_prevention=None, require_lowercase_characters=None, require_numbers=None, require_symbols=None, require_uppercase_characters=None, region=None, key=None, keyid=None, profile=None): ''' Update the password policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_account_password_policy True ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.update_account_password_policy(allow_users_to_change_password, hard_expiry, max_password_age, minimum_password_length, password_reuse_prevention, require_lowercase_characters, require_numbers, require_symbols, require_uppercase_characters) log.info('The password policy has been updated.') return True except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy' log.error(msg) return False def get_account_policy(region=None, key=None, keyid=None, profile=None): ''' Get account policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_account_password_policy() return info.get_account_password_policy_response.get_account_password_policy_result.password_policy except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy.' log.error(msg) return False def create_role(name, policy_document=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Create an instance role. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if role_exists(name, region, key, keyid, profile): return True if not policy_document: policy_document = None try: conn.create_role(name, assume_role_policy_document=policy_document, path=path) log.info('Created IAM role %s.', name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to create IAM role %s.', name) return False def delete_role(name, region=None, key=None, keyid=None, profile=None): ''' Delete an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(name, region, key, keyid, profile): return True try: conn.delete_role(name) log.info('Deleted %s IAM role.', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s IAM role.', name) return False def profile_associated(role_name, profile_name, region, key, keyid, profile): ''' Check to see if an instance profile is associated with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.profile_associated myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # The IAM module of boto doesn't return objects. Instead you need to grab # values through its properties. Sigh. try: profiles = conn.list_instance_profiles_for_role(role_name) except boto.exception.BotoServerError as e: log.debug(e) return False profiles = profiles.list_instance_profiles_for_role_response profiles = profiles.list_instance_profiles_for_role_result profiles = profiles.instance_profiles for profile in profiles: if profile.instance_profile_name == profile_name: return True return False def associate_profile_to_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Associate an instance profile with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.associate_profile_to_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if associated: return True else: try: conn.add_role_to_instance_profile(profile_name, role_name) log.info('Added %s instance profile to IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add %s instance profile to IAM role %s', profile_name, role_name) return False def disassociate_profile_from_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Disassociate an instance profile from an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.disassociate_profile_from_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if not associated: return True else: try: conn.remove_role_from_instance_profile(profile_name, role_name) log.info('Removed %s instance profile from IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove %s instance profile from IAM role %s.', profile_name, role_name) return False def list_role_policies(role_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_role_policies myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_role_policies(role_name) _list = response.list_role_policies_response.list_role_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def get_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.get_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: _policy = conn.get_role_policy(role_name, policy_name) # I _hate_ you for not giving me an object boto. _policy = _policy.get_role_policy_response.policy_document # Policy is url encoded _policy = _unquote(_policy) _policy = salt.utils.json.loads(_policy, object_pairs_hook=odict.OrderedDict) return _policy except boto.exception.BotoServerError: return {} def create_role_policy(role_name, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Create or modify a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role_policy myirole mypolicy '{"MyPolicy": "Statement": [{"Action": ["sqs:*"], "Effect": "Allow", "Resource": ["arn:aws:sqs:*:*:*"], "Sid": "MyPolicySqs1"}]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) mode = 'create' if _policy: if _policy == policy: return True mode = 'modify' if isinstance(policy, six.string_types): policy = salt.utils.json.loads(policy, object_pairs_hook=odict.OrderedDict) try: _policy = salt.utils.json.dumps(policy) conn.put_role_policy(role_name, policy_name, _policy) if mode == 'create': msg = 'Successfully added policy %s to IAM role %s.' else: msg = 'Successfully modified policy %s for IAM role %s.' log.info(msg, policy_name, role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to %s policy %s for IAM role %s.', mode, policy_name, role_name) return False def delete_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) if not _policy: return True try: conn.delete_role_policy(role_name, policy_name) log.info('Successfully deleted policy %s for IAM role %s.', policy_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM role %s.', policy_name, role_name) return False def update_assume_role_policy(role_name, policy_document, region=None, key=None, keyid=None, profile=None): ''' Update an assume role policy for a role. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_assume_role_policy myrole '{"Statement":"..."}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(policy_document, six.string_types): policy_document = salt.utils.json.loads(policy_document, object_pairs_hook=odict.OrderedDict) try: _policy_document = salt.utils.json.dumps(policy_document) conn.update_assume_role_policy(role_name, _policy_document) log.info('Successfully updated assume role policy for IAM role %s.', role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to update assume role policy for IAM role %s.', role_name) return False def build_policy(region=None, key=None, keyid=None, profile=None): ''' Build a default assume role policy. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.build_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if hasattr(conn, 'build_policy'): policy = salt.utils.json.loads(conn.build_policy()) elif hasattr(conn, '_build_policy'): policy = salt.utils.json.loads(conn._build_policy()) else: return {} # The format we get from build_policy isn't going to be what we get back # from AWS for the exact same policy. AWS converts single item list values # into strings, so let's do the same here. for key, policy_val in policy.items(): for statement in policy_val: if (isinstance(statement['Action'], list) and len(statement['Action']) == 1): statement['Action'] = statement['Action'][0] if (isinstance(statement['Principal']['Service'], list) and len(statement['Principal']['Service']) == 1): statement['Principal']['Service'] = statement['Principal']['Service'][0] # build_policy doesn't add a version field, which AWS is going to set to a # default value, when we get it back, so let's set it. policy['Version'] = '2008-10-17' return policy def get_account_id(region=None, key=None, keyid=None, profile=None): ''' Get a the AWS account id associated with the used credentials. CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_id ''' cache_key = 'boto_iam.account_id' if cache_key not in __context__: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_user() # The get_user call returns an user ARN: # arn:aws:iam::027050522557:user/salt-test arn = ret['get_user_response']['get_user_result']['user']['arn'] account_id = arn.split(':')[4] except boto.exception.BotoServerError: # If call failed, then let's try to get the ARN from the metadata timeout = boto.config.getfloat( 'Boto', 'metadata_service_timeout', 1.0 ) attempts = boto.config.getint( 'Boto', 'metadata_service_num_attempts', 1 ) identity = boto.utils.get_instance_identity( timeout=timeout, num_retries=attempts ) try: account_id = identity['document']['accountId'] except KeyError: log.error('Failed to get account id from instance_identity in' ' boto_iam.get_account_id.') __context__[cache_key] = account_id return __context__[cache_key] def get_all_roles(path_prefix=None, region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM role details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_roles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _roles = conn.list_roles(path_prefix=path_prefix) roles = _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) while marker: _roles = conn.list_roles(path_prefix=path_prefix, marker=marker) roles = roles + _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) return roles def get_all_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM user details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_users ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _users = conn.get_all_users(path_prefix=path_prefix) users = _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) while marker: _users = conn.get_all_users(path_prefix=path_prefix, marker=marker) users = users + _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) return users def get_all_user_policies(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all user policies. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_user_policies myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_all_user_policies(user_name, marker, max_items) if not info: return False _list = info.list_user_policies_response.list_user_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policies for user %s.', user_name) return False def put_user_policy(user_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_user_policy myuser policyname policyrules ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_user_policy(user_name, policy_name, policy_json) if created: log.info('Created policy %s for IAM user %s.', policy_name, user_name) return True log.error('Could not create policy %s for IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy %s for IAM user %s.', policy_name, user_name) return False def delete_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user_policy myuser mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_user_policy( user_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_user_policy(user_name, policy_name) log.info('Successfully deleted policy %s for IAM user %s.', policy_name, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM user %s.', policy_name, user_name) return False def upload_server_cert(cert_name, cert_body, private_key, cert_chain=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Upload a certificate to Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.upload_server_cert mycert_name crt priv_key :param cert_name: The name for the server certificate. Do not include the path in this value. :param cert_body: The contents of the public key certificate in PEM-encoded format. :param private_key: The contents of the private key in PEM-encoded format. :param cert_chain: The contents of the certificate chain. This is typically a concatenation of the PEM-encoded public key certificates of the chain. :param path: The path for the server certificate. :param region: The name of the region to connect to. :param key: The key to be used in order to connect :param keyid: The keyid to be used in order to connect :param profile: The profile that contains a dict of region, key, keyid :return: True / False ''' exists = get_server_certificate(cert_name, region, key, keyid, profile) if exists: return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.upload_server_cert(cert_name, cert_body, private_key, cert_chain) log.info('Created certificate %s.', cert_name) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to failed to create certificate %s.', cert_name) return False def list_server_certificates(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Lists the server certificates stored in IAM that have the specified path prefix. .. versionadded:: ??? :param path_prefix: The path prefix for filtering the results. For example: /company/servercerts would get all server certificates for which the path starts with /company/servercerts . This parameter is optional. If it is not included, it defaults to a slash (/), listing all server certificates. This parameter allows (per its regex pattern) a string of characters consisting of either a forward slash (/) by itself or a string that must begin and end with forward slashes. In addition, it can contain any ASCII character from the ! (u0021) through the DEL character (u007F), including most punctuation characters, digits, and upper and lowercased letters. CLI Example: .. code-block:: bash salt myminion boto_iam.list_server_certificates path_prefix=/somepath/ ''' retries = 10 sleep = 6 conn = __utils__['boto3.get_connection']('iam', region=region, key=key, keyid=keyid, profile=profile) Items = [] while retries: try: log.debug('Garnering list of IAM Server Certificates') IsTruncated = True while IsTruncated: kwargs = {'PathPrefix': path_prefix} ret = conn.list_server_certificates(**kwargs) Items += ret.get('ServerCertificateMetadataList', []) IsTruncated = ret.get('IsTruncated') kwargs.update({'Marker': ret.get('Marker')}) return Items except botocore.exceptions.ParamValidationError as err: raise SaltInvocationError(str(err)) except botocore.exceptions.ClientError as err: if retries and jmespath.search('Error.Code', err.response) == 'Throttling': retries -= 1 log.debug('Throttled by AWS API, retrying in %s seconds...', sleep) time.sleep(sleep) continue log.error('Failed to list IAM Server Certificates: %s', err.message) return None def get_server_certificate(cert_name, region=None, key=None, keyid=None, profile=None): ''' Returns certificate information from Amazon .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_server_certificate mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_server_certificate(cert_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get certificate %s information.', cert_name) return False def delete_server_cert(cert_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a certificate from Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_server_cert mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_server_cert(cert_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete certificate %s.', cert_name) return False def export_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM user details. Produces results that can be used to create an sls file. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.export_users --out=txt | sed "s/local: //" > iam_users.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() users = get_all_users(path_prefix, region, key, keyid, profile) for user in users: name = user.user_name _policies = conn.get_all_user_policies(name, max_items=100) _policies = _policies.list_user_policies_response.list_user_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_user_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_user_policy_response.get_user_policy_result.policy_document )) policies[policy_name] = _policy user_sls = [] user_sls.append({"name": name}) user_sls.append({"policies": policies}) user_sls.append({"path": user.path}) results["manage user " + name] = {"boto_iam.user_present": user_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def export_roles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM role details. Produces results that can be used to create an sls file. CLI Example: salt-call boto_iam.export_roles --out=txt | sed "s/local: //" > iam_roles.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() roles = get_all_roles(path_prefix, region, key, keyid, profile) for role in roles: name = role.role_name _policies = conn.list_role_policies(name, max_items=100) _policies = _policies.list_role_policies_response.list_role_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_role_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_role_policy_response.get_role_policy_result.policy_document )) policies[policy_name] = _policy role_sls = [] role_sls.append({"name": name}) role_sls.append({"policies": policies}) role_sls.append({'policy_document': salt.utils.json.loads(_unquote(role.assume_role_policy_document))}) role_sls.append({"path": role.path}) results["manage role " + name] = {"boto_iam_role.present": role_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def _get_policy_arn(name, region=None, key=None, keyid=None, profile=None): if name.startswith('arn:aws:iam:'): return name account_id = get_account_id( region=region, key=key, keyid=keyid, profile=profile ) return 'arn:aws:iam::{0}:policy/{1}'.format(account_id, name) def policy_exists(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return True except boto.exception.BotoServerError: return False def get_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return ret.get('get_policy_response', {}).get('get_policy_result', {}) except boto.exception.BotoServerError: return None def create_policy(policy_name, policy_document, path=None, description=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in 'path', 'description': if locals()[arg] is not None: params[arg] = locals()[arg] if policy_exists(policy_name, region, key, keyid, profile): return True try: conn.create_policy(policy_name, policy_document, **params) log.info('Created IAM policy %s.', policy_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s.', policy_name) return False return True def delete_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_exists(policy_arn, region, key, keyid, profile): return True try: conn.delete_policy(policy_arn) log.info('Deleted %s policy.', policy_name) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete %s policy: %s.', policy_name, aws.get('message')) return False return True def list_policies(region=None, key=None, keyid=None, profile=None): ''' List policies. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policies ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: policies = [] for ret in __utils__['boto.paged_call'](conn.list_policies): policies.append(ret.get('list_policies_response', {}).get('list_policies_result', {}).get('policies')) return policies except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to list policy versions.' log.error(msg) return [] def policy_version_exists(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.get_policy_version(policy_arn, version_id) return True except boto.exception.BotoServerError: return False def get_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy_version(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile), version_id) retval = ret.get('get_policy_version_response', {}).get('get_policy_version_result', {}).get('policy_version', {}) retval['document'] = _unquote(retval.get('document')) return {'policy_version': retval} except boto.exception.BotoServerError: return None def create_policy_version(policy_name, policy_document, set_as_default=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy version. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy_version mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in ('set_as_default',): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.create_policy_version(policy_arn, policy_document, **params) vid = ret.get('create_policy_version_response', {}).get('create_policy_version_result', {}).get('policy_version', {}).get('version_id') log.info('Created IAM policy %s version %s.', policy_name, vid) return {'created': True, 'version_id': vid} except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s version %s.', policy_name, vid) return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Delete a policy version. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_version_exists(policy_arn, version_id, region, key, keyid, profile): return True try: conn.delete_policy_version(policy_arn, version_id) log.info('Deleted IAM policy %s version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete IAM policy %s version %s: %s', policy_name, version_id, aws.get('message')) return False return True def list_policy_versions(policy_name, region=None, key=None, keyid=None, profile=None): ''' List versions of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policy_versions mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.list_policy_versions(policy_arn) return ret.get('list_policy_versions_response', {}).get('list_policy_versions_result', {}).get('versions') except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list versions for IAM policy %s.', policy_name) return [] def set_default_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Set the default version of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.set_default_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.set_default_policy_version(policy_arn, version_id) log.info('Set %s policy to version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to set %s policy to version %s: %s', policy_name, version_id, aws.get('message')) return False return True def attach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_user_policy(policy_arn, user_name) log.info('Attached policy %s to IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach %s policy to IAM user %s.', policy_name, user_name) return False return True def detach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_user_policy(policy_arn, user_name) log.info('Detached %s policy from IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach %s policy from IAM user %s.', policy_name, user_name) return False return True def attach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_group_policy(policy_arn, group_name) log.info('Attached policy %s to IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM group %s.', policy_name, group_name) return False return True def detach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_group_policy(policy_arn, group_name) log.info('Detached policy %s from IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM group %s.', policy_name, group_name) return False return True def attach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_role_policy(policy_arn, role_name) log.info('Attached policy %s to IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM role %s.', policy_name, role_name) return False return True def detach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_role_policy(policy_arn, role_name) log.info('Detached policy %s from IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM role %s.', policy_name, role_name) return False return True def list_entities_for_policy(policy_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities that a policy is attached to. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 params = {} for arg in ('path_prefix', 'entity_filter'): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) while retries: try: allret = { 'policy_groups': [], 'policy_users': [], 'policy_roles': [], } for ret in __utils__['boto.paged_call'](conn.list_entities_for_policy, policy_arn=policy_arn, **params): for k, v in six.iteritems(allret): v.extend(ret.get('list_entities_for_policy_response', {}).get('list_entities_for_policy_result', {}).get(k)) return allret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('Failed to list entities for IAM policy %s: %s', policy_name, e.message) return {} return {} def list_attached_user_policies(user_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given user. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'UserName': user_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedUserPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_user_policies_response', {}).get('list_attached_user_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM user %s.', user_name) return [] def list_attached_group_policies(group_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given group. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'GroupName': group_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedGroupPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_group_policies_response', {}).get('list_attached_group_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM group %s.', group_name) return [] def list_attached_role_policies(role_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'RoleName': role_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedRolePolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_role_policies_response', {}).get('list_attached_role_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM role %s.', role_name) return [] def create_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Create SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.create_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_saml_provider(saml_metadata_document, name) log.info('Successfully created %s SAML provider.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to create SAML provider %s.', name) return False def get_saml_provider_arn(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider_arn my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_saml_providers() for saml_provider in response.list_saml_providers_response.list_saml_providers_result.saml_provider_list: if saml_provider['arn'].endswith(':saml-provider/' + name): return saml_provider['arn'] return False except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to get ARN of SAML provider %s.', name) return False def delete_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Delete SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.delete_saml_provider my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return True conn.delete_saml_provider(saml_provider_arn) log.info('Successfully deleted SAML provider %s.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete SAML provider %s.', name) return False def list_saml_providers(region=None, key=None, keyid=None, profile=None): ''' List SAML providers. CLI Example: .. code-block:: bash salt myminion boto_iam.list_saml_providers ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: providers = [] info = conn.list_saml_providers() for arn in info['list_saml_providers_response']['list_saml_providers_result']['saml_provider_list']: providers.append(arn['arn'].rsplit('/', 1)[1]) return providers except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get list of SAML providers.') return False def get_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider document. CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider arn ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: provider = conn.get_saml_provider(name) return provider['get_saml_provider_response']['get_saml_provider_result']['saml_metadata_document'] except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get SAML provider document %s.', name) return False def update_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Update SAML provider. CLI Example: .. code-block:: bash salt myminion boto_iam.update_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return False if conn.update_saml_provider(name, saml_metadata_document): return True return False except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to update SAML provider %s.', name) return False
saltstack/salt
salt/modules/boto_iam.py
put_user_policy
python
def put_user_policy(user_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_user_policy myuser policyname policyrules ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_user_policy(user_name, policy_name, policy_json) if created: log.info('Created policy %s for IAM user %s.', policy_name, user_name) return True log.error('Could not create policy %s for IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy %s for IAM user %s.', policy_name, user_name) return False
Adds or updates the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_user_policy myuser policyname policyrules
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iam.py#L1426-L1455
[ "def dumps(obj, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.dumps, and assumes that ensure_ascii is False (unless explicitly\n passed as True) for unicode compatibility. Note that setting it to True\n will mess up any unicode characters, as they will be dumped as the string\n literal version of the unicode code point.\n\n On Python 2, encodes the result to a str since json.dumps does not want\n unicode types.\n\n You can pass an alternate json module (loaded via import_json() above)\n using the _json_module argument)\n '''\n json_module = kwargs.pop('_json_module', json)\n orig_enc_func = kwargs.pop('default', lambda x: x)\n\n def _enc_func(obj):\n obj = ThreadLocalProxy.unproxy(obj)\n return orig_enc_func(obj)\n\n if 'ensure_ascii' not in kwargs:\n kwargs['ensure_ascii'] = False\n if six.PY2:\n obj = salt.utils.data.encode(obj)\n return json_module.dumps(obj, default=_enc_func, **kwargs) # future lint: blacklisted-function\n", "def get_user(user_name=None, region=None, key=None, keyid=None, profile=None):\n '''\n Get user information.\n\n .. versionadded:: 2015.8.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_iam.get_user myuser\n '''\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n try:\n info = conn.get_user(user_name)\n if not info:\n return False\n return info\n except boto.exception.BotoServerError as e:\n log.debug(e)\n log.error('Failed to get IAM user %s info.', user_name)\n return False\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon IAM .. versionadded:: 2014.7.0 :configuration: This module accepts explicit iam 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 iam.keyid: GKTADJGHEIQSXMKKRBJ08H iam.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs iam.region: 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: boto ''' # keep lint from choking on _get_conn and _cache_id #pylint: disable=E0602 # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import salt libs from salt.ext import six import salt.utils.compat import salt.utils.json import salt.utils.odict as odict import salt.utils.versions from salt.exceptions import SaltInvocationError # Import third party libs # pylint: disable=unused-import from salt.ext.six.moves.urllib.parse import unquote as _unquote # pylint: disable=no-name-in-module try: import boto import boto.iam import boto3 import botocore logging.getLogger('boto').setLevel(logging.CRITICAL) logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=unused-import log = logging.getLogger(__name__) def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'iam', pack=__salt__) def instance_profile_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an instance profile exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: # Boto weirdly returns an exception here if an instance profile doesn't # exist. conn.get_instance_profile(name) return True except boto.exception.BotoServerError: return False def create_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Create an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.create_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if instance_profile_exists(name, region, key, keyid, profile): return True try: # This call returns an instance profile if successful and an exception # if not. It's annoying. conn.create_instance_profile(name) log.info('Created %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create %s instance profile.', name) return False return True def delete_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Delete an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not instance_profile_exists(name, region, key, keyid, profile): return True try: conn.delete_instance_profile(name) log.info('Deleted %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s instance profile.', name) return False return True def role_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an IAM role exists. CLI Example: .. code-block:: bash salt myminion boto_iam.role_exists myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_role(name) return True except boto.exception.BotoServerError: return False def describe_role(name, region=None, key=None, keyid=None, profile=None): ''' Get information for a role. CLI Example: .. code-block:: bash salt myminion boto_iam.describe_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_role(name) if not info: return False role = info.get_role_response.get_role_result.role role['assume_role_policy_document'] = salt.utils.json.loads(_unquote( role.assume_role_policy_document )) # If Sid wasn't defined by the user, boto will still return a Sid in # each policy. To properly check idempotently, let's remove the Sid # from the return if it's not actually set. for policy_key, policy in role['assume_role_policy_document'].items(): if policy_key == 'Statement': for val in policy: if 'Sid' in val and not val['Sid']: del val['Sid'] return role except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get %s information.', name) return False def create_user(user_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_user myuser ''' if not path: path = '/' if get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_user(user_name, path) log.info('Created IAM user : %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM user %s.', user_name) return False def get_all_access_keys(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all access keys from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_access_keys myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.get_all_access_keys(user_name, marker, max_items) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get access keys for IAM user %s.', user_name) return six.text_type(e) def create_access_key(user_name, region=None, key=None, keyid=None, profile=None): ''' Create access key id for a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.create_access_key(user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create access key.') return six.text_type(e) def delete_access_key(access_key_id, user_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete access key id from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_access_key(access_key_id, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete access key id %s.', access_key_id) return six.text_type(e) def delete_user(user_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user myuser ''' if not get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.delete_user(user_name) log.info('Deleted IAM user : %s .', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM user %s', user_name) return six.text_type(e) def get_user(user_name=None, region=None, key=None, keyid=None, profile=None): ''' Get user information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user(user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM user %s info.', user_name) return False def create_group(group_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_group group ''' if not path: path = '/' if get_group(group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_group(group_name, path) log.info('Created IAM group : %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM group %s.', group_name) return False def get_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group(group_name, max_items=1) if not info: return False return info['get_group_response']['get_group_result']['group'] except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_group_members(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: marker = None truncated = True users = [] while truncated: info = conn.get_group(group_name, marker=marker, max_items=1000) if not info: return False truncated = bool(info['get_group_response']['get_group_result']['is_truncated']) if truncated and 'marker' in info['get_group_response']['get_group_result']: marker = info['get_group_response']['get_group_result']['marker'] else: marker = None truncated = False users += info['get_group_response']['get_group_result']['users'] return users except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get members for IAM group %s.', group_name) return False def add_user_to_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Add user to group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.add_user_to_group myuser mygroup ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('Username : %s does not exist.', user_name) return False if user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.add_user_to_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add IAM user %s to group %s.', user_name, group_name) return False def user_exists_in_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Check if user exists in group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.user_exists_in_group myuser mygroup ''' # TODO this should probably use boto.iam.get_groups_for_user users = get_group_members( group_name=group_name, region=region, key=key, keyid=keyid, profile=profile ) if users: for _user in users: if user_name == _user['user_name']: log.debug('IAM user %s is already in IAM group %s.', user_name, group_name) return True return False def remove_user_from_group(group_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Remove user from group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.remove_user_from_group mygroup myuser ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist.', user_name) return False if not user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.remove_user_from_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove IAM user %s from group %s', user_name, group_name) return False def put_group_policy(group_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_group_policy mygroup policyname policyrules ''' group = get_group(group_name, region=region, key=key, keyid=keyid, profile=profile) if not group: log.error('Group %s does not exist', group_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_group_policy(group_name, policy_name, policy_json) if created: log.info('Created policy for IAM group %s.', group_name) return True log.error('Could not create policy for IAM group %s', group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy for IAM group %s', group_name) return False def delete_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group_policy mygroup mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_group_policy( group_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_group_policy(group_name, policy_name) log.info('Successfully deleted policy %s for IAM group %s.', policy_name, group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM group %s.', policy_name, group_name) return False def get_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group_policy mygroup policyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group_policy(group_name, policy_name) log.debug('info for group policy is : %s', info) if not info: return False info = info.get_group_policy_response.get_group_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_all_groups(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM group details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_groups ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _groups = conn.get_all_groups(path_prefix=path_prefix) groups = _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) while marker: _groups = conn.get_all_groups(path_prefix=path_prefix, marker=marker) groups = groups + _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) return groups def get_all_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.get_all_instance_profiles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) marker = False profiles = [] while marker is not None: marker = marker if marker else None p = conn.list_instance_profiles(path_prefix=path_prefix, marker=marker) res = p.list_instance_profiles_response.list_instance_profiles_result profiles += res.instance_profiles marker = getattr(res, 'marker', None) return profiles def list_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' List all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.list_instance_profiles ''' p = get_all_instance_profiles(path_prefix, region, key, keyid, profile) return [i['instance_profile_name'] for i in p] def get_all_group_policies(group_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a group. CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_group_policies mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False try: response = conn.get_all_group_policies(group_name) _list = response.list_group_policies_response.list_group_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def delete_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _group = get_group( group_name, region, key, keyid, profile ) if not _group: return True try: conn.delete_group(group_name) log.info('Successfully deleted IAM group %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM group %s.', group_name) return False def create_login_profile(user_name, password, region=None, key=None, keyid=None, profile=None): ''' Creates a login profile for the specified user, give the user the ability to access AWS services and the AWS Management Console. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_login_profile user_name password ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.create_login_profile(user_name, password) log.info('Created profile for IAM user %s.', user_name) return info except boto.exception.BotoServerError as e: log.debug(e) if 'Conflict' in e: log.info('Profile already exists for IAM user %s.', user_name) return 'Conflict' log.error('Failed to update profile for IAM user %s.', user_name) return False def delete_login_profile(user_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a login profile for the specified user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_login_profile user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.delete_login_profile(user_name) log.info('Deleted login profile for IAM user %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Login profile already deleted for IAM user %s.', user_name) return True log.error('Failed to delete login profile for IAM user %s.', user_name) return False def get_all_mfa_devices(user_name, region=None, key=None, keyid=None, profile=None): ''' Get all MFA devices associated with an IAM user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_mfa_devices user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: result = conn.get_all_mfa_devices(user_name) devices = result['list_mfa_devices_response']['list_mfa_devices_result']['mfa_devices'] return devices except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Could not find IAM user %s.', user_name) return [] log.error('Failed to get all MFA devices for IAM user %s.', user_name) return False def deactivate_mfa_device(user_name, serial, region=None, key=None, keyid=None, profile=None): ''' Deactivates the specified MFA device and removes it from association with the user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.deactivate_mfa_device user_name serial_num ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.deactivate_mfa_device(user_name, serial) log.info('Deactivated MFA device %s for IAM user %s.', serial, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('MFA device %s not associated with IAM user %s.', serial, user_name) return True log.error('Failed to deactivate MFA device %s for IAM user %s.', serial, user_name) return False def delete_virtual_mfa_device(serial, region=None, key=None, keyid=None, profile=None): ''' Deletes the specified virtual MFA device. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_virtual_mfa_device serial_num ''' conn = __utils__['boto3.get_connection_func']('iam')() try: conn.delete_virtual_mfa_device(SerialNumber=serial) log.info('Deleted virtual MFA device %s.', serial) return True except botocore.exceptions.ClientError as e: log.debug(e) if 'NoSuchEntity' in six.text_type(e): log.info('Virtual MFA device %s not found.', serial) return True log.error('Failed to delete virtual MFA device %s.', serial) return False def update_account_password_policy(allow_users_to_change_password=None, hard_expiry=None, max_password_age=None, minimum_password_length=None, password_reuse_prevention=None, require_lowercase_characters=None, require_numbers=None, require_symbols=None, require_uppercase_characters=None, region=None, key=None, keyid=None, profile=None): ''' Update the password policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_account_password_policy True ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.update_account_password_policy(allow_users_to_change_password, hard_expiry, max_password_age, minimum_password_length, password_reuse_prevention, require_lowercase_characters, require_numbers, require_symbols, require_uppercase_characters) log.info('The password policy has been updated.') return True except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy' log.error(msg) return False def get_account_policy(region=None, key=None, keyid=None, profile=None): ''' Get account policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_account_password_policy() return info.get_account_password_policy_response.get_account_password_policy_result.password_policy except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy.' log.error(msg) return False def create_role(name, policy_document=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Create an instance role. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if role_exists(name, region, key, keyid, profile): return True if not policy_document: policy_document = None try: conn.create_role(name, assume_role_policy_document=policy_document, path=path) log.info('Created IAM role %s.', name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to create IAM role %s.', name) return False def delete_role(name, region=None, key=None, keyid=None, profile=None): ''' Delete an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(name, region, key, keyid, profile): return True try: conn.delete_role(name) log.info('Deleted %s IAM role.', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s IAM role.', name) return False def profile_associated(role_name, profile_name, region, key, keyid, profile): ''' Check to see if an instance profile is associated with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.profile_associated myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # The IAM module of boto doesn't return objects. Instead you need to grab # values through its properties. Sigh. try: profiles = conn.list_instance_profiles_for_role(role_name) except boto.exception.BotoServerError as e: log.debug(e) return False profiles = profiles.list_instance_profiles_for_role_response profiles = profiles.list_instance_profiles_for_role_result profiles = profiles.instance_profiles for profile in profiles: if profile.instance_profile_name == profile_name: return True return False def associate_profile_to_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Associate an instance profile with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.associate_profile_to_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if associated: return True else: try: conn.add_role_to_instance_profile(profile_name, role_name) log.info('Added %s instance profile to IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add %s instance profile to IAM role %s', profile_name, role_name) return False def disassociate_profile_from_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Disassociate an instance profile from an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.disassociate_profile_from_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if not associated: return True else: try: conn.remove_role_from_instance_profile(profile_name, role_name) log.info('Removed %s instance profile from IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove %s instance profile from IAM role %s.', profile_name, role_name) return False def list_role_policies(role_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_role_policies myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_role_policies(role_name) _list = response.list_role_policies_response.list_role_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def get_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.get_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: _policy = conn.get_role_policy(role_name, policy_name) # I _hate_ you for not giving me an object boto. _policy = _policy.get_role_policy_response.policy_document # Policy is url encoded _policy = _unquote(_policy) _policy = salt.utils.json.loads(_policy, object_pairs_hook=odict.OrderedDict) return _policy except boto.exception.BotoServerError: return {} def create_role_policy(role_name, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Create or modify a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role_policy myirole mypolicy '{"MyPolicy": "Statement": [{"Action": ["sqs:*"], "Effect": "Allow", "Resource": ["arn:aws:sqs:*:*:*"], "Sid": "MyPolicySqs1"}]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) mode = 'create' if _policy: if _policy == policy: return True mode = 'modify' if isinstance(policy, six.string_types): policy = salt.utils.json.loads(policy, object_pairs_hook=odict.OrderedDict) try: _policy = salt.utils.json.dumps(policy) conn.put_role_policy(role_name, policy_name, _policy) if mode == 'create': msg = 'Successfully added policy %s to IAM role %s.' else: msg = 'Successfully modified policy %s for IAM role %s.' log.info(msg, policy_name, role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to %s policy %s for IAM role %s.', mode, policy_name, role_name) return False def delete_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) if not _policy: return True try: conn.delete_role_policy(role_name, policy_name) log.info('Successfully deleted policy %s for IAM role %s.', policy_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM role %s.', policy_name, role_name) return False def update_assume_role_policy(role_name, policy_document, region=None, key=None, keyid=None, profile=None): ''' Update an assume role policy for a role. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_assume_role_policy myrole '{"Statement":"..."}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(policy_document, six.string_types): policy_document = salt.utils.json.loads(policy_document, object_pairs_hook=odict.OrderedDict) try: _policy_document = salt.utils.json.dumps(policy_document) conn.update_assume_role_policy(role_name, _policy_document) log.info('Successfully updated assume role policy for IAM role %s.', role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to update assume role policy for IAM role %s.', role_name) return False def build_policy(region=None, key=None, keyid=None, profile=None): ''' Build a default assume role policy. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.build_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if hasattr(conn, 'build_policy'): policy = salt.utils.json.loads(conn.build_policy()) elif hasattr(conn, '_build_policy'): policy = salt.utils.json.loads(conn._build_policy()) else: return {} # The format we get from build_policy isn't going to be what we get back # from AWS for the exact same policy. AWS converts single item list values # into strings, so let's do the same here. for key, policy_val in policy.items(): for statement in policy_val: if (isinstance(statement['Action'], list) and len(statement['Action']) == 1): statement['Action'] = statement['Action'][0] if (isinstance(statement['Principal']['Service'], list) and len(statement['Principal']['Service']) == 1): statement['Principal']['Service'] = statement['Principal']['Service'][0] # build_policy doesn't add a version field, which AWS is going to set to a # default value, when we get it back, so let's set it. policy['Version'] = '2008-10-17' return policy def get_account_id(region=None, key=None, keyid=None, profile=None): ''' Get a the AWS account id associated with the used credentials. CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_id ''' cache_key = 'boto_iam.account_id' if cache_key not in __context__: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_user() # The get_user call returns an user ARN: # arn:aws:iam::027050522557:user/salt-test arn = ret['get_user_response']['get_user_result']['user']['arn'] account_id = arn.split(':')[4] except boto.exception.BotoServerError: # If call failed, then let's try to get the ARN from the metadata timeout = boto.config.getfloat( 'Boto', 'metadata_service_timeout', 1.0 ) attempts = boto.config.getint( 'Boto', 'metadata_service_num_attempts', 1 ) identity = boto.utils.get_instance_identity( timeout=timeout, num_retries=attempts ) try: account_id = identity['document']['accountId'] except KeyError: log.error('Failed to get account id from instance_identity in' ' boto_iam.get_account_id.') __context__[cache_key] = account_id return __context__[cache_key] def get_all_roles(path_prefix=None, region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM role details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_roles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _roles = conn.list_roles(path_prefix=path_prefix) roles = _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) while marker: _roles = conn.list_roles(path_prefix=path_prefix, marker=marker) roles = roles + _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) return roles def get_all_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM user details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_users ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _users = conn.get_all_users(path_prefix=path_prefix) users = _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) while marker: _users = conn.get_all_users(path_prefix=path_prefix, marker=marker) users = users + _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) return users def get_all_user_policies(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all user policies. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_user_policies myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_all_user_policies(user_name, marker, max_items) if not info: return False _list = info.list_user_policies_response.list_user_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policies for user %s.', user_name) return False def get_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user_policy myuser mypolicyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user_policy(user_name, policy_name) log.debug('Info for IAM user %s policy %s: %s.', user_name, policy_name, info) if not info: return False info = info.get_user_policy_response.get_user_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policy %s for IAM user %s.', policy_name, user_name) return False def delete_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user_policy myuser mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_user_policy( user_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_user_policy(user_name, policy_name) log.info('Successfully deleted policy %s for IAM user %s.', policy_name, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM user %s.', policy_name, user_name) return False def upload_server_cert(cert_name, cert_body, private_key, cert_chain=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Upload a certificate to Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.upload_server_cert mycert_name crt priv_key :param cert_name: The name for the server certificate. Do not include the path in this value. :param cert_body: The contents of the public key certificate in PEM-encoded format. :param private_key: The contents of the private key in PEM-encoded format. :param cert_chain: The contents of the certificate chain. This is typically a concatenation of the PEM-encoded public key certificates of the chain. :param path: The path for the server certificate. :param region: The name of the region to connect to. :param key: The key to be used in order to connect :param keyid: The keyid to be used in order to connect :param profile: The profile that contains a dict of region, key, keyid :return: True / False ''' exists = get_server_certificate(cert_name, region, key, keyid, profile) if exists: return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.upload_server_cert(cert_name, cert_body, private_key, cert_chain) log.info('Created certificate %s.', cert_name) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to failed to create certificate %s.', cert_name) return False def list_server_certificates(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Lists the server certificates stored in IAM that have the specified path prefix. .. versionadded:: ??? :param path_prefix: The path prefix for filtering the results. For example: /company/servercerts would get all server certificates for which the path starts with /company/servercerts . This parameter is optional. If it is not included, it defaults to a slash (/), listing all server certificates. This parameter allows (per its regex pattern) a string of characters consisting of either a forward slash (/) by itself or a string that must begin and end with forward slashes. In addition, it can contain any ASCII character from the ! (u0021) through the DEL character (u007F), including most punctuation characters, digits, and upper and lowercased letters. CLI Example: .. code-block:: bash salt myminion boto_iam.list_server_certificates path_prefix=/somepath/ ''' retries = 10 sleep = 6 conn = __utils__['boto3.get_connection']('iam', region=region, key=key, keyid=keyid, profile=profile) Items = [] while retries: try: log.debug('Garnering list of IAM Server Certificates') IsTruncated = True while IsTruncated: kwargs = {'PathPrefix': path_prefix} ret = conn.list_server_certificates(**kwargs) Items += ret.get('ServerCertificateMetadataList', []) IsTruncated = ret.get('IsTruncated') kwargs.update({'Marker': ret.get('Marker')}) return Items except botocore.exceptions.ParamValidationError as err: raise SaltInvocationError(str(err)) except botocore.exceptions.ClientError as err: if retries and jmespath.search('Error.Code', err.response) == 'Throttling': retries -= 1 log.debug('Throttled by AWS API, retrying in %s seconds...', sleep) time.sleep(sleep) continue log.error('Failed to list IAM Server Certificates: %s', err.message) return None def get_server_certificate(cert_name, region=None, key=None, keyid=None, profile=None): ''' Returns certificate information from Amazon .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_server_certificate mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_server_certificate(cert_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get certificate %s information.', cert_name) return False def delete_server_cert(cert_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a certificate from Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_server_cert mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_server_cert(cert_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete certificate %s.', cert_name) return False def export_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM user details. Produces results that can be used to create an sls file. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.export_users --out=txt | sed "s/local: //" > iam_users.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() users = get_all_users(path_prefix, region, key, keyid, profile) for user in users: name = user.user_name _policies = conn.get_all_user_policies(name, max_items=100) _policies = _policies.list_user_policies_response.list_user_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_user_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_user_policy_response.get_user_policy_result.policy_document )) policies[policy_name] = _policy user_sls = [] user_sls.append({"name": name}) user_sls.append({"policies": policies}) user_sls.append({"path": user.path}) results["manage user " + name] = {"boto_iam.user_present": user_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def export_roles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM role details. Produces results that can be used to create an sls file. CLI Example: salt-call boto_iam.export_roles --out=txt | sed "s/local: //" > iam_roles.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() roles = get_all_roles(path_prefix, region, key, keyid, profile) for role in roles: name = role.role_name _policies = conn.list_role_policies(name, max_items=100) _policies = _policies.list_role_policies_response.list_role_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_role_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_role_policy_response.get_role_policy_result.policy_document )) policies[policy_name] = _policy role_sls = [] role_sls.append({"name": name}) role_sls.append({"policies": policies}) role_sls.append({'policy_document': salt.utils.json.loads(_unquote(role.assume_role_policy_document))}) role_sls.append({"path": role.path}) results["manage role " + name] = {"boto_iam_role.present": role_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def _get_policy_arn(name, region=None, key=None, keyid=None, profile=None): if name.startswith('arn:aws:iam:'): return name account_id = get_account_id( region=region, key=key, keyid=keyid, profile=profile ) return 'arn:aws:iam::{0}:policy/{1}'.format(account_id, name) def policy_exists(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return True except boto.exception.BotoServerError: return False def get_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return ret.get('get_policy_response', {}).get('get_policy_result', {}) except boto.exception.BotoServerError: return None def create_policy(policy_name, policy_document, path=None, description=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in 'path', 'description': if locals()[arg] is not None: params[arg] = locals()[arg] if policy_exists(policy_name, region, key, keyid, profile): return True try: conn.create_policy(policy_name, policy_document, **params) log.info('Created IAM policy %s.', policy_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s.', policy_name) return False return True def delete_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_exists(policy_arn, region, key, keyid, profile): return True try: conn.delete_policy(policy_arn) log.info('Deleted %s policy.', policy_name) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete %s policy: %s.', policy_name, aws.get('message')) return False return True def list_policies(region=None, key=None, keyid=None, profile=None): ''' List policies. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policies ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: policies = [] for ret in __utils__['boto.paged_call'](conn.list_policies): policies.append(ret.get('list_policies_response', {}).get('list_policies_result', {}).get('policies')) return policies except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to list policy versions.' log.error(msg) return [] def policy_version_exists(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.get_policy_version(policy_arn, version_id) return True except boto.exception.BotoServerError: return False def get_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy_version(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile), version_id) retval = ret.get('get_policy_version_response', {}).get('get_policy_version_result', {}).get('policy_version', {}) retval['document'] = _unquote(retval.get('document')) return {'policy_version': retval} except boto.exception.BotoServerError: return None def create_policy_version(policy_name, policy_document, set_as_default=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy version. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy_version mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in ('set_as_default',): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.create_policy_version(policy_arn, policy_document, **params) vid = ret.get('create_policy_version_response', {}).get('create_policy_version_result', {}).get('policy_version', {}).get('version_id') log.info('Created IAM policy %s version %s.', policy_name, vid) return {'created': True, 'version_id': vid} except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s version %s.', policy_name, vid) return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Delete a policy version. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_version_exists(policy_arn, version_id, region, key, keyid, profile): return True try: conn.delete_policy_version(policy_arn, version_id) log.info('Deleted IAM policy %s version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete IAM policy %s version %s: %s', policy_name, version_id, aws.get('message')) return False return True def list_policy_versions(policy_name, region=None, key=None, keyid=None, profile=None): ''' List versions of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policy_versions mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.list_policy_versions(policy_arn) return ret.get('list_policy_versions_response', {}).get('list_policy_versions_result', {}).get('versions') except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list versions for IAM policy %s.', policy_name) return [] def set_default_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Set the default version of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.set_default_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.set_default_policy_version(policy_arn, version_id) log.info('Set %s policy to version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to set %s policy to version %s: %s', policy_name, version_id, aws.get('message')) return False return True def attach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_user_policy(policy_arn, user_name) log.info('Attached policy %s to IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach %s policy to IAM user %s.', policy_name, user_name) return False return True def detach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_user_policy(policy_arn, user_name) log.info('Detached %s policy from IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach %s policy from IAM user %s.', policy_name, user_name) return False return True def attach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_group_policy(policy_arn, group_name) log.info('Attached policy %s to IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM group %s.', policy_name, group_name) return False return True def detach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_group_policy(policy_arn, group_name) log.info('Detached policy %s from IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM group %s.', policy_name, group_name) return False return True def attach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_role_policy(policy_arn, role_name) log.info('Attached policy %s to IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM role %s.', policy_name, role_name) return False return True def detach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_role_policy(policy_arn, role_name) log.info('Detached policy %s from IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM role %s.', policy_name, role_name) return False return True def list_entities_for_policy(policy_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities that a policy is attached to. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 params = {} for arg in ('path_prefix', 'entity_filter'): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) while retries: try: allret = { 'policy_groups': [], 'policy_users': [], 'policy_roles': [], } for ret in __utils__['boto.paged_call'](conn.list_entities_for_policy, policy_arn=policy_arn, **params): for k, v in six.iteritems(allret): v.extend(ret.get('list_entities_for_policy_response', {}).get('list_entities_for_policy_result', {}).get(k)) return allret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('Failed to list entities for IAM policy %s: %s', policy_name, e.message) return {} return {} def list_attached_user_policies(user_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given user. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'UserName': user_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedUserPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_user_policies_response', {}).get('list_attached_user_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM user %s.', user_name) return [] def list_attached_group_policies(group_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given group. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'GroupName': group_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedGroupPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_group_policies_response', {}).get('list_attached_group_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM group %s.', group_name) return [] def list_attached_role_policies(role_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'RoleName': role_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedRolePolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_role_policies_response', {}).get('list_attached_role_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM role %s.', role_name) return [] def create_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Create SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.create_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_saml_provider(saml_metadata_document, name) log.info('Successfully created %s SAML provider.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to create SAML provider %s.', name) return False def get_saml_provider_arn(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider_arn my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_saml_providers() for saml_provider in response.list_saml_providers_response.list_saml_providers_result.saml_provider_list: if saml_provider['arn'].endswith(':saml-provider/' + name): return saml_provider['arn'] return False except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to get ARN of SAML provider %s.', name) return False def delete_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Delete SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.delete_saml_provider my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return True conn.delete_saml_provider(saml_provider_arn) log.info('Successfully deleted SAML provider %s.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete SAML provider %s.', name) return False def list_saml_providers(region=None, key=None, keyid=None, profile=None): ''' List SAML providers. CLI Example: .. code-block:: bash salt myminion boto_iam.list_saml_providers ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: providers = [] info = conn.list_saml_providers() for arn in info['list_saml_providers_response']['list_saml_providers_result']['saml_provider_list']: providers.append(arn['arn'].rsplit('/', 1)[1]) return providers except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get list of SAML providers.') return False def get_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider document. CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider arn ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: provider = conn.get_saml_provider(name) return provider['get_saml_provider_response']['get_saml_provider_result']['saml_metadata_document'] except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get SAML provider document %s.', name) return False def update_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Update SAML provider. CLI Example: .. code-block:: bash salt myminion boto_iam.update_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return False if conn.update_saml_provider(name, saml_metadata_document): return True return False except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to update SAML provider %s.', name) return False
saltstack/salt
salt/modules/boto_iam.py
delete_user_policy
python
def delete_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user_policy myuser mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_user_policy( user_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_user_policy(user_name, policy_name) log.info('Successfully deleted policy %s for IAM user %s.', policy_name, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM user %s.', policy_name, user_name) return False
Delete a user policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user_policy myuser mypolicy
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iam.py#L1458-L1483
[ "def get_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None):\n '''\n Retrieves the specified policy document for the specified user.\n\n .. versionadded:: 2015.8.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_iam.get_user_policy myuser mypolicyname\n '''\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n try:\n info = conn.get_user_policy(user_name, policy_name)\n log.debug('Info for IAM user %s policy %s: %s.', user_name, policy_name, info)\n if not info:\n return False\n info = info.get_user_policy_response.get_user_policy_result.policy_document\n info = _unquote(info)\n info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict)\n return info\n except boto.exception.BotoServerError as e:\n log.debug(e)\n log.error('Failed to get policy %s for IAM user %s.', policy_name, user_name)\n return False\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon IAM .. versionadded:: 2014.7.0 :configuration: This module accepts explicit iam 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 iam.keyid: GKTADJGHEIQSXMKKRBJ08H iam.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs iam.region: 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: boto ''' # keep lint from choking on _get_conn and _cache_id #pylint: disable=E0602 # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import salt libs from salt.ext import six import salt.utils.compat import salt.utils.json import salt.utils.odict as odict import salt.utils.versions from salt.exceptions import SaltInvocationError # Import third party libs # pylint: disable=unused-import from salt.ext.six.moves.urllib.parse import unquote as _unquote # pylint: disable=no-name-in-module try: import boto import boto.iam import boto3 import botocore logging.getLogger('boto').setLevel(logging.CRITICAL) logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=unused-import log = logging.getLogger(__name__) def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'iam', pack=__salt__) def instance_profile_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an instance profile exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: # Boto weirdly returns an exception here if an instance profile doesn't # exist. conn.get_instance_profile(name) return True except boto.exception.BotoServerError: return False def create_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Create an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.create_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if instance_profile_exists(name, region, key, keyid, profile): return True try: # This call returns an instance profile if successful and an exception # if not. It's annoying. conn.create_instance_profile(name) log.info('Created %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create %s instance profile.', name) return False return True def delete_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Delete an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not instance_profile_exists(name, region, key, keyid, profile): return True try: conn.delete_instance_profile(name) log.info('Deleted %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s instance profile.', name) return False return True def role_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an IAM role exists. CLI Example: .. code-block:: bash salt myminion boto_iam.role_exists myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_role(name) return True except boto.exception.BotoServerError: return False def describe_role(name, region=None, key=None, keyid=None, profile=None): ''' Get information for a role. CLI Example: .. code-block:: bash salt myminion boto_iam.describe_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_role(name) if not info: return False role = info.get_role_response.get_role_result.role role['assume_role_policy_document'] = salt.utils.json.loads(_unquote( role.assume_role_policy_document )) # If Sid wasn't defined by the user, boto will still return a Sid in # each policy. To properly check idempotently, let's remove the Sid # from the return if it's not actually set. for policy_key, policy in role['assume_role_policy_document'].items(): if policy_key == 'Statement': for val in policy: if 'Sid' in val and not val['Sid']: del val['Sid'] return role except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get %s information.', name) return False def create_user(user_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_user myuser ''' if not path: path = '/' if get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_user(user_name, path) log.info('Created IAM user : %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM user %s.', user_name) return False def get_all_access_keys(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all access keys from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_access_keys myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.get_all_access_keys(user_name, marker, max_items) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get access keys for IAM user %s.', user_name) return six.text_type(e) def create_access_key(user_name, region=None, key=None, keyid=None, profile=None): ''' Create access key id for a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.create_access_key(user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create access key.') return six.text_type(e) def delete_access_key(access_key_id, user_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete access key id from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_access_key(access_key_id, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete access key id %s.', access_key_id) return six.text_type(e) def delete_user(user_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user myuser ''' if not get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.delete_user(user_name) log.info('Deleted IAM user : %s .', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM user %s', user_name) return six.text_type(e) def get_user(user_name=None, region=None, key=None, keyid=None, profile=None): ''' Get user information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user(user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM user %s info.', user_name) return False def create_group(group_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_group group ''' if not path: path = '/' if get_group(group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_group(group_name, path) log.info('Created IAM group : %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM group %s.', group_name) return False def get_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group(group_name, max_items=1) if not info: return False return info['get_group_response']['get_group_result']['group'] except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_group_members(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: marker = None truncated = True users = [] while truncated: info = conn.get_group(group_name, marker=marker, max_items=1000) if not info: return False truncated = bool(info['get_group_response']['get_group_result']['is_truncated']) if truncated and 'marker' in info['get_group_response']['get_group_result']: marker = info['get_group_response']['get_group_result']['marker'] else: marker = None truncated = False users += info['get_group_response']['get_group_result']['users'] return users except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get members for IAM group %s.', group_name) return False def add_user_to_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Add user to group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.add_user_to_group myuser mygroup ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('Username : %s does not exist.', user_name) return False if user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.add_user_to_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add IAM user %s to group %s.', user_name, group_name) return False def user_exists_in_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Check if user exists in group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.user_exists_in_group myuser mygroup ''' # TODO this should probably use boto.iam.get_groups_for_user users = get_group_members( group_name=group_name, region=region, key=key, keyid=keyid, profile=profile ) if users: for _user in users: if user_name == _user['user_name']: log.debug('IAM user %s is already in IAM group %s.', user_name, group_name) return True return False def remove_user_from_group(group_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Remove user from group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.remove_user_from_group mygroup myuser ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist.', user_name) return False if not user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.remove_user_from_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove IAM user %s from group %s', user_name, group_name) return False def put_group_policy(group_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_group_policy mygroup policyname policyrules ''' group = get_group(group_name, region=region, key=key, keyid=keyid, profile=profile) if not group: log.error('Group %s does not exist', group_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_group_policy(group_name, policy_name, policy_json) if created: log.info('Created policy for IAM group %s.', group_name) return True log.error('Could not create policy for IAM group %s', group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy for IAM group %s', group_name) return False def delete_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group_policy mygroup mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_group_policy( group_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_group_policy(group_name, policy_name) log.info('Successfully deleted policy %s for IAM group %s.', policy_name, group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM group %s.', policy_name, group_name) return False def get_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group_policy mygroup policyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group_policy(group_name, policy_name) log.debug('info for group policy is : %s', info) if not info: return False info = info.get_group_policy_response.get_group_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_all_groups(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM group details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_groups ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _groups = conn.get_all_groups(path_prefix=path_prefix) groups = _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) while marker: _groups = conn.get_all_groups(path_prefix=path_prefix, marker=marker) groups = groups + _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) return groups def get_all_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.get_all_instance_profiles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) marker = False profiles = [] while marker is not None: marker = marker if marker else None p = conn.list_instance_profiles(path_prefix=path_prefix, marker=marker) res = p.list_instance_profiles_response.list_instance_profiles_result profiles += res.instance_profiles marker = getattr(res, 'marker', None) return profiles def list_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' List all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.list_instance_profiles ''' p = get_all_instance_profiles(path_prefix, region, key, keyid, profile) return [i['instance_profile_name'] for i in p] def get_all_group_policies(group_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a group. CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_group_policies mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False try: response = conn.get_all_group_policies(group_name) _list = response.list_group_policies_response.list_group_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def delete_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _group = get_group( group_name, region, key, keyid, profile ) if not _group: return True try: conn.delete_group(group_name) log.info('Successfully deleted IAM group %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM group %s.', group_name) return False def create_login_profile(user_name, password, region=None, key=None, keyid=None, profile=None): ''' Creates a login profile for the specified user, give the user the ability to access AWS services and the AWS Management Console. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_login_profile user_name password ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.create_login_profile(user_name, password) log.info('Created profile for IAM user %s.', user_name) return info except boto.exception.BotoServerError as e: log.debug(e) if 'Conflict' in e: log.info('Profile already exists for IAM user %s.', user_name) return 'Conflict' log.error('Failed to update profile for IAM user %s.', user_name) return False def delete_login_profile(user_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a login profile for the specified user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_login_profile user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.delete_login_profile(user_name) log.info('Deleted login profile for IAM user %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Login profile already deleted for IAM user %s.', user_name) return True log.error('Failed to delete login profile for IAM user %s.', user_name) return False def get_all_mfa_devices(user_name, region=None, key=None, keyid=None, profile=None): ''' Get all MFA devices associated with an IAM user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_mfa_devices user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: result = conn.get_all_mfa_devices(user_name) devices = result['list_mfa_devices_response']['list_mfa_devices_result']['mfa_devices'] return devices except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Could not find IAM user %s.', user_name) return [] log.error('Failed to get all MFA devices for IAM user %s.', user_name) return False def deactivate_mfa_device(user_name, serial, region=None, key=None, keyid=None, profile=None): ''' Deactivates the specified MFA device and removes it from association with the user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.deactivate_mfa_device user_name serial_num ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.deactivate_mfa_device(user_name, serial) log.info('Deactivated MFA device %s for IAM user %s.', serial, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('MFA device %s not associated with IAM user %s.', serial, user_name) return True log.error('Failed to deactivate MFA device %s for IAM user %s.', serial, user_name) return False def delete_virtual_mfa_device(serial, region=None, key=None, keyid=None, profile=None): ''' Deletes the specified virtual MFA device. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_virtual_mfa_device serial_num ''' conn = __utils__['boto3.get_connection_func']('iam')() try: conn.delete_virtual_mfa_device(SerialNumber=serial) log.info('Deleted virtual MFA device %s.', serial) return True except botocore.exceptions.ClientError as e: log.debug(e) if 'NoSuchEntity' in six.text_type(e): log.info('Virtual MFA device %s not found.', serial) return True log.error('Failed to delete virtual MFA device %s.', serial) return False def update_account_password_policy(allow_users_to_change_password=None, hard_expiry=None, max_password_age=None, minimum_password_length=None, password_reuse_prevention=None, require_lowercase_characters=None, require_numbers=None, require_symbols=None, require_uppercase_characters=None, region=None, key=None, keyid=None, profile=None): ''' Update the password policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_account_password_policy True ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.update_account_password_policy(allow_users_to_change_password, hard_expiry, max_password_age, minimum_password_length, password_reuse_prevention, require_lowercase_characters, require_numbers, require_symbols, require_uppercase_characters) log.info('The password policy has been updated.') return True except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy' log.error(msg) return False def get_account_policy(region=None, key=None, keyid=None, profile=None): ''' Get account policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_account_password_policy() return info.get_account_password_policy_response.get_account_password_policy_result.password_policy except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy.' log.error(msg) return False def create_role(name, policy_document=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Create an instance role. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if role_exists(name, region, key, keyid, profile): return True if not policy_document: policy_document = None try: conn.create_role(name, assume_role_policy_document=policy_document, path=path) log.info('Created IAM role %s.', name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to create IAM role %s.', name) return False def delete_role(name, region=None, key=None, keyid=None, profile=None): ''' Delete an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(name, region, key, keyid, profile): return True try: conn.delete_role(name) log.info('Deleted %s IAM role.', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s IAM role.', name) return False def profile_associated(role_name, profile_name, region, key, keyid, profile): ''' Check to see if an instance profile is associated with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.profile_associated myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # The IAM module of boto doesn't return objects. Instead you need to grab # values through its properties. Sigh. try: profiles = conn.list_instance_profiles_for_role(role_name) except boto.exception.BotoServerError as e: log.debug(e) return False profiles = profiles.list_instance_profiles_for_role_response profiles = profiles.list_instance_profiles_for_role_result profiles = profiles.instance_profiles for profile in profiles: if profile.instance_profile_name == profile_name: return True return False def associate_profile_to_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Associate an instance profile with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.associate_profile_to_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if associated: return True else: try: conn.add_role_to_instance_profile(profile_name, role_name) log.info('Added %s instance profile to IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add %s instance profile to IAM role %s', profile_name, role_name) return False def disassociate_profile_from_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Disassociate an instance profile from an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.disassociate_profile_from_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if not associated: return True else: try: conn.remove_role_from_instance_profile(profile_name, role_name) log.info('Removed %s instance profile from IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove %s instance profile from IAM role %s.', profile_name, role_name) return False def list_role_policies(role_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_role_policies myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_role_policies(role_name) _list = response.list_role_policies_response.list_role_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def get_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.get_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: _policy = conn.get_role_policy(role_name, policy_name) # I _hate_ you for not giving me an object boto. _policy = _policy.get_role_policy_response.policy_document # Policy is url encoded _policy = _unquote(_policy) _policy = salt.utils.json.loads(_policy, object_pairs_hook=odict.OrderedDict) return _policy except boto.exception.BotoServerError: return {} def create_role_policy(role_name, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Create or modify a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role_policy myirole mypolicy '{"MyPolicy": "Statement": [{"Action": ["sqs:*"], "Effect": "Allow", "Resource": ["arn:aws:sqs:*:*:*"], "Sid": "MyPolicySqs1"}]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) mode = 'create' if _policy: if _policy == policy: return True mode = 'modify' if isinstance(policy, six.string_types): policy = salt.utils.json.loads(policy, object_pairs_hook=odict.OrderedDict) try: _policy = salt.utils.json.dumps(policy) conn.put_role_policy(role_name, policy_name, _policy) if mode == 'create': msg = 'Successfully added policy %s to IAM role %s.' else: msg = 'Successfully modified policy %s for IAM role %s.' log.info(msg, policy_name, role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to %s policy %s for IAM role %s.', mode, policy_name, role_name) return False def delete_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) if not _policy: return True try: conn.delete_role_policy(role_name, policy_name) log.info('Successfully deleted policy %s for IAM role %s.', policy_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM role %s.', policy_name, role_name) return False def update_assume_role_policy(role_name, policy_document, region=None, key=None, keyid=None, profile=None): ''' Update an assume role policy for a role. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_assume_role_policy myrole '{"Statement":"..."}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(policy_document, six.string_types): policy_document = salt.utils.json.loads(policy_document, object_pairs_hook=odict.OrderedDict) try: _policy_document = salt.utils.json.dumps(policy_document) conn.update_assume_role_policy(role_name, _policy_document) log.info('Successfully updated assume role policy for IAM role %s.', role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to update assume role policy for IAM role %s.', role_name) return False def build_policy(region=None, key=None, keyid=None, profile=None): ''' Build a default assume role policy. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.build_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if hasattr(conn, 'build_policy'): policy = salt.utils.json.loads(conn.build_policy()) elif hasattr(conn, '_build_policy'): policy = salt.utils.json.loads(conn._build_policy()) else: return {} # The format we get from build_policy isn't going to be what we get back # from AWS for the exact same policy. AWS converts single item list values # into strings, so let's do the same here. for key, policy_val in policy.items(): for statement in policy_val: if (isinstance(statement['Action'], list) and len(statement['Action']) == 1): statement['Action'] = statement['Action'][0] if (isinstance(statement['Principal']['Service'], list) and len(statement['Principal']['Service']) == 1): statement['Principal']['Service'] = statement['Principal']['Service'][0] # build_policy doesn't add a version field, which AWS is going to set to a # default value, when we get it back, so let's set it. policy['Version'] = '2008-10-17' return policy def get_account_id(region=None, key=None, keyid=None, profile=None): ''' Get a the AWS account id associated with the used credentials. CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_id ''' cache_key = 'boto_iam.account_id' if cache_key not in __context__: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_user() # The get_user call returns an user ARN: # arn:aws:iam::027050522557:user/salt-test arn = ret['get_user_response']['get_user_result']['user']['arn'] account_id = arn.split(':')[4] except boto.exception.BotoServerError: # If call failed, then let's try to get the ARN from the metadata timeout = boto.config.getfloat( 'Boto', 'metadata_service_timeout', 1.0 ) attempts = boto.config.getint( 'Boto', 'metadata_service_num_attempts', 1 ) identity = boto.utils.get_instance_identity( timeout=timeout, num_retries=attempts ) try: account_id = identity['document']['accountId'] except KeyError: log.error('Failed to get account id from instance_identity in' ' boto_iam.get_account_id.') __context__[cache_key] = account_id return __context__[cache_key] def get_all_roles(path_prefix=None, region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM role details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_roles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _roles = conn.list_roles(path_prefix=path_prefix) roles = _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) while marker: _roles = conn.list_roles(path_prefix=path_prefix, marker=marker) roles = roles + _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) return roles def get_all_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM user details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_users ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _users = conn.get_all_users(path_prefix=path_prefix) users = _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) while marker: _users = conn.get_all_users(path_prefix=path_prefix, marker=marker) users = users + _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) return users def get_all_user_policies(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all user policies. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_user_policies myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_all_user_policies(user_name, marker, max_items) if not info: return False _list = info.list_user_policies_response.list_user_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policies for user %s.', user_name) return False def get_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user_policy myuser mypolicyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user_policy(user_name, policy_name) log.debug('Info for IAM user %s policy %s: %s.', user_name, policy_name, info) if not info: return False info = info.get_user_policy_response.get_user_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policy %s for IAM user %s.', policy_name, user_name) return False def put_user_policy(user_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_user_policy myuser policyname policyrules ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_user_policy(user_name, policy_name, policy_json) if created: log.info('Created policy %s for IAM user %s.', policy_name, user_name) return True log.error('Could not create policy %s for IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy %s for IAM user %s.', policy_name, user_name) return False def upload_server_cert(cert_name, cert_body, private_key, cert_chain=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Upload a certificate to Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.upload_server_cert mycert_name crt priv_key :param cert_name: The name for the server certificate. Do not include the path in this value. :param cert_body: The contents of the public key certificate in PEM-encoded format. :param private_key: The contents of the private key in PEM-encoded format. :param cert_chain: The contents of the certificate chain. This is typically a concatenation of the PEM-encoded public key certificates of the chain. :param path: The path for the server certificate. :param region: The name of the region to connect to. :param key: The key to be used in order to connect :param keyid: The keyid to be used in order to connect :param profile: The profile that contains a dict of region, key, keyid :return: True / False ''' exists = get_server_certificate(cert_name, region, key, keyid, profile) if exists: return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.upload_server_cert(cert_name, cert_body, private_key, cert_chain) log.info('Created certificate %s.', cert_name) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to failed to create certificate %s.', cert_name) return False def list_server_certificates(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Lists the server certificates stored in IAM that have the specified path prefix. .. versionadded:: ??? :param path_prefix: The path prefix for filtering the results. For example: /company/servercerts would get all server certificates for which the path starts with /company/servercerts . This parameter is optional. If it is not included, it defaults to a slash (/), listing all server certificates. This parameter allows (per its regex pattern) a string of characters consisting of either a forward slash (/) by itself or a string that must begin and end with forward slashes. In addition, it can contain any ASCII character from the ! (u0021) through the DEL character (u007F), including most punctuation characters, digits, and upper and lowercased letters. CLI Example: .. code-block:: bash salt myminion boto_iam.list_server_certificates path_prefix=/somepath/ ''' retries = 10 sleep = 6 conn = __utils__['boto3.get_connection']('iam', region=region, key=key, keyid=keyid, profile=profile) Items = [] while retries: try: log.debug('Garnering list of IAM Server Certificates') IsTruncated = True while IsTruncated: kwargs = {'PathPrefix': path_prefix} ret = conn.list_server_certificates(**kwargs) Items += ret.get('ServerCertificateMetadataList', []) IsTruncated = ret.get('IsTruncated') kwargs.update({'Marker': ret.get('Marker')}) return Items except botocore.exceptions.ParamValidationError as err: raise SaltInvocationError(str(err)) except botocore.exceptions.ClientError as err: if retries and jmespath.search('Error.Code', err.response) == 'Throttling': retries -= 1 log.debug('Throttled by AWS API, retrying in %s seconds...', sleep) time.sleep(sleep) continue log.error('Failed to list IAM Server Certificates: %s', err.message) return None def get_server_certificate(cert_name, region=None, key=None, keyid=None, profile=None): ''' Returns certificate information from Amazon .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_server_certificate mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_server_certificate(cert_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get certificate %s information.', cert_name) return False def delete_server_cert(cert_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a certificate from Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_server_cert mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_server_cert(cert_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete certificate %s.', cert_name) return False def export_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM user details. Produces results that can be used to create an sls file. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.export_users --out=txt | sed "s/local: //" > iam_users.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() users = get_all_users(path_prefix, region, key, keyid, profile) for user in users: name = user.user_name _policies = conn.get_all_user_policies(name, max_items=100) _policies = _policies.list_user_policies_response.list_user_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_user_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_user_policy_response.get_user_policy_result.policy_document )) policies[policy_name] = _policy user_sls = [] user_sls.append({"name": name}) user_sls.append({"policies": policies}) user_sls.append({"path": user.path}) results["manage user " + name] = {"boto_iam.user_present": user_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def export_roles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM role details. Produces results that can be used to create an sls file. CLI Example: salt-call boto_iam.export_roles --out=txt | sed "s/local: //" > iam_roles.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() roles = get_all_roles(path_prefix, region, key, keyid, profile) for role in roles: name = role.role_name _policies = conn.list_role_policies(name, max_items=100) _policies = _policies.list_role_policies_response.list_role_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_role_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_role_policy_response.get_role_policy_result.policy_document )) policies[policy_name] = _policy role_sls = [] role_sls.append({"name": name}) role_sls.append({"policies": policies}) role_sls.append({'policy_document': salt.utils.json.loads(_unquote(role.assume_role_policy_document))}) role_sls.append({"path": role.path}) results["manage role " + name] = {"boto_iam_role.present": role_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def _get_policy_arn(name, region=None, key=None, keyid=None, profile=None): if name.startswith('arn:aws:iam:'): return name account_id = get_account_id( region=region, key=key, keyid=keyid, profile=profile ) return 'arn:aws:iam::{0}:policy/{1}'.format(account_id, name) def policy_exists(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return True except boto.exception.BotoServerError: return False def get_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return ret.get('get_policy_response', {}).get('get_policy_result', {}) except boto.exception.BotoServerError: return None def create_policy(policy_name, policy_document, path=None, description=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in 'path', 'description': if locals()[arg] is not None: params[arg] = locals()[arg] if policy_exists(policy_name, region, key, keyid, profile): return True try: conn.create_policy(policy_name, policy_document, **params) log.info('Created IAM policy %s.', policy_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s.', policy_name) return False return True def delete_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_exists(policy_arn, region, key, keyid, profile): return True try: conn.delete_policy(policy_arn) log.info('Deleted %s policy.', policy_name) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete %s policy: %s.', policy_name, aws.get('message')) return False return True def list_policies(region=None, key=None, keyid=None, profile=None): ''' List policies. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policies ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: policies = [] for ret in __utils__['boto.paged_call'](conn.list_policies): policies.append(ret.get('list_policies_response', {}).get('list_policies_result', {}).get('policies')) return policies except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to list policy versions.' log.error(msg) return [] def policy_version_exists(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.get_policy_version(policy_arn, version_id) return True except boto.exception.BotoServerError: return False def get_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy_version(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile), version_id) retval = ret.get('get_policy_version_response', {}).get('get_policy_version_result', {}).get('policy_version', {}) retval['document'] = _unquote(retval.get('document')) return {'policy_version': retval} except boto.exception.BotoServerError: return None def create_policy_version(policy_name, policy_document, set_as_default=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy version. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy_version mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in ('set_as_default',): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.create_policy_version(policy_arn, policy_document, **params) vid = ret.get('create_policy_version_response', {}).get('create_policy_version_result', {}).get('policy_version', {}).get('version_id') log.info('Created IAM policy %s version %s.', policy_name, vid) return {'created': True, 'version_id': vid} except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s version %s.', policy_name, vid) return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Delete a policy version. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_version_exists(policy_arn, version_id, region, key, keyid, profile): return True try: conn.delete_policy_version(policy_arn, version_id) log.info('Deleted IAM policy %s version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete IAM policy %s version %s: %s', policy_name, version_id, aws.get('message')) return False return True def list_policy_versions(policy_name, region=None, key=None, keyid=None, profile=None): ''' List versions of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policy_versions mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.list_policy_versions(policy_arn) return ret.get('list_policy_versions_response', {}).get('list_policy_versions_result', {}).get('versions') except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list versions for IAM policy %s.', policy_name) return [] def set_default_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Set the default version of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.set_default_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.set_default_policy_version(policy_arn, version_id) log.info('Set %s policy to version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to set %s policy to version %s: %s', policy_name, version_id, aws.get('message')) return False return True def attach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_user_policy(policy_arn, user_name) log.info('Attached policy %s to IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach %s policy to IAM user %s.', policy_name, user_name) return False return True def detach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_user_policy(policy_arn, user_name) log.info('Detached %s policy from IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach %s policy from IAM user %s.', policy_name, user_name) return False return True def attach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_group_policy(policy_arn, group_name) log.info('Attached policy %s to IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM group %s.', policy_name, group_name) return False return True def detach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_group_policy(policy_arn, group_name) log.info('Detached policy %s from IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM group %s.', policy_name, group_name) return False return True def attach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_role_policy(policy_arn, role_name) log.info('Attached policy %s to IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM role %s.', policy_name, role_name) return False return True def detach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_role_policy(policy_arn, role_name) log.info('Detached policy %s from IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM role %s.', policy_name, role_name) return False return True def list_entities_for_policy(policy_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities that a policy is attached to. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 params = {} for arg in ('path_prefix', 'entity_filter'): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) while retries: try: allret = { 'policy_groups': [], 'policy_users': [], 'policy_roles': [], } for ret in __utils__['boto.paged_call'](conn.list_entities_for_policy, policy_arn=policy_arn, **params): for k, v in six.iteritems(allret): v.extend(ret.get('list_entities_for_policy_response', {}).get('list_entities_for_policy_result', {}).get(k)) return allret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('Failed to list entities for IAM policy %s: %s', policy_name, e.message) return {} return {} def list_attached_user_policies(user_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given user. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'UserName': user_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedUserPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_user_policies_response', {}).get('list_attached_user_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM user %s.', user_name) return [] def list_attached_group_policies(group_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given group. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'GroupName': group_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedGroupPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_group_policies_response', {}).get('list_attached_group_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM group %s.', group_name) return [] def list_attached_role_policies(role_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'RoleName': role_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedRolePolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_role_policies_response', {}).get('list_attached_role_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM role %s.', role_name) return [] def create_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Create SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.create_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_saml_provider(saml_metadata_document, name) log.info('Successfully created %s SAML provider.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to create SAML provider %s.', name) return False def get_saml_provider_arn(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider_arn my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_saml_providers() for saml_provider in response.list_saml_providers_response.list_saml_providers_result.saml_provider_list: if saml_provider['arn'].endswith(':saml-provider/' + name): return saml_provider['arn'] return False except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to get ARN of SAML provider %s.', name) return False def delete_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Delete SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.delete_saml_provider my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return True conn.delete_saml_provider(saml_provider_arn) log.info('Successfully deleted SAML provider %s.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete SAML provider %s.', name) return False def list_saml_providers(region=None, key=None, keyid=None, profile=None): ''' List SAML providers. CLI Example: .. code-block:: bash salt myminion boto_iam.list_saml_providers ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: providers = [] info = conn.list_saml_providers() for arn in info['list_saml_providers_response']['list_saml_providers_result']['saml_provider_list']: providers.append(arn['arn'].rsplit('/', 1)[1]) return providers except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get list of SAML providers.') return False def get_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider document. CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider arn ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: provider = conn.get_saml_provider(name) return provider['get_saml_provider_response']['get_saml_provider_result']['saml_metadata_document'] except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get SAML provider document %s.', name) return False def update_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Update SAML provider. CLI Example: .. code-block:: bash salt myminion boto_iam.update_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return False if conn.update_saml_provider(name, saml_metadata_document): return True return False except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to update SAML provider %s.', name) return False
saltstack/salt
salt/modules/boto_iam.py
upload_server_cert
python
def upload_server_cert(cert_name, cert_body, private_key, cert_chain=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Upload a certificate to Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.upload_server_cert mycert_name crt priv_key :param cert_name: The name for the server certificate. Do not include the path in this value. :param cert_body: The contents of the public key certificate in PEM-encoded format. :param private_key: The contents of the private key in PEM-encoded format. :param cert_chain: The contents of the certificate chain. This is typically a concatenation of the PEM-encoded public key certificates of the chain. :param path: The path for the server certificate. :param region: The name of the region to connect to. :param key: The key to be used in order to connect :param keyid: The keyid to be used in order to connect :param profile: The profile that contains a dict of region, key, keyid :return: True / False ''' exists = get_server_certificate(cert_name, region, key, keyid, profile) if exists: return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.upload_server_cert(cert_name, cert_body, private_key, cert_chain) log.info('Created certificate %s.', cert_name) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to failed to create certificate %s.', cert_name) return False
Upload a certificate to Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.upload_server_cert mycert_name crt priv_key :param cert_name: The name for the server certificate. Do not include the path in this value. :param cert_body: The contents of the public key certificate in PEM-encoded format. :param private_key: The contents of the private key in PEM-encoded format. :param cert_chain: The contents of the certificate chain. This is typically a concatenation of the PEM-encoded public key certificates of the chain. :param path: The path for the server certificate. :param region: The name of the region to connect to. :param key: The key to be used in order to connect :param keyid: The keyid to be used in order to connect :param profile: The profile that contains a dict of region, key, keyid :return: True / False
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iam.py#L1486-L1522
[ "def get_server_certificate(cert_name, region=None, key=None, keyid=None, profile=None):\n '''\n Returns certificate information from Amazon\n\n .. versionadded:: 2015.8.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_iam.get_server_certificate mycert_name\n '''\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n try:\n info = conn.get_server_certificate(cert_name)\n if not info:\n return False\n return info\n except boto.exception.BotoServerError as e:\n log.debug(e)\n log.error('Failed to get certificate %s information.', cert_name)\n return False\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon IAM .. versionadded:: 2014.7.0 :configuration: This module accepts explicit iam 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 iam.keyid: GKTADJGHEIQSXMKKRBJ08H iam.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs iam.region: 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: boto ''' # keep lint from choking on _get_conn and _cache_id #pylint: disable=E0602 # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import salt libs from salt.ext import six import salt.utils.compat import salt.utils.json import salt.utils.odict as odict import salt.utils.versions from salt.exceptions import SaltInvocationError # Import third party libs # pylint: disable=unused-import from salt.ext.six.moves.urllib.parse import unquote as _unquote # pylint: disable=no-name-in-module try: import boto import boto.iam import boto3 import botocore logging.getLogger('boto').setLevel(logging.CRITICAL) logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=unused-import log = logging.getLogger(__name__) def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'iam', pack=__salt__) def instance_profile_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an instance profile exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: # Boto weirdly returns an exception here if an instance profile doesn't # exist. conn.get_instance_profile(name) return True except boto.exception.BotoServerError: return False def create_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Create an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.create_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if instance_profile_exists(name, region, key, keyid, profile): return True try: # This call returns an instance profile if successful and an exception # if not. It's annoying. conn.create_instance_profile(name) log.info('Created %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create %s instance profile.', name) return False return True def delete_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Delete an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not instance_profile_exists(name, region, key, keyid, profile): return True try: conn.delete_instance_profile(name) log.info('Deleted %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s instance profile.', name) return False return True def role_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an IAM role exists. CLI Example: .. code-block:: bash salt myminion boto_iam.role_exists myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_role(name) return True except boto.exception.BotoServerError: return False def describe_role(name, region=None, key=None, keyid=None, profile=None): ''' Get information for a role. CLI Example: .. code-block:: bash salt myminion boto_iam.describe_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_role(name) if not info: return False role = info.get_role_response.get_role_result.role role['assume_role_policy_document'] = salt.utils.json.loads(_unquote( role.assume_role_policy_document )) # If Sid wasn't defined by the user, boto will still return a Sid in # each policy. To properly check idempotently, let's remove the Sid # from the return if it's not actually set. for policy_key, policy in role['assume_role_policy_document'].items(): if policy_key == 'Statement': for val in policy: if 'Sid' in val and not val['Sid']: del val['Sid'] return role except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get %s information.', name) return False def create_user(user_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_user myuser ''' if not path: path = '/' if get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_user(user_name, path) log.info('Created IAM user : %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM user %s.', user_name) return False def get_all_access_keys(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all access keys from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_access_keys myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.get_all_access_keys(user_name, marker, max_items) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get access keys for IAM user %s.', user_name) return six.text_type(e) def create_access_key(user_name, region=None, key=None, keyid=None, profile=None): ''' Create access key id for a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.create_access_key(user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create access key.') return six.text_type(e) def delete_access_key(access_key_id, user_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete access key id from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_access_key(access_key_id, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete access key id %s.', access_key_id) return six.text_type(e) def delete_user(user_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user myuser ''' if not get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.delete_user(user_name) log.info('Deleted IAM user : %s .', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM user %s', user_name) return six.text_type(e) def get_user(user_name=None, region=None, key=None, keyid=None, profile=None): ''' Get user information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user(user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM user %s info.', user_name) return False def create_group(group_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_group group ''' if not path: path = '/' if get_group(group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_group(group_name, path) log.info('Created IAM group : %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM group %s.', group_name) return False def get_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group(group_name, max_items=1) if not info: return False return info['get_group_response']['get_group_result']['group'] except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_group_members(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: marker = None truncated = True users = [] while truncated: info = conn.get_group(group_name, marker=marker, max_items=1000) if not info: return False truncated = bool(info['get_group_response']['get_group_result']['is_truncated']) if truncated and 'marker' in info['get_group_response']['get_group_result']: marker = info['get_group_response']['get_group_result']['marker'] else: marker = None truncated = False users += info['get_group_response']['get_group_result']['users'] return users except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get members for IAM group %s.', group_name) return False def add_user_to_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Add user to group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.add_user_to_group myuser mygroup ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('Username : %s does not exist.', user_name) return False if user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.add_user_to_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add IAM user %s to group %s.', user_name, group_name) return False def user_exists_in_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Check if user exists in group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.user_exists_in_group myuser mygroup ''' # TODO this should probably use boto.iam.get_groups_for_user users = get_group_members( group_name=group_name, region=region, key=key, keyid=keyid, profile=profile ) if users: for _user in users: if user_name == _user['user_name']: log.debug('IAM user %s is already in IAM group %s.', user_name, group_name) return True return False def remove_user_from_group(group_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Remove user from group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.remove_user_from_group mygroup myuser ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist.', user_name) return False if not user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.remove_user_from_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove IAM user %s from group %s', user_name, group_name) return False def put_group_policy(group_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_group_policy mygroup policyname policyrules ''' group = get_group(group_name, region=region, key=key, keyid=keyid, profile=profile) if not group: log.error('Group %s does not exist', group_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_group_policy(group_name, policy_name, policy_json) if created: log.info('Created policy for IAM group %s.', group_name) return True log.error('Could not create policy for IAM group %s', group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy for IAM group %s', group_name) return False def delete_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group_policy mygroup mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_group_policy( group_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_group_policy(group_name, policy_name) log.info('Successfully deleted policy %s for IAM group %s.', policy_name, group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM group %s.', policy_name, group_name) return False def get_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group_policy mygroup policyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group_policy(group_name, policy_name) log.debug('info for group policy is : %s', info) if not info: return False info = info.get_group_policy_response.get_group_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_all_groups(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM group details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_groups ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _groups = conn.get_all_groups(path_prefix=path_prefix) groups = _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) while marker: _groups = conn.get_all_groups(path_prefix=path_prefix, marker=marker) groups = groups + _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) return groups def get_all_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.get_all_instance_profiles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) marker = False profiles = [] while marker is not None: marker = marker if marker else None p = conn.list_instance_profiles(path_prefix=path_prefix, marker=marker) res = p.list_instance_profiles_response.list_instance_profiles_result profiles += res.instance_profiles marker = getattr(res, 'marker', None) return profiles def list_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' List all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.list_instance_profiles ''' p = get_all_instance_profiles(path_prefix, region, key, keyid, profile) return [i['instance_profile_name'] for i in p] def get_all_group_policies(group_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a group. CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_group_policies mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False try: response = conn.get_all_group_policies(group_name) _list = response.list_group_policies_response.list_group_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def delete_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _group = get_group( group_name, region, key, keyid, profile ) if not _group: return True try: conn.delete_group(group_name) log.info('Successfully deleted IAM group %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM group %s.', group_name) return False def create_login_profile(user_name, password, region=None, key=None, keyid=None, profile=None): ''' Creates a login profile for the specified user, give the user the ability to access AWS services and the AWS Management Console. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_login_profile user_name password ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.create_login_profile(user_name, password) log.info('Created profile for IAM user %s.', user_name) return info except boto.exception.BotoServerError as e: log.debug(e) if 'Conflict' in e: log.info('Profile already exists for IAM user %s.', user_name) return 'Conflict' log.error('Failed to update profile for IAM user %s.', user_name) return False def delete_login_profile(user_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a login profile for the specified user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_login_profile user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.delete_login_profile(user_name) log.info('Deleted login profile for IAM user %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Login profile already deleted for IAM user %s.', user_name) return True log.error('Failed to delete login profile for IAM user %s.', user_name) return False def get_all_mfa_devices(user_name, region=None, key=None, keyid=None, profile=None): ''' Get all MFA devices associated with an IAM user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_mfa_devices user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: result = conn.get_all_mfa_devices(user_name) devices = result['list_mfa_devices_response']['list_mfa_devices_result']['mfa_devices'] return devices except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Could not find IAM user %s.', user_name) return [] log.error('Failed to get all MFA devices for IAM user %s.', user_name) return False def deactivate_mfa_device(user_name, serial, region=None, key=None, keyid=None, profile=None): ''' Deactivates the specified MFA device and removes it from association with the user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.deactivate_mfa_device user_name serial_num ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.deactivate_mfa_device(user_name, serial) log.info('Deactivated MFA device %s for IAM user %s.', serial, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('MFA device %s not associated with IAM user %s.', serial, user_name) return True log.error('Failed to deactivate MFA device %s for IAM user %s.', serial, user_name) return False def delete_virtual_mfa_device(serial, region=None, key=None, keyid=None, profile=None): ''' Deletes the specified virtual MFA device. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_virtual_mfa_device serial_num ''' conn = __utils__['boto3.get_connection_func']('iam')() try: conn.delete_virtual_mfa_device(SerialNumber=serial) log.info('Deleted virtual MFA device %s.', serial) return True except botocore.exceptions.ClientError as e: log.debug(e) if 'NoSuchEntity' in six.text_type(e): log.info('Virtual MFA device %s not found.', serial) return True log.error('Failed to delete virtual MFA device %s.', serial) return False def update_account_password_policy(allow_users_to_change_password=None, hard_expiry=None, max_password_age=None, minimum_password_length=None, password_reuse_prevention=None, require_lowercase_characters=None, require_numbers=None, require_symbols=None, require_uppercase_characters=None, region=None, key=None, keyid=None, profile=None): ''' Update the password policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_account_password_policy True ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.update_account_password_policy(allow_users_to_change_password, hard_expiry, max_password_age, minimum_password_length, password_reuse_prevention, require_lowercase_characters, require_numbers, require_symbols, require_uppercase_characters) log.info('The password policy has been updated.') return True except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy' log.error(msg) return False def get_account_policy(region=None, key=None, keyid=None, profile=None): ''' Get account policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_account_password_policy() return info.get_account_password_policy_response.get_account_password_policy_result.password_policy except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy.' log.error(msg) return False def create_role(name, policy_document=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Create an instance role. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if role_exists(name, region, key, keyid, profile): return True if not policy_document: policy_document = None try: conn.create_role(name, assume_role_policy_document=policy_document, path=path) log.info('Created IAM role %s.', name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to create IAM role %s.', name) return False def delete_role(name, region=None, key=None, keyid=None, profile=None): ''' Delete an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(name, region, key, keyid, profile): return True try: conn.delete_role(name) log.info('Deleted %s IAM role.', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s IAM role.', name) return False def profile_associated(role_name, profile_name, region, key, keyid, profile): ''' Check to see if an instance profile is associated with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.profile_associated myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # The IAM module of boto doesn't return objects. Instead you need to grab # values through its properties. Sigh. try: profiles = conn.list_instance_profiles_for_role(role_name) except boto.exception.BotoServerError as e: log.debug(e) return False profiles = profiles.list_instance_profiles_for_role_response profiles = profiles.list_instance_profiles_for_role_result profiles = profiles.instance_profiles for profile in profiles: if profile.instance_profile_name == profile_name: return True return False def associate_profile_to_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Associate an instance profile with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.associate_profile_to_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if associated: return True else: try: conn.add_role_to_instance_profile(profile_name, role_name) log.info('Added %s instance profile to IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add %s instance profile to IAM role %s', profile_name, role_name) return False def disassociate_profile_from_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Disassociate an instance profile from an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.disassociate_profile_from_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if not associated: return True else: try: conn.remove_role_from_instance_profile(profile_name, role_name) log.info('Removed %s instance profile from IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove %s instance profile from IAM role %s.', profile_name, role_name) return False def list_role_policies(role_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_role_policies myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_role_policies(role_name) _list = response.list_role_policies_response.list_role_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def get_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.get_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: _policy = conn.get_role_policy(role_name, policy_name) # I _hate_ you for not giving me an object boto. _policy = _policy.get_role_policy_response.policy_document # Policy is url encoded _policy = _unquote(_policy) _policy = salt.utils.json.loads(_policy, object_pairs_hook=odict.OrderedDict) return _policy except boto.exception.BotoServerError: return {} def create_role_policy(role_name, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Create or modify a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role_policy myirole mypolicy '{"MyPolicy": "Statement": [{"Action": ["sqs:*"], "Effect": "Allow", "Resource": ["arn:aws:sqs:*:*:*"], "Sid": "MyPolicySqs1"}]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) mode = 'create' if _policy: if _policy == policy: return True mode = 'modify' if isinstance(policy, six.string_types): policy = salt.utils.json.loads(policy, object_pairs_hook=odict.OrderedDict) try: _policy = salt.utils.json.dumps(policy) conn.put_role_policy(role_name, policy_name, _policy) if mode == 'create': msg = 'Successfully added policy %s to IAM role %s.' else: msg = 'Successfully modified policy %s for IAM role %s.' log.info(msg, policy_name, role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to %s policy %s for IAM role %s.', mode, policy_name, role_name) return False def delete_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) if not _policy: return True try: conn.delete_role_policy(role_name, policy_name) log.info('Successfully deleted policy %s for IAM role %s.', policy_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM role %s.', policy_name, role_name) return False def update_assume_role_policy(role_name, policy_document, region=None, key=None, keyid=None, profile=None): ''' Update an assume role policy for a role. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_assume_role_policy myrole '{"Statement":"..."}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(policy_document, six.string_types): policy_document = salt.utils.json.loads(policy_document, object_pairs_hook=odict.OrderedDict) try: _policy_document = salt.utils.json.dumps(policy_document) conn.update_assume_role_policy(role_name, _policy_document) log.info('Successfully updated assume role policy for IAM role %s.', role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to update assume role policy for IAM role %s.', role_name) return False def build_policy(region=None, key=None, keyid=None, profile=None): ''' Build a default assume role policy. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.build_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if hasattr(conn, 'build_policy'): policy = salt.utils.json.loads(conn.build_policy()) elif hasattr(conn, '_build_policy'): policy = salt.utils.json.loads(conn._build_policy()) else: return {} # The format we get from build_policy isn't going to be what we get back # from AWS for the exact same policy. AWS converts single item list values # into strings, so let's do the same here. for key, policy_val in policy.items(): for statement in policy_val: if (isinstance(statement['Action'], list) and len(statement['Action']) == 1): statement['Action'] = statement['Action'][0] if (isinstance(statement['Principal']['Service'], list) and len(statement['Principal']['Service']) == 1): statement['Principal']['Service'] = statement['Principal']['Service'][0] # build_policy doesn't add a version field, which AWS is going to set to a # default value, when we get it back, so let's set it. policy['Version'] = '2008-10-17' return policy def get_account_id(region=None, key=None, keyid=None, profile=None): ''' Get a the AWS account id associated with the used credentials. CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_id ''' cache_key = 'boto_iam.account_id' if cache_key not in __context__: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_user() # The get_user call returns an user ARN: # arn:aws:iam::027050522557:user/salt-test arn = ret['get_user_response']['get_user_result']['user']['arn'] account_id = arn.split(':')[4] except boto.exception.BotoServerError: # If call failed, then let's try to get the ARN from the metadata timeout = boto.config.getfloat( 'Boto', 'metadata_service_timeout', 1.0 ) attempts = boto.config.getint( 'Boto', 'metadata_service_num_attempts', 1 ) identity = boto.utils.get_instance_identity( timeout=timeout, num_retries=attempts ) try: account_id = identity['document']['accountId'] except KeyError: log.error('Failed to get account id from instance_identity in' ' boto_iam.get_account_id.') __context__[cache_key] = account_id return __context__[cache_key] def get_all_roles(path_prefix=None, region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM role details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_roles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _roles = conn.list_roles(path_prefix=path_prefix) roles = _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) while marker: _roles = conn.list_roles(path_prefix=path_prefix, marker=marker) roles = roles + _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) return roles def get_all_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM user details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_users ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _users = conn.get_all_users(path_prefix=path_prefix) users = _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) while marker: _users = conn.get_all_users(path_prefix=path_prefix, marker=marker) users = users + _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) return users def get_all_user_policies(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all user policies. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_user_policies myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_all_user_policies(user_name, marker, max_items) if not info: return False _list = info.list_user_policies_response.list_user_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policies for user %s.', user_name) return False def get_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user_policy myuser mypolicyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user_policy(user_name, policy_name) log.debug('Info for IAM user %s policy %s: %s.', user_name, policy_name, info) if not info: return False info = info.get_user_policy_response.get_user_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policy %s for IAM user %s.', policy_name, user_name) return False def put_user_policy(user_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_user_policy myuser policyname policyrules ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_user_policy(user_name, policy_name, policy_json) if created: log.info('Created policy %s for IAM user %s.', policy_name, user_name) return True log.error('Could not create policy %s for IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy %s for IAM user %s.', policy_name, user_name) return False def delete_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user_policy myuser mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_user_policy( user_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_user_policy(user_name, policy_name) log.info('Successfully deleted policy %s for IAM user %s.', policy_name, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM user %s.', policy_name, user_name) return False def list_server_certificates(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Lists the server certificates stored in IAM that have the specified path prefix. .. versionadded:: ??? :param path_prefix: The path prefix for filtering the results. For example: /company/servercerts would get all server certificates for which the path starts with /company/servercerts . This parameter is optional. If it is not included, it defaults to a slash (/), listing all server certificates. This parameter allows (per its regex pattern) a string of characters consisting of either a forward slash (/) by itself or a string that must begin and end with forward slashes. In addition, it can contain any ASCII character from the ! (u0021) through the DEL character (u007F), including most punctuation characters, digits, and upper and lowercased letters. CLI Example: .. code-block:: bash salt myminion boto_iam.list_server_certificates path_prefix=/somepath/ ''' retries = 10 sleep = 6 conn = __utils__['boto3.get_connection']('iam', region=region, key=key, keyid=keyid, profile=profile) Items = [] while retries: try: log.debug('Garnering list of IAM Server Certificates') IsTruncated = True while IsTruncated: kwargs = {'PathPrefix': path_prefix} ret = conn.list_server_certificates(**kwargs) Items += ret.get('ServerCertificateMetadataList', []) IsTruncated = ret.get('IsTruncated') kwargs.update({'Marker': ret.get('Marker')}) return Items except botocore.exceptions.ParamValidationError as err: raise SaltInvocationError(str(err)) except botocore.exceptions.ClientError as err: if retries and jmespath.search('Error.Code', err.response) == 'Throttling': retries -= 1 log.debug('Throttled by AWS API, retrying in %s seconds...', sleep) time.sleep(sleep) continue log.error('Failed to list IAM Server Certificates: %s', err.message) return None def get_server_certificate(cert_name, region=None, key=None, keyid=None, profile=None): ''' Returns certificate information from Amazon .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_server_certificate mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_server_certificate(cert_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get certificate %s information.', cert_name) return False def delete_server_cert(cert_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a certificate from Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_server_cert mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_server_cert(cert_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete certificate %s.', cert_name) return False def export_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM user details. Produces results that can be used to create an sls file. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.export_users --out=txt | sed "s/local: //" > iam_users.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() users = get_all_users(path_prefix, region, key, keyid, profile) for user in users: name = user.user_name _policies = conn.get_all_user_policies(name, max_items=100) _policies = _policies.list_user_policies_response.list_user_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_user_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_user_policy_response.get_user_policy_result.policy_document )) policies[policy_name] = _policy user_sls = [] user_sls.append({"name": name}) user_sls.append({"policies": policies}) user_sls.append({"path": user.path}) results["manage user " + name] = {"boto_iam.user_present": user_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def export_roles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM role details. Produces results that can be used to create an sls file. CLI Example: salt-call boto_iam.export_roles --out=txt | sed "s/local: //" > iam_roles.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() roles = get_all_roles(path_prefix, region, key, keyid, profile) for role in roles: name = role.role_name _policies = conn.list_role_policies(name, max_items=100) _policies = _policies.list_role_policies_response.list_role_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_role_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_role_policy_response.get_role_policy_result.policy_document )) policies[policy_name] = _policy role_sls = [] role_sls.append({"name": name}) role_sls.append({"policies": policies}) role_sls.append({'policy_document': salt.utils.json.loads(_unquote(role.assume_role_policy_document))}) role_sls.append({"path": role.path}) results["manage role " + name] = {"boto_iam_role.present": role_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def _get_policy_arn(name, region=None, key=None, keyid=None, profile=None): if name.startswith('arn:aws:iam:'): return name account_id = get_account_id( region=region, key=key, keyid=keyid, profile=profile ) return 'arn:aws:iam::{0}:policy/{1}'.format(account_id, name) def policy_exists(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return True except boto.exception.BotoServerError: return False def get_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return ret.get('get_policy_response', {}).get('get_policy_result', {}) except boto.exception.BotoServerError: return None def create_policy(policy_name, policy_document, path=None, description=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in 'path', 'description': if locals()[arg] is not None: params[arg] = locals()[arg] if policy_exists(policy_name, region, key, keyid, profile): return True try: conn.create_policy(policy_name, policy_document, **params) log.info('Created IAM policy %s.', policy_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s.', policy_name) return False return True def delete_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_exists(policy_arn, region, key, keyid, profile): return True try: conn.delete_policy(policy_arn) log.info('Deleted %s policy.', policy_name) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete %s policy: %s.', policy_name, aws.get('message')) return False return True def list_policies(region=None, key=None, keyid=None, profile=None): ''' List policies. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policies ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: policies = [] for ret in __utils__['boto.paged_call'](conn.list_policies): policies.append(ret.get('list_policies_response', {}).get('list_policies_result', {}).get('policies')) return policies except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to list policy versions.' log.error(msg) return [] def policy_version_exists(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.get_policy_version(policy_arn, version_id) return True except boto.exception.BotoServerError: return False def get_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy_version(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile), version_id) retval = ret.get('get_policy_version_response', {}).get('get_policy_version_result', {}).get('policy_version', {}) retval['document'] = _unquote(retval.get('document')) return {'policy_version': retval} except boto.exception.BotoServerError: return None def create_policy_version(policy_name, policy_document, set_as_default=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy version. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy_version mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in ('set_as_default',): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.create_policy_version(policy_arn, policy_document, **params) vid = ret.get('create_policy_version_response', {}).get('create_policy_version_result', {}).get('policy_version', {}).get('version_id') log.info('Created IAM policy %s version %s.', policy_name, vid) return {'created': True, 'version_id': vid} except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s version %s.', policy_name, vid) return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Delete a policy version. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_version_exists(policy_arn, version_id, region, key, keyid, profile): return True try: conn.delete_policy_version(policy_arn, version_id) log.info('Deleted IAM policy %s version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete IAM policy %s version %s: %s', policy_name, version_id, aws.get('message')) return False return True def list_policy_versions(policy_name, region=None, key=None, keyid=None, profile=None): ''' List versions of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policy_versions mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.list_policy_versions(policy_arn) return ret.get('list_policy_versions_response', {}).get('list_policy_versions_result', {}).get('versions') except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list versions for IAM policy %s.', policy_name) return [] def set_default_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Set the default version of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.set_default_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.set_default_policy_version(policy_arn, version_id) log.info('Set %s policy to version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to set %s policy to version %s: %s', policy_name, version_id, aws.get('message')) return False return True def attach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_user_policy(policy_arn, user_name) log.info('Attached policy %s to IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach %s policy to IAM user %s.', policy_name, user_name) return False return True def detach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_user_policy(policy_arn, user_name) log.info('Detached %s policy from IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach %s policy from IAM user %s.', policy_name, user_name) return False return True def attach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_group_policy(policy_arn, group_name) log.info('Attached policy %s to IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM group %s.', policy_name, group_name) return False return True def detach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_group_policy(policy_arn, group_name) log.info('Detached policy %s from IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM group %s.', policy_name, group_name) return False return True def attach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_role_policy(policy_arn, role_name) log.info('Attached policy %s to IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM role %s.', policy_name, role_name) return False return True def detach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_role_policy(policy_arn, role_name) log.info('Detached policy %s from IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM role %s.', policy_name, role_name) return False return True def list_entities_for_policy(policy_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities that a policy is attached to. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 params = {} for arg in ('path_prefix', 'entity_filter'): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) while retries: try: allret = { 'policy_groups': [], 'policy_users': [], 'policy_roles': [], } for ret in __utils__['boto.paged_call'](conn.list_entities_for_policy, policy_arn=policy_arn, **params): for k, v in six.iteritems(allret): v.extend(ret.get('list_entities_for_policy_response', {}).get('list_entities_for_policy_result', {}).get(k)) return allret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('Failed to list entities for IAM policy %s: %s', policy_name, e.message) return {} return {} def list_attached_user_policies(user_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given user. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'UserName': user_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedUserPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_user_policies_response', {}).get('list_attached_user_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM user %s.', user_name) return [] def list_attached_group_policies(group_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given group. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'GroupName': group_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedGroupPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_group_policies_response', {}).get('list_attached_group_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM group %s.', group_name) return [] def list_attached_role_policies(role_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'RoleName': role_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedRolePolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_role_policies_response', {}).get('list_attached_role_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM role %s.', role_name) return [] def create_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Create SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.create_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_saml_provider(saml_metadata_document, name) log.info('Successfully created %s SAML provider.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to create SAML provider %s.', name) return False def get_saml_provider_arn(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider_arn my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_saml_providers() for saml_provider in response.list_saml_providers_response.list_saml_providers_result.saml_provider_list: if saml_provider['arn'].endswith(':saml-provider/' + name): return saml_provider['arn'] return False except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to get ARN of SAML provider %s.', name) return False def delete_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Delete SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.delete_saml_provider my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return True conn.delete_saml_provider(saml_provider_arn) log.info('Successfully deleted SAML provider %s.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete SAML provider %s.', name) return False def list_saml_providers(region=None, key=None, keyid=None, profile=None): ''' List SAML providers. CLI Example: .. code-block:: bash salt myminion boto_iam.list_saml_providers ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: providers = [] info = conn.list_saml_providers() for arn in info['list_saml_providers_response']['list_saml_providers_result']['saml_provider_list']: providers.append(arn['arn'].rsplit('/', 1)[1]) return providers except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get list of SAML providers.') return False def get_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider document. CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider arn ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: provider = conn.get_saml_provider(name) return provider['get_saml_provider_response']['get_saml_provider_result']['saml_metadata_document'] except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get SAML provider document %s.', name) return False def update_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Update SAML provider. CLI Example: .. code-block:: bash salt myminion boto_iam.update_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return False if conn.update_saml_provider(name, saml_metadata_document): return True return False except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to update SAML provider %s.', name) return False
saltstack/salt
salt/modules/boto_iam.py
list_server_certificates
python
def list_server_certificates(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Lists the server certificates stored in IAM that have the specified path prefix. .. versionadded:: ??? :param path_prefix: The path prefix for filtering the results. For example: /company/servercerts would get all server certificates for which the path starts with /company/servercerts . This parameter is optional. If it is not included, it defaults to a slash (/), listing all server certificates. This parameter allows (per its regex pattern) a string of characters consisting of either a forward slash (/) by itself or a string that must begin and end with forward slashes. In addition, it can contain any ASCII character from the ! (u0021) through the DEL character (u007F), including most punctuation characters, digits, and upper and lowercased letters. CLI Example: .. code-block:: bash salt myminion boto_iam.list_server_certificates path_prefix=/somepath/ ''' retries = 10 sleep = 6 conn = __utils__['boto3.get_connection']('iam', region=region, key=key, keyid=keyid, profile=profile) Items = [] while retries: try: log.debug('Garnering list of IAM Server Certificates') IsTruncated = True while IsTruncated: kwargs = {'PathPrefix': path_prefix} ret = conn.list_server_certificates(**kwargs) Items += ret.get('ServerCertificateMetadataList', []) IsTruncated = ret.get('IsTruncated') kwargs.update({'Marker': ret.get('Marker')}) return Items except botocore.exceptions.ParamValidationError as err: raise SaltInvocationError(str(err)) except botocore.exceptions.ClientError as err: if retries and jmespath.search('Error.Code', err.response) == 'Throttling': retries -= 1 log.debug('Throttled by AWS API, retrying in %s seconds...', sleep) time.sleep(sleep) continue log.error('Failed to list IAM Server Certificates: %s', err.message) return None
Lists the server certificates stored in IAM that have the specified path prefix. .. versionadded:: ??? :param path_prefix: The path prefix for filtering the results. For example: /company/servercerts would get all server certificates for which the path starts with /company/servercerts . This parameter is optional. If it is not included, it defaults to a slash (/), listing all server certificates. This parameter allows (per its regex pattern) a string of characters consisting of either a forward slash (/) by itself or a string that must begin and end with forward slashes. In addition, it can contain any ASCII character from the ! (u0021) through the DEL character (u007F), including most punctuation characters, digits, and upper and lowercased letters. CLI Example: .. code-block:: bash salt myminion boto_iam.list_server_certificates path_prefix=/somepath/
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iam.py#L1525-L1572
null
# -*- coding: utf-8 -*- ''' Connection module for Amazon IAM .. versionadded:: 2014.7.0 :configuration: This module accepts explicit iam 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 iam.keyid: GKTADJGHEIQSXMKKRBJ08H iam.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs iam.region: 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: boto ''' # keep lint from choking on _get_conn and _cache_id #pylint: disable=E0602 # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import salt libs from salt.ext import six import salt.utils.compat import salt.utils.json import salt.utils.odict as odict import salt.utils.versions from salt.exceptions import SaltInvocationError # Import third party libs # pylint: disable=unused-import from salt.ext.six.moves.urllib.parse import unquote as _unquote # pylint: disable=no-name-in-module try: import boto import boto.iam import boto3 import botocore logging.getLogger('boto').setLevel(logging.CRITICAL) logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=unused-import log = logging.getLogger(__name__) def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'iam', pack=__salt__) def instance_profile_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an instance profile exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: # Boto weirdly returns an exception here if an instance profile doesn't # exist. conn.get_instance_profile(name) return True except boto.exception.BotoServerError: return False def create_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Create an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.create_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if instance_profile_exists(name, region, key, keyid, profile): return True try: # This call returns an instance profile if successful and an exception # if not. It's annoying. conn.create_instance_profile(name) log.info('Created %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create %s instance profile.', name) return False return True def delete_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Delete an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not instance_profile_exists(name, region, key, keyid, profile): return True try: conn.delete_instance_profile(name) log.info('Deleted %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s instance profile.', name) return False return True def role_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an IAM role exists. CLI Example: .. code-block:: bash salt myminion boto_iam.role_exists myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_role(name) return True except boto.exception.BotoServerError: return False def describe_role(name, region=None, key=None, keyid=None, profile=None): ''' Get information for a role. CLI Example: .. code-block:: bash salt myminion boto_iam.describe_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_role(name) if not info: return False role = info.get_role_response.get_role_result.role role['assume_role_policy_document'] = salt.utils.json.loads(_unquote( role.assume_role_policy_document )) # If Sid wasn't defined by the user, boto will still return a Sid in # each policy. To properly check idempotently, let's remove the Sid # from the return if it's not actually set. for policy_key, policy in role['assume_role_policy_document'].items(): if policy_key == 'Statement': for val in policy: if 'Sid' in val and not val['Sid']: del val['Sid'] return role except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get %s information.', name) return False def create_user(user_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_user myuser ''' if not path: path = '/' if get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_user(user_name, path) log.info('Created IAM user : %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM user %s.', user_name) return False def get_all_access_keys(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all access keys from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_access_keys myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.get_all_access_keys(user_name, marker, max_items) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get access keys for IAM user %s.', user_name) return six.text_type(e) def create_access_key(user_name, region=None, key=None, keyid=None, profile=None): ''' Create access key id for a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.create_access_key(user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create access key.') return six.text_type(e) def delete_access_key(access_key_id, user_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete access key id from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_access_key(access_key_id, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete access key id %s.', access_key_id) return six.text_type(e) def delete_user(user_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user myuser ''' if not get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.delete_user(user_name) log.info('Deleted IAM user : %s .', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM user %s', user_name) return six.text_type(e) def get_user(user_name=None, region=None, key=None, keyid=None, profile=None): ''' Get user information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user(user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM user %s info.', user_name) return False def create_group(group_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_group group ''' if not path: path = '/' if get_group(group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_group(group_name, path) log.info('Created IAM group : %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM group %s.', group_name) return False def get_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group(group_name, max_items=1) if not info: return False return info['get_group_response']['get_group_result']['group'] except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_group_members(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: marker = None truncated = True users = [] while truncated: info = conn.get_group(group_name, marker=marker, max_items=1000) if not info: return False truncated = bool(info['get_group_response']['get_group_result']['is_truncated']) if truncated and 'marker' in info['get_group_response']['get_group_result']: marker = info['get_group_response']['get_group_result']['marker'] else: marker = None truncated = False users += info['get_group_response']['get_group_result']['users'] return users except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get members for IAM group %s.', group_name) return False def add_user_to_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Add user to group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.add_user_to_group myuser mygroup ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('Username : %s does not exist.', user_name) return False if user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.add_user_to_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add IAM user %s to group %s.', user_name, group_name) return False def user_exists_in_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Check if user exists in group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.user_exists_in_group myuser mygroup ''' # TODO this should probably use boto.iam.get_groups_for_user users = get_group_members( group_name=group_name, region=region, key=key, keyid=keyid, profile=profile ) if users: for _user in users: if user_name == _user['user_name']: log.debug('IAM user %s is already in IAM group %s.', user_name, group_name) return True return False def remove_user_from_group(group_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Remove user from group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.remove_user_from_group mygroup myuser ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist.', user_name) return False if not user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.remove_user_from_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove IAM user %s from group %s', user_name, group_name) return False def put_group_policy(group_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_group_policy mygroup policyname policyrules ''' group = get_group(group_name, region=region, key=key, keyid=keyid, profile=profile) if not group: log.error('Group %s does not exist', group_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_group_policy(group_name, policy_name, policy_json) if created: log.info('Created policy for IAM group %s.', group_name) return True log.error('Could not create policy for IAM group %s', group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy for IAM group %s', group_name) return False def delete_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group_policy mygroup mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_group_policy( group_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_group_policy(group_name, policy_name) log.info('Successfully deleted policy %s for IAM group %s.', policy_name, group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM group %s.', policy_name, group_name) return False def get_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group_policy mygroup policyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group_policy(group_name, policy_name) log.debug('info for group policy is : %s', info) if not info: return False info = info.get_group_policy_response.get_group_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_all_groups(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM group details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_groups ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _groups = conn.get_all_groups(path_prefix=path_prefix) groups = _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) while marker: _groups = conn.get_all_groups(path_prefix=path_prefix, marker=marker) groups = groups + _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) return groups def get_all_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.get_all_instance_profiles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) marker = False profiles = [] while marker is not None: marker = marker if marker else None p = conn.list_instance_profiles(path_prefix=path_prefix, marker=marker) res = p.list_instance_profiles_response.list_instance_profiles_result profiles += res.instance_profiles marker = getattr(res, 'marker', None) return profiles def list_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' List all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.list_instance_profiles ''' p = get_all_instance_profiles(path_prefix, region, key, keyid, profile) return [i['instance_profile_name'] for i in p] def get_all_group_policies(group_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a group. CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_group_policies mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False try: response = conn.get_all_group_policies(group_name) _list = response.list_group_policies_response.list_group_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def delete_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _group = get_group( group_name, region, key, keyid, profile ) if not _group: return True try: conn.delete_group(group_name) log.info('Successfully deleted IAM group %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM group %s.', group_name) return False def create_login_profile(user_name, password, region=None, key=None, keyid=None, profile=None): ''' Creates a login profile for the specified user, give the user the ability to access AWS services and the AWS Management Console. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_login_profile user_name password ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.create_login_profile(user_name, password) log.info('Created profile for IAM user %s.', user_name) return info except boto.exception.BotoServerError as e: log.debug(e) if 'Conflict' in e: log.info('Profile already exists for IAM user %s.', user_name) return 'Conflict' log.error('Failed to update profile for IAM user %s.', user_name) return False def delete_login_profile(user_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a login profile for the specified user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_login_profile user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.delete_login_profile(user_name) log.info('Deleted login profile for IAM user %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Login profile already deleted for IAM user %s.', user_name) return True log.error('Failed to delete login profile for IAM user %s.', user_name) return False def get_all_mfa_devices(user_name, region=None, key=None, keyid=None, profile=None): ''' Get all MFA devices associated with an IAM user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_mfa_devices user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: result = conn.get_all_mfa_devices(user_name) devices = result['list_mfa_devices_response']['list_mfa_devices_result']['mfa_devices'] return devices except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Could not find IAM user %s.', user_name) return [] log.error('Failed to get all MFA devices for IAM user %s.', user_name) return False def deactivate_mfa_device(user_name, serial, region=None, key=None, keyid=None, profile=None): ''' Deactivates the specified MFA device and removes it from association with the user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.deactivate_mfa_device user_name serial_num ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.deactivate_mfa_device(user_name, serial) log.info('Deactivated MFA device %s for IAM user %s.', serial, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('MFA device %s not associated with IAM user %s.', serial, user_name) return True log.error('Failed to deactivate MFA device %s for IAM user %s.', serial, user_name) return False def delete_virtual_mfa_device(serial, region=None, key=None, keyid=None, profile=None): ''' Deletes the specified virtual MFA device. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_virtual_mfa_device serial_num ''' conn = __utils__['boto3.get_connection_func']('iam')() try: conn.delete_virtual_mfa_device(SerialNumber=serial) log.info('Deleted virtual MFA device %s.', serial) return True except botocore.exceptions.ClientError as e: log.debug(e) if 'NoSuchEntity' in six.text_type(e): log.info('Virtual MFA device %s not found.', serial) return True log.error('Failed to delete virtual MFA device %s.', serial) return False def update_account_password_policy(allow_users_to_change_password=None, hard_expiry=None, max_password_age=None, minimum_password_length=None, password_reuse_prevention=None, require_lowercase_characters=None, require_numbers=None, require_symbols=None, require_uppercase_characters=None, region=None, key=None, keyid=None, profile=None): ''' Update the password policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_account_password_policy True ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.update_account_password_policy(allow_users_to_change_password, hard_expiry, max_password_age, minimum_password_length, password_reuse_prevention, require_lowercase_characters, require_numbers, require_symbols, require_uppercase_characters) log.info('The password policy has been updated.') return True except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy' log.error(msg) return False def get_account_policy(region=None, key=None, keyid=None, profile=None): ''' Get account policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_account_password_policy() return info.get_account_password_policy_response.get_account_password_policy_result.password_policy except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy.' log.error(msg) return False def create_role(name, policy_document=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Create an instance role. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if role_exists(name, region, key, keyid, profile): return True if not policy_document: policy_document = None try: conn.create_role(name, assume_role_policy_document=policy_document, path=path) log.info('Created IAM role %s.', name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to create IAM role %s.', name) return False def delete_role(name, region=None, key=None, keyid=None, profile=None): ''' Delete an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(name, region, key, keyid, profile): return True try: conn.delete_role(name) log.info('Deleted %s IAM role.', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s IAM role.', name) return False def profile_associated(role_name, profile_name, region, key, keyid, profile): ''' Check to see if an instance profile is associated with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.profile_associated myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # The IAM module of boto doesn't return objects. Instead you need to grab # values through its properties. Sigh. try: profiles = conn.list_instance_profiles_for_role(role_name) except boto.exception.BotoServerError as e: log.debug(e) return False profiles = profiles.list_instance_profiles_for_role_response profiles = profiles.list_instance_profiles_for_role_result profiles = profiles.instance_profiles for profile in profiles: if profile.instance_profile_name == profile_name: return True return False def associate_profile_to_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Associate an instance profile with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.associate_profile_to_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if associated: return True else: try: conn.add_role_to_instance_profile(profile_name, role_name) log.info('Added %s instance profile to IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add %s instance profile to IAM role %s', profile_name, role_name) return False def disassociate_profile_from_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Disassociate an instance profile from an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.disassociate_profile_from_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if not associated: return True else: try: conn.remove_role_from_instance_profile(profile_name, role_name) log.info('Removed %s instance profile from IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove %s instance profile from IAM role %s.', profile_name, role_name) return False def list_role_policies(role_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_role_policies myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_role_policies(role_name) _list = response.list_role_policies_response.list_role_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def get_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.get_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: _policy = conn.get_role_policy(role_name, policy_name) # I _hate_ you for not giving me an object boto. _policy = _policy.get_role_policy_response.policy_document # Policy is url encoded _policy = _unquote(_policy) _policy = salt.utils.json.loads(_policy, object_pairs_hook=odict.OrderedDict) return _policy except boto.exception.BotoServerError: return {} def create_role_policy(role_name, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Create or modify a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role_policy myirole mypolicy '{"MyPolicy": "Statement": [{"Action": ["sqs:*"], "Effect": "Allow", "Resource": ["arn:aws:sqs:*:*:*"], "Sid": "MyPolicySqs1"}]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) mode = 'create' if _policy: if _policy == policy: return True mode = 'modify' if isinstance(policy, six.string_types): policy = salt.utils.json.loads(policy, object_pairs_hook=odict.OrderedDict) try: _policy = salt.utils.json.dumps(policy) conn.put_role_policy(role_name, policy_name, _policy) if mode == 'create': msg = 'Successfully added policy %s to IAM role %s.' else: msg = 'Successfully modified policy %s for IAM role %s.' log.info(msg, policy_name, role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to %s policy %s for IAM role %s.', mode, policy_name, role_name) return False def delete_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) if not _policy: return True try: conn.delete_role_policy(role_name, policy_name) log.info('Successfully deleted policy %s for IAM role %s.', policy_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM role %s.', policy_name, role_name) return False def update_assume_role_policy(role_name, policy_document, region=None, key=None, keyid=None, profile=None): ''' Update an assume role policy for a role. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_assume_role_policy myrole '{"Statement":"..."}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(policy_document, six.string_types): policy_document = salt.utils.json.loads(policy_document, object_pairs_hook=odict.OrderedDict) try: _policy_document = salt.utils.json.dumps(policy_document) conn.update_assume_role_policy(role_name, _policy_document) log.info('Successfully updated assume role policy for IAM role %s.', role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to update assume role policy for IAM role %s.', role_name) return False def build_policy(region=None, key=None, keyid=None, profile=None): ''' Build a default assume role policy. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.build_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if hasattr(conn, 'build_policy'): policy = salt.utils.json.loads(conn.build_policy()) elif hasattr(conn, '_build_policy'): policy = salt.utils.json.loads(conn._build_policy()) else: return {} # The format we get from build_policy isn't going to be what we get back # from AWS for the exact same policy. AWS converts single item list values # into strings, so let's do the same here. for key, policy_val in policy.items(): for statement in policy_val: if (isinstance(statement['Action'], list) and len(statement['Action']) == 1): statement['Action'] = statement['Action'][0] if (isinstance(statement['Principal']['Service'], list) and len(statement['Principal']['Service']) == 1): statement['Principal']['Service'] = statement['Principal']['Service'][0] # build_policy doesn't add a version field, which AWS is going to set to a # default value, when we get it back, so let's set it. policy['Version'] = '2008-10-17' return policy def get_account_id(region=None, key=None, keyid=None, profile=None): ''' Get a the AWS account id associated with the used credentials. CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_id ''' cache_key = 'boto_iam.account_id' if cache_key not in __context__: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_user() # The get_user call returns an user ARN: # arn:aws:iam::027050522557:user/salt-test arn = ret['get_user_response']['get_user_result']['user']['arn'] account_id = arn.split(':')[4] except boto.exception.BotoServerError: # If call failed, then let's try to get the ARN from the metadata timeout = boto.config.getfloat( 'Boto', 'metadata_service_timeout', 1.0 ) attempts = boto.config.getint( 'Boto', 'metadata_service_num_attempts', 1 ) identity = boto.utils.get_instance_identity( timeout=timeout, num_retries=attempts ) try: account_id = identity['document']['accountId'] except KeyError: log.error('Failed to get account id from instance_identity in' ' boto_iam.get_account_id.') __context__[cache_key] = account_id return __context__[cache_key] def get_all_roles(path_prefix=None, region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM role details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_roles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _roles = conn.list_roles(path_prefix=path_prefix) roles = _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) while marker: _roles = conn.list_roles(path_prefix=path_prefix, marker=marker) roles = roles + _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) return roles def get_all_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM user details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_users ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _users = conn.get_all_users(path_prefix=path_prefix) users = _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) while marker: _users = conn.get_all_users(path_prefix=path_prefix, marker=marker) users = users + _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) return users def get_all_user_policies(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all user policies. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_user_policies myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_all_user_policies(user_name, marker, max_items) if not info: return False _list = info.list_user_policies_response.list_user_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policies for user %s.', user_name) return False def get_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user_policy myuser mypolicyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user_policy(user_name, policy_name) log.debug('Info for IAM user %s policy %s: %s.', user_name, policy_name, info) if not info: return False info = info.get_user_policy_response.get_user_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policy %s for IAM user %s.', policy_name, user_name) return False def put_user_policy(user_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_user_policy myuser policyname policyrules ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_user_policy(user_name, policy_name, policy_json) if created: log.info('Created policy %s for IAM user %s.', policy_name, user_name) return True log.error('Could not create policy %s for IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy %s for IAM user %s.', policy_name, user_name) return False def delete_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user_policy myuser mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_user_policy( user_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_user_policy(user_name, policy_name) log.info('Successfully deleted policy %s for IAM user %s.', policy_name, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM user %s.', policy_name, user_name) return False def upload_server_cert(cert_name, cert_body, private_key, cert_chain=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Upload a certificate to Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.upload_server_cert mycert_name crt priv_key :param cert_name: The name for the server certificate. Do not include the path in this value. :param cert_body: The contents of the public key certificate in PEM-encoded format. :param private_key: The contents of the private key in PEM-encoded format. :param cert_chain: The contents of the certificate chain. This is typically a concatenation of the PEM-encoded public key certificates of the chain. :param path: The path for the server certificate. :param region: The name of the region to connect to. :param key: The key to be used in order to connect :param keyid: The keyid to be used in order to connect :param profile: The profile that contains a dict of region, key, keyid :return: True / False ''' exists = get_server_certificate(cert_name, region, key, keyid, profile) if exists: return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.upload_server_cert(cert_name, cert_body, private_key, cert_chain) log.info('Created certificate %s.', cert_name) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to failed to create certificate %s.', cert_name) return False def get_server_certificate(cert_name, region=None, key=None, keyid=None, profile=None): ''' Returns certificate information from Amazon .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_server_certificate mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_server_certificate(cert_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get certificate %s information.', cert_name) return False def delete_server_cert(cert_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a certificate from Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_server_cert mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_server_cert(cert_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete certificate %s.', cert_name) return False def export_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM user details. Produces results that can be used to create an sls file. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.export_users --out=txt | sed "s/local: //" > iam_users.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() users = get_all_users(path_prefix, region, key, keyid, profile) for user in users: name = user.user_name _policies = conn.get_all_user_policies(name, max_items=100) _policies = _policies.list_user_policies_response.list_user_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_user_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_user_policy_response.get_user_policy_result.policy_document )) policies[policy_name] = _policy user_sls = [] user_sls.append({"name": name}) user_sls.append({"policies": policies}) user_sls.append({"path": user.path}) results["manage user " + name] = {"boto_iam.user_present": user_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def export_roles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM role details. Produces results that can be used to create an sls file. CLI Example: salt-call boto_iam.export_roles --out=txt | sed "s/local: //" > iam_roles.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() roles = get_all_roles(path_prefix, region, key, keyid, profile) for role in roles: name = role.role_name _policies = conn.list_role_policies(name, max_items=100) _policies = _policies.list_role_policies_response.list_role_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_role_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_role_policy_response.get_role_policy_result.policy_document )) policies[policy_name] = _policy role_sls = [] role_sls.append({"name": name}) role_sls.append({"policies": policies}) role_sls.append({'policy_document': salt.utils.json.loads(_unquote(role.assume_role_policy_document))}) role_sls.append({"path": role.path}) results["manage role " + name] = {"boto_iam_role.present": role_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def _get_policy_arn(name, region=None, key=None, keyid=None, profile=None): if name.startswith('arn:aws:iam:'): return name account_id = get_account_id( region=region, key=key, keyid=keyid, profile=profile ) return 'arn:aws:iam::{0}:policy/{1}'.format(account_id, name) def policy_exists(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return True except boto.exception.BotoServerError: return False def get_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return ret.get('get_policy_response', {}).get('get_policy_result', {}) except boto.exception.BotoServerError: return None def create_policy(policy_name, policy_document, path=None, description=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in 'path', 'description': if locals()[arg] is not None: params[arg] = locals()[arg] if policy_exists(policy_name, region, key, keyid, profile): return True try: conn.create_policy(policy_name, policy_document, **params) log.info('Created IAM policy %s.', policy_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s.', policy_name) return False return True def delete_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_exists(policy_arn, region, key, keyid, profile): return True try: conn.delete_policy(policy_arn) log.info('Deleted %s policy.', policy_name) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete %s policy: %s.', policy_name, aws.get('message')) return False return True def list_policies(region=None, key=None, keyid=None, profile=None): ''' List policies. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policies ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: policies = [] for ret in __utils__['boto.paged_call'](conn.list_policies): policies.append(ret.get('list_policies_response', {}).get('list_policies_result', {}).get('policies')) return policies except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to list policy versions.' log.error(msg) return [] def policy_version_exists(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.get_policy_version(policy_arn, version_id) return True except boto.exception.BotoServerError: return False def get_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy_version(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile), version_id) retval = ret.get('get_policy_version_response', {}).get('get_policy_version_result', {}).get('policy_version', {}) retval['document'] = _unquote(retval.get('document')) return {'policy_version': retval} except boto.exception.BotoServerError: return None def create_policy_version(policy_name, policy_document, set_as_default=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy version. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy_version mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in ('set_as_default',): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.create_policy_version(policy_arn, policy_document, **params) vid = ret.get('create_policy_version_response', {}).get('create_policy_version_result', {}).get('policy_version', {}).get('version_id') log.info('Created IAM policy %s version %s.', policy_name, vid) return {'created': True, 'version_id': vid} except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s version %s.', policy_name, vid) return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Delete a policy version. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_version_exists(policy_arn, version_id, region, key, keyid, profile): return True try: conn.delete_policy_version(policy_arn, version_id) log.info('Deleted IAM policy %s version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete IAM policy %s version %s: %s', policy_name, version_id, aws.get('message')) return False return True def list_policy_versions(policy_name, region=None, key=None, keyid=None, profile=None): ''' List versions of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policy_versions mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.list_policy_versions(policy_arn) return ret.get('list_policy_versions_response', {}).get('list_policy_versions_result', {}).get('versions') except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list versions for IAM policy %s.', policy_name) return [] def set_default_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Set the default version of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.set_default_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.set_default_policy_version(policy_arn, version_id) log.info('Set %s policy to version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to set %s policy to version %s: %s', policy_name, version_id, aws.get('message')) return False return True def attach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_user_policy(policy_arn, user_name) log.info('Attached policy %s to IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach %s policy to IAM user %s.', policy_name, user_name) return False return True def detach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_user_policy(policy_arn, user_name) log.info('Detached %s policy from IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach %s policy from IAM user %s.', policy_name, user_name) return False return True def attach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_group_policy(policy_arn, group_name) log.info('Attached policy %s to IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM group %s.', policy_name, group_name) return False return True def detach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_group_policy(policy_arn, group_name) log.info('Detached policy %s from IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM group %s.', policy_name, group_name) return False return True def attach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_role_policy(policy_arn, role_name) log.info('Attached policy %s to IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM role %s.', policy_name, role_name) return False return True def detach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_role_policy(policy_arn, role_name) log.info('Detached policy %s from IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM role %s.', policy_name, role_name) return False return True def list_entities_for_policy(policy_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities that a policy is attached to. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 params = {} for arg in ('path_prefix', 'entity_filter'): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) while retries: try: allret = { 'policy_groups': [], 'policy_users': [], 'policy_roles': [], } for ret in __utils__['boto.paged_call'](conn.list_entities_for_policy, policy_arn=policy_arn, **params): for k, v in six.iteritems(allret): v.extend(ret.get('list_entities_for_policy_response', {}).get('list_entities_for_policy_result', {}).get(k)) return allret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('Failed to list entities for IAM policy %s: %s', policy_name, e.message) return {} return {} def list_attached_user_policies(user_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given user. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'UserName': user_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedUserPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_user_policies_response', {}).get('list_attached_user_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM user %s.', user_name) return [] def list_attached_group_policies(group_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given group. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'GroupName': group_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedGroupPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_group_policies_response', {}).get('list_attached_group_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM group %s.', group_name) return [] def list_attached_role_policies(role_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'RoleName': role_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedRolePolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_role_policies_response', {}).get('list_attached_role_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM role %s.', role_name) return [] def create_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Create SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.create_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_saml_provider(saml_metadata_document, name) log.info('Successfully created %s SAML provider.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to create SAML provider %s.', name) return False def get_saml_provider_arn(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider_arn my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_saml_providers() for saml_provider in response.list_saml_providers_response.list_saml_providers_result.saml_provider_list: if saml_provider['arn'].endswith(':saml-provider/' + name): return saml_provider['arn'] return False except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to get ARN of SAML provider %s.', name) return False def delete_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Delete SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.delete_saml_provider my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return True conn.delete_saml_provider(saml_provider_arn) log.info('Successfully deleted SAML provider %s.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete SAML provider %s.', name) return False def list_saml_providers(region=None, key=None, keyid=None, profile=None): ''' List SAML providers. CLI Example: .. code-block:: bash salt myminion boto_iam.list_saml_providers ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: providers = [] info = conn.list_saml_providers() for arn in info['list_saml_providers_response']['list_saml_providers_result']['saml_provider_list']: providers.append(arn['arn'].rsplit('/', 1)[1]) return providers except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get list of SAML providers.') return False def get_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider document. CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider arn ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: provider = conn.get_saml_provider(name) return provider['get_saml_provider_response']['get_saml_provider_result']['saml_metadata_document'] except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get SAML provider document %s.', name) return False def update_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Update SAML provider. CLI Example: .. code-block:: bash salt myminion boto_iam.update_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return False if conn.update_saml_provider(name, saml_metadata_document): return True return False except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to update SAML provider %s.', name) return False
saltstack/salt
salt/modules/boto_iam.py
delete_server_cert
python
def delete_server_cert(cert_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a certificate from Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_server_cert mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_server_cert(cert_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete certificate %s.', cert_name) return False
Deletes a certificate from Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_server_cert mycert_name
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iam.py#L1599-L1617
null
# -*- coding: utf-8 -*- ''' Connection module for Amazon IAM .. versionadded:: 2014.7.0 :configuration: This module accepts explicit iam 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 iam.keyid: GKTADJGHEIQSXMKKRBJ08H iam.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs iam.region: 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: boto ''' # keep lint from choking on _get_conn and _cache_id #pylint: disable=E0602 # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import salt libs from salt.ext import six import salt.utils.compat import salt.utils.json import salt.utils.odict as odict import salt.utils.versions from salt.exceptions import SaltInvocationError # Import third party libs # pylint: disable=unused-import from salt.ext.six.moves.urllib.parse import unquote as _unquote # pylint: disable=no-name-in-module try: import boto import boto.iam import boto3 import botocore logging.getLogger('boto').setLevel(logging.CRITICAL) logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=unused-import log = logging.getLogger(__name__) def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'iam', pack=__salt__) def instance_profile_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an instance profile exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: # Boto weirdly returns an exception here if an instance profile doesn't # exist. conn.get_instance_profile(name) return True except boto.exception.BotoServerError: return False def create_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Create an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.create_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if instance_profile_exists(name, region, key, keyid, profile): return True try: # This call returns an instance profile if successful and an exception # if not. It's annoying. conn.create_instance_profile(name) log.info('Created %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create %s instance profile.', name) return False return True def delete_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Delete an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not instance_profile_exists(name, region, key, keyid, profile): return True try: conn.delete_instance_profile(name) log.info('Deleted %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s instance profile.', name) return False return True def role_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an IAM role exists. CLI Example: .. code-block:: bash salt myminion boto_iam.role_exists myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_role(name) return True except boto.exception.BotoServerError: return False def describe_role(name, region=None, key=None, keyid=None, profile=None): ''' Get information for a role. CLI Example: .. code-block:: bash salt myminion boto_iam.describe_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_role(name) if not info: return False role = info.get_role_response.get_role_result.role role['assume_role_policy_document'] = salt.utils.json.loads(_unquote( role.assume_role_policy_document )) # If Sid wasn't defined by the user, boto will still return a Sid in # each policy. To properly check idempotently, let's remove the Sid # from the return if it's not actually set. for policy_key, policy in role['assume_role_policy_document'].items(): if policy_key == 'Statement': for val in policy: if 'Sid' in val and not val['Sid']: del val['Sid'] return role except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get %s information.', name) return False def create_user(user_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_user myuser ''' if not path: path = '/' if get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_user(user_name, path) log.info('Created IAM user : %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM user %s.', user_name) return False def get_all_access_keys(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all access keys from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_access_keys myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.get_all_access_keys(user_name, marker, max_items) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get access keys for IAM user %s.', user_name) return six.text_type(e) def create_access_key(user_name, region=None, key=None, keyid=None, profile=None): ''' Create access key id for a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.create_access_key(user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create access key.') return six.text_type(e) def delete_access_key(access_key_id, user_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete access key id from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_access_key(access_key_id, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete access key id %s.', access_key_id) return six.text_type(e) def delete_user(user_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user myuser ''' if not get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.delete_user(user_name) log.info('Deleted IAM user : %s .', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM user %s', user_name) return six.text_type(e) def get_user(user_name=None, region=None, key=None, keyid=None, profile=None): ''' Get user information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user(user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM user %s info.', user_name) return False def create_group(group_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_group group ''' if not path: path = '/' if get_group(group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_group(group_name, path) log.info('Created IAM group : %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM group %s.', group_name) return False def get_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group(group_name, max_items=1) if not info: return False return info['get_group_response']['get_group_result']['group'] except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_group_members(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: marker = None truncated = True users = [] while truncated: info = conn.get_group(group_name, marker=marker, max_items=1000) if not info: return False truncated = bool(info['get_group_response']['get_group_result']['is_truncated']) if truncated and 'marker' in info['get_group_response']['get_group_result']: marker = info['get_group_response']['get_group_result']['marker'] else: marker = None truncated = False users += info['get_group_response']['get_group_result']['users'] return users except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get members for IAM group %s.', group_name) return False def add_user_to_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Add user to group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.add_user_to_group myuser mygroup ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('Username : %s does not exist.', user_name) return False if user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.add_user_to_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add IAM user %s to group %s.', user_name, group_name) return False def user_exists_in_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Check if user exists in group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.user_exists_in_group myuser mygroup ''' # TODO this should probably use boto.iam.get_groups_for_user users = get_group_members( group_name=group_name, region=region, key=key, keyid=keyid, profile=profile ) if users: for _user in users: if user_name == _user['user_name']: log.debug('IAM user %s is already in IAM group %s.', user_name, group_name) return True return False def remove_user_from_group(group_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Remove user from group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.remove_user_from_group mygroup myuser ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist.', user_name) return False if not user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.remove_user_from_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove IAM user %s from group %s', user_name, group_name) return False def put_group_policy(group_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_group_policy mygroup policyname policyrules ''' group = get_group(group_name, region=region, key=key, keyid=keyid, profile=profile) if not group: log.error('Group %s does not exist', group_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_group_policy(group_name, policy_name, policy_json) if created: log.info('Created policy for IAM group %s.', group_name) return True log.error('Could not create policy for IAM group %s', group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy for IAM group %s', group_name) return False def delete_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group_policy mygroup mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_group_policy( group_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_group_policy(group_name, policy_name) log.info('Successfully deleted policy %s for IAM group %s.', policy_name, group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM group %s.', policy_name, group_name) return False def get_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group_policy mygroup policyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group_policy(group_name, policy_name) log.debug('info for group policy is : %s', info) if not info: return False info = info.get_group_policy_response.get_group_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_all_groups(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM group details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_groups ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _groups = conn.get_all_groups(path_prefix=path_prefix) groups = _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) while marker: _groups = conn.get_all_groups(path_prefix=path_prefix, marker=marker) groups = groups + _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) return groups def get_all_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.get_all_instance_profiles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) marker = False profiles = [] while marker is not None: marker = marker if marker else None p = conn.list_instance_profiles(path_prefix=path_prefix, marker=marker) res = p.list_instance_profiles_response.list_instance_profiles_result profiles += res.instance_profiles marker = getattr(res, 'marker', None) return profiles def list_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' List all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.list_instance_profiles ''' p = get_all_instance_profiles(path_prefix, region, key, keyid, profile) return [i['instance_profile_name'] for i in p] def get_all_group_policies(group_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a group. CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_group_policies mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False try: response = conn.get_all_group_policies(group_name) _list = response.list_group_policies_response.list_group_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def delete_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _group = get_group( group_name, region, key, keyid, profile ) if not _group: return True try: conn.delete_group(group_name) log.info('Successfully deleted IAM group %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM group %s.', group_name) return False def create_login_profile(user_name, password, region=None, key=None, keyid=None, profile=None): ''' Creates a login profile for the specified user, give the user the ability to access AWS services and the AWS Management Console. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_login_profile user_name password ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.create_login_profile(user_name, password) log.info('Created profile for IAM user %s.', user_name) return info except boto.exception.BotoServerError as e: log.debug(e) if 'Conflict' in e: log.info('Profile already exists for IAM user %s.', user_name) return 'Conflict' log.error('Failed to update profile for IAM user %s.', user_name) return False def delete_login_profile(user_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a login profile for the specified user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_login_profile user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.delete_login_profile(user_name) log.info('Deleted login profile for IAM user %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Login profile already deleted for IAM user %s.', user_name) return True log.error('Failed to delete login profile for IAM user %s.', user_name) return False def get_all_mfa_devices(user_name, region=None, key=None, keyid=None, profile=None): ''' Get all MFA devices associated with an IAM user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_mfa_devices user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: result = conn.get_all_mfa_devices(user_name) devices = result['list_mfa_devices_response']['list_mfa_devices_result']['mfa_devices'] return devices except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Could not find IAM user %s.', user_name) return [] log.error('Failed to get all MFA devices for IAM user %s.', user_name) return False def deactivate_mfa_device(user_name, serial, region=None, key=None, keyid=None, profile=None): ''' Deactivates the specified MFA device and removes it from association with the user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.deactivate_mfa_device user_name serial_num ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.deactivate_mfa_device(user_name, serial) log.info('Deactivated MFA device %s for IAM user %s.', serial, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('MFA device %s not associated with IAM user %s.', serial, user_name) return True log.error('Failed to deactivate MFA device %s for IAM user %s.', serial, user_name) return False def delete_virtual_mfa_device(serial, region=None, key=None, keyid=None, profile=None): ''' Deletes the specified virtual MFA device. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_virtual_mfa_device serial_num ''' conn = __utils__['boto3.get_connection_func']('iam')() try: conn.delete_virtual_mfa_device(SerialNumber=serial) log.info('Deleted virtual MFA device %s.', serial) return True except botocore.exceptions.ClientError as e: log.debug(e) if 'NoSuchEntity' in six.text_type(e): log.info('Virtual MFA device %s not found.', serial) return True log.error('Failed to delete virtual MFA device %s.', serial) return False def update_account_password_policy(allow_users_to_change_password=None, hard_expiry=None, max_password_age=None, minimum_password_length=None, password_reuse_prevention=None, require_lowercase_characters=None, require_numbers=None, require_symbols=None, require_uppercase_characters=None, region=None, key=None, keyid=None, profile=None): ''' Update the password policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_account_password_policy True ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.update_account_password_policy(allow_users_to_change_password, hard_expiry, max_password_age, minimum_password_length, password_reuse_prevention, require_lowercase_characters, require_numbers, require_symbols, require_uppercase_characters) log.info('The password policy has been updated.') return True except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy' log.error(msg) return False def get_account_policy(region=None, key=None, keyid=None, profile=None): ''' Get account policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_account_password_policy() return info.get_account_password_policy_response.get_account_password_policy_result.password_policy except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy.' log.error(msg) return False def create_role(name, policy_document=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Create an instance role. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if role_exists(name, region, key, keyid, profile): return True if not policy_document: policy_document = None try: conn.create_role(name, assume_role_policy_document=policy_document, path=path) log.info('Created IAM role %s.', name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to create IAM role %s.', name) return False def delete_role(name, region=None, key=None, keyid=None, profile=None): ''' Delete an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(name, region, key, keyid, profile): return True try: conn.delete_role(name) log.info('Deleted %s IAM role.', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s IAM role.', name) return False def profile_associated(role_name, profile_name, region, key, keyid, profile): ''' Check to see if an instance profile is associated with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.profile_associated myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # The IAM module of boto doesn't return objects. Instead you need to grab # values through its properties. Sigh. try: profiles = conn.list_instance_profiles_for_role(role_name) except boto.exception.BotoServerError as e: log.debug(e) return False profiles = profiles.list_instance_profiles_for_role_response profiles = profiles.list_instance_profiles_for_role_result profiles = profiles.instance_profiles for profile in profiles: if profile.instance_profile_name == profile_name: return True return False def associate_profile_to_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Associate an instance profile with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.associate_profile_to_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if associated: return True else: try: conn.add_role_to_instance_profile(profile_name, role_name) log.info('Added %s instance profile to IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add %s instance profile to IAM role %s', profile_name, role_name) return False def disassociate_profile_from_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Disassociate an instance profile from an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.disassociate_profile_from_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if not associated: return True else: try: conn.remove_role_from_instance_profile(profile_name, role_name) log.info('Removed %s instance profile from IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove %s instance profile from IAM role %s.', profile_name, role_name) return False def list_role_policies(role_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_role_policies myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_role_policies(role_name) _list = response.list_role_policies_response.list_role_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def get_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.get_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: _policy = conn.get_role_policy(role_name, policy_name) # I _hate_ you for not giving me an object boto. _policy = _policy.get_role_policy_response.policy_document # Policy is url encoded _policy = _unquote(_policy) _policy = salt.utils.json.loads(_policy, object_pairs_hook=odict.OrderedDict) return _policy except boto.exception.BotoServerError: return {} def create_role_policy(role_name, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Create or modify a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role_policy myirole mypolicy '{"MyPolicy": "Statement": [{"Action": ["sqs:*"], "Effect": "Allow", "Resource": ["arn:aws:sqs:*:*:*"], "Sid": "MyPolicySqs1"}]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) mode = 'create' if _policy: if _policy == policy: return True mode = 'modify' if isinstance(policy, six.string_types): policy = salt.utils.json.loads(policy, object_pairs_hook=odict.OrderedDict) try: _policy = salt.utils.json.dumps(policy) conn.put_role_policy(role_name, policy_name, _policy) if mode == 'create': msg = 'Successfully added policy %s to IAM role %s.' else: msg = 'Successfully modified policy %s for IAM role %s.' log.info(msg, policy_name, role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to %s policy %s for IAM role %s.', mode, policy_name, role_name) return False def delete_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) if not _policy: return True try: conn.delete_role_policy(role_name, policy_name) log.info('Successfully deleted policy %s for IAM role %s.', policy_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM role %s.', policy_name, role_name) return False def update_assume_role_policy(role_name, policy_document, region=None, key=None, keyid=None, profile=None): ''' Update an assume role policy for a role. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_assume_role_policy myrole '{"Statement":"..."}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(policy_document, six.string_types): policy_document = salt.utils.json.loads(policy_document, object_pairs_hook=odict.OrderedDict) try: _policy_document = salt.utils.json.dumps(policy_document) conn.update_assume_role_policy(role_name, _policy_document) log.info('Successfully updated assume role policy for IAM role %s.', role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to update assume role policy for IAM role %s.', role_name) return False def build_policy(region=None, key=None, keyid=None, profile=None): ''' Build a default assume role policy. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.build_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if hasattr(conn, 'build_policy'): policy = salt.utils.json.loads(conn.build_policy()) elif hasattr(conn, '_build_policy'): policy = salt.utils.json.loads(conn._build_policy()) else: return {} # The format we get from build_policy isn't going to be what we get back # from AWS for the exact same policy. AWS converts single item list values # into strings, so let's do the same here. for key, policy_val in policy.items(): for statement in policy_val: if (isinstance(statement['Action'], list) and len(statement['Action']) == 1): statement['Action'] = statement['Action'][0] if (isinstance(statement['Principal']['Service'], list) and len(statement['Principal']['Service']) == 1): statement['Principal']['Service'] = statement['Principal']['Service'][0] # build_policy doesn't add a version field, which AWS is going to set to a # default value, when we get it back, so let's set it. policy['Version'] = '2008-10-17' return policy def get_account_id(region=None, key=None, keyid=None, profile=None): ''' Get a the AWS account id associated with the used credentials. CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_id ''' cache_key = 'boto_iam.account_id' if cache_key not in __context__: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_user() # The get_user call returns an user ARN: # arn:aws:iam::027050522557:user/salt-test arn = ret['get_user_response']['get_user_result']['user']['arn'] account_id = arn.split(':')[4] except boto.exception.BotoServerError: # If call failed, then let's try to get the ARN from the metadata timeout = boto.config.getfloat( 'Boto', 'metadata_service_timeout', 1.0 ) attempts = boto.config.getint( 'Boto', 'metadata_service_num_attempts', 1 ) identity = boto.utils.get_instance_identity( timeout=timeout, num_retries=attempts ) try: account_id = identity['document']['accountId'] except KeyError: log.error('Failed to get account id from instance_identity in' ' boto_iam.get_account_id.') __context__[cache_key] = account_id return __context__[cache_key] def get_all_roles(path_prefix=None, region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM role details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_roles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _roles = conn.list_roles(path_prefix=path_prefix) roles = _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) while marker: _roles = conn.list_roles(path_prefix=path_prefix, marker=marker) roles = roles + _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) return roles def get_all_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM user details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_users ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _users = conn.get_all_users(path_prefix=path_prefix) users = _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) while marker: _users = conn.get_all_users(path_prefix=path_prefix, marker=marker) users = users + _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) return users def get_all_user_policies(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all user policies. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_user_policies myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_all_user_policies(user_name, marker, max_items) if not info: return False _list = info.list_user_policies_response.list_user_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policies for user %s.', user_name) return False def get_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user_policy myuser mypolicyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user_policy(user_name, policy_name) log.debug('Info for IAM user %s policy %s: %s.', user_name, policy_name, info) if not info: return False info = info.get_user_policy_response.get_user_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policy %s for IAM user %s.', policy_name, user_name) return False def put_user_policy(user_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_user_policy myuser policyname policyrules ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_user_policy(user_name, policy_name, policy_json) if created: log.info('Created policy %s for IAM user %s.', policy_name, user_name) return True log.error('Could not create policy %s for IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy %s for IAM user %s.', policy_name, user_name) return False def delete_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user_policy myuser mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_user_policy( user_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_user_policy(user_name, policy_name) log.info('Successfully deleted policy %s for IAM user %s.', policy_name, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM user %s.', policy_name, user_name) return False def upload_server_cert(cert_name, cert_body, private_key, cert_chain=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Upload a certificate to Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.upload_server_cert mycert_name crt priv_key :param cert_name: The name for the server certificate. Do not include the path in this value. :param cert_body: The contents of the public key certificate in PEM-encoded format. :param private_key: The contents of the private key in PEM-encoded format. :param cert_chain: The contents of the certificate chain. This is typically a concatenation of the PEM-encoded public key certificates of the chain. :param path: The path for the server certificate. :param region: The name of the region to connect to. :param key: The key to be used in order to connect :param keyid: The keyid to be used in order to connect :param profile: The profile that contains a dict of region, key, keyid :return: True / False ''' exists = get_server_certificate(cert_name, region, key, keyid, profile) if exists: return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.upload_server_cert(cert_name, cert_body, private_key, cert_chain) log.info('Created certificate %s.', cert_name) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to failed to create certificate %s.', cert_name) return False def list_server_certificates(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Lists the server certificates stored in IAM that have the specified path prefix. .. versionadded:: ??? :param path_prefix: The path prefix for filtering the results. For example: /company/servercerts would get all server certificates for which the path starts with /company/servercerts . This parameter is optional. If it is not included, it defaults to a slash (/), listing all server certificates. This parameter allows (per its regex pattern) a string of characters consisting of either a forward slash (/) by itself or a string that must begin and end with forward slashes. In addition, it can contain any ASCII character from the ! (u0021) through the DEL character (u007F), including most punctuation characters, digits, and upper and lowercased letters. CLI Example: .. code-block:: bash salt myminion boto_iam.list_server_certificates path_prefix=/somepath/ ''' retries = 10 sleep = 6 conn = __utils__['boto3.get_connection']('iam', region=region, key=key, keyid=keyid, profile=profile) Items = [] while retries: try: log.debug('Garnering list of IAM Server Certificates') IsTruncated = True while IsTruncated: kwargs = {'PathPrefix': path_prefix} ret = conn.list_server_certificates(**kwargs) Items += ret.get('ServerCertificateMetadataList', []) IsTruncated = ret.get('IsTruncated') kwargs.update({'Marker': ret.get('Marker')}) return Items except botocore.exceptions.ParamValidationError as err: raise SaltInvocationError(str(err)) except botocore.exceptions.ClientError as err: if retries and jmespath.search('Error.Code', err.response) == 'Throttling': retries -= 1 log.debug('Throttled by AWS API, retrying in %s seconds...', sleep) time.sleep(sleep) continue log.error('Failed to list IAM Server Certificates: %s', err.message) return None def get_server_certificate(cert_name, region=None, key=None, keyid=None, profile=None): ''' Returns certificate information from Amazon .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_server_certificate mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_server_certificate(cert_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get certificate %s information.', cert_name) return False def export_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM user details. Produces results that can be used to create an sls file. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.export_users --out=txt | sed "s/local: //" > iam_users.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() users = get_all_users(path_prefix, region, key, keyid, profile) for user in users: name = user.user_name _policies = conn.get_all_user_policies(name, max_items=100) _policies = _policies.list_user_policies_response.list_user_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_user_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_user_policy_response.get_user_policy_result.policy_document )) policies[policy_name] = _policy user_sls = [] user_sls.append({"name": name}) user_sls.append({"policies": policies}) user_sls.append({"path": user.path}) results["manage user " + name] = {"boto_iam.user_present": user_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def export_roles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM role details. Produces results that can be used to create an sls file. CLI Example: salt-call boto_iam.export_roles --out=txt | sed "s/local: //" > iam_roles.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() roles = get_all_roles(path_prefix, region, key, keyid, profile) for role in roles: name = role.role_name _policies = conn.list_role_policies(name, max_items=100) _policies = _policies.list_role_policies_response.list_role_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_role_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_role_policy_response.get_role_policy_result.policy_document )) policies[policy_name] = _policy role_sls = [] role_sls.append({"name": name}) role_sls.append({"policies": policies}) role_sls.append({'policy_document': salt.utils.json.loads(_unquote(role.assume_role_policy_document))}) role_sls.append({"path": role.path}) results["manage role " + name] = {"boto_iam_role.present": role_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def _get_policy_arn(name, region=None, key=None, keyid=None, profile=None): if name.startswith('arn:aws:iam:'): return name account_id = get_account_id( region=region, key=key, keyid=keyid, profile=profile ) return 'arn:aws:iam::{0}:policy/{1}'.format(account_id, name) def policy_exists(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return True except boto.exception.BotoServerError: return False def get_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return ret.get('get_policy_response', {}).get('get_policy_result', {}) except boto.exception.BotoServerError: return None def create_policy(policy_name, policy_document, path=None, description=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in 'path', 'description': if locals()[arg] is not None: params[arg] = locals()[arg] if policy_exists(policy_name, region, key, keyid, profile): return True try: conn.create_policy(policy_name, policy_document, **params) log.info('Created IAM policy %s.', policy_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s.', policy_name) return False return True def delete_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_exists(policy_arn, region, key, keyid, profile): return True try: conn.delete_policy(policy_arn) log.info('Deleted %s policy.', policy_name) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete %s policy: %s.', policy_name, aws.get('message')) return False return True def list_policies(region=None, key=None, keyid=None, profile=None): ''' List policies. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policies ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: policies = [] for ret in __utils__['boto.paged_call'](conn.list_policies): policies.append(ret.get('list_policies_response', {}).get('list_policies_result', {}).get('policies')) return policies except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to list policy versions.' log.error(msg) return [] def policy_version_exists(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.get_policy_version(policy_arn, version_id) return True except boto.exception.BotoServerError: return False def get_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy_version(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile), version_id) retval = ret.get('get_policy_version_response', {}).get('get_policy_version_result', {}).get('policy_version', {}) retval['document'] = _unquote(retval.get('document')) return {'policy_version': retval} except boto.exception.BotoServerError: return None def create_policy_version(policy_name, policy_document, set_as_default=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy version. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy_version mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in ('set_as_default',): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.create_policy_version(policy_arn, policy_document, **params) vid = ret.get('create_policy_version_response', {}).get('create_policy_version_result', {}).get('policy_version', {}).get('version_id') log.info('Created IAM policy %s version %s.', policy_name, vid) return {'created': True, 'version_id': vid} except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s version %s.', policy_name, vid) return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Delete a policy version. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_version_exists(policy_arn, version_id, region, key, keyid, profile): return True try: conn.delete_policy_version(policy_arn, version_id) log.info('Deleted IAM policy %s version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete IAM policy %s version %s: %s', policy_name, version_id, aws.get('message')) return False return True def list_policy_versions(policy_name, region=None, key=None, keyid=None, profile=None): ''' List versions of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policy_versions mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.list_policy_versions(policy_arn) return ret.get('list_policy_versions_response', {}).get('list_policy_versions_result', {}).get('versions') except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list versions for IAM policy %s.', policy_name) return [] def set_default_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Set the default version of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.set_default_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.set_default_policy_version(policy_arn, version_id) log.info('Set %s policy to version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to set %s policy to version %s: %s', policy_name, version_id, aws.get('message')) return False return True def attach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_user_policy(policy_arn, user_name) log.info('Attached policy %s to IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach %s policy to IAM user %s.', policy_name, user_name) return False return True def detach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_user_policy(policy_arn, user_name) log.info('Detached %s policy from IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach %s policy from IAM user %s.', policy_name, user_name) return False return True def attach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_group_policy(policy_arn, group_name) log.info('Attached policy %s to IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM group %s.', policy_name, group_name) return False return True def detach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_group_policy(policy_arn, group_name) log.info('Detached policy %s from IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM group %s.', policy_name, group_name) return False return True def attach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_role_policy(policy_arn, role_name) log.info('Attached policy %s to IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM role %s.', policy_name, role_name) return False return True def detach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_role_policy(policy_arn, role_name) log.info('Detached policy %s from IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM role %s.', policy_name, role_name) return False return True def list_entities_for_policy(policy_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities that a policy is attached to. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 params = {} for arg in ('path_prefix', 'entity_filter'): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) while retries: try: allret = { 'policy_groups': [], 'policy_users': [], 'policy_roles': [], } for ret in __utils__['boto.paged_call'](conn.list_entities_for_policy, policy_arn=policy_arn, **params): for k, v in six.iteritems(allret): v.extend(ret.get('list_entities_for_policy_response', {}).get('list_entities_for_policy_result', {}).get(k)) return allret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('Failed to list entities for IAM policy %s: %s', policy_name, e.message) return {} return {} def list_attached_user_policies(user_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given user. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'UserName': user_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedUserPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_user_policies_response', {}).get('list_attached_user_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM user %s.', user_name) return [] def list_attached_group_policies(group_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given group. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'GroupName': group_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedGroupPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_group_policies_response', {}).get('list_attached_group_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM group %s.', group_name) return [] def list_attached_role_policies(role_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'RoleName': role_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedRolePolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_role_policies_response', {}).get('list_attached_role_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM role %s.', role_name) return [] def create_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Create SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.create_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_saml_provider(saml_metadata_document, name) log.info('Successfully created %s SAML provider.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to create SAML provider %s.', name) return False def get_saml_provider_arn(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider_arn my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_saml_providers() for saml_provider in response.list_saml_providers_response.list_saml_providers_result.saml_provider_list: if saml_provider['arn'].endswith(':saml-provider/' + name): return saml_provider['arn'] return False except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to get ARN of SAML provider %s.', name) return False def delete_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Delete SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.delete_saml_provider my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return True conn.delete_saml_provider(saml_provider_arn) log.info('Successfully deleted SAML provider %s.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete SAML provider %s.', name) return False def list_saml_providers(region=None, key=None, keyid=None, profile=None): ''' List SAML providers. CLI Example: .. code-block:: bash salt myminion boto_iam.list_saml_providers ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: providers = [] info = conn.list_saml_providers() for arn in info['list_saml_providers_response']['list_saml_providers_result']['saml_provider_list']: providers.append(arn['arn'].rsplit('/', 1)[1]) return providers except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get list of SAML providers.') return False def get_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider document. CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider arn ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: provider = conn.get_saml_provider(name) return provider['get_saml_provider_response']['get_saml_provider_result']['saml_metadata_document'] except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get SAML provider document %s.', name) return False def update_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Update SAML provider. CLI Example: .. code-block:: bash salt myminion boto_iam.update_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return False if conn.update_saml_provider(name, saml_metadata_document): return True return False except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to update SAML provider %s.', name) return False
saltstack/salt
salt/modules/boto_iam.py
export_users
python
def export_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM user details. Produces results that can be used to create an sls file. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.export_users --out=txt | sed "s/local: //" > iam_users.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() users = get_all_users(path_prefix, region, key, keyid, profile) for user in users: name = user.user_name _policies = conn.get_all_user_policies(name, max_items=100) _policies = _policies.list_user_policies_response.list_user_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_user_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_user_policy_response.get_user_policy_result.policy_document )) policies[policy_name] = _policy user_sls = [] user_sls.append({"name": name}) user_sls.append({"policies": policies}) user_sls.append({"path": user.path}) results["manage user " + name] = {"boto_iam.user_present": user_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2)
Get all IAM user details. Produces results that can be used to create an sls file. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.export_users --out=txt | sed "s/local: //" > iam_users.sls
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iam.py#L1620-L1656
[ "def loads(s, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.loads and prevents a traceback in the event that a bytestring is\n passed to the function. (Python < 3.6 cannot load bytestrings)\n\n You can pass an alternate json module (loaded via import_json() above)\n using the _json_module argument)\n '''\n json_module = kwargs.pop('_json_module', json)\n try:\n return json_module.loads(s, **kwargs)\n except TypeError as exc:\n # json.loads cannot load bytestrings in Python < 3.6\n if six.PY3 and isinstance(s, bytes):\n return json_module.loads(salt.utils.stringutils.to_unicode(s), **kwargs)\n else:\n raise exc\n", "def get_all_users(path_prefix='/', region=None, key=None, keyid=None,\n profile=None):\n '''\n Get and return all IAM user details, starting at the optional path.\n\n .. versionadded:: 2016.3.0\n\n CLI Example:\n\n salt-call boto_iam.get_all_users\n '''\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n if not conn:\n return None\n _users = conn.get_all_users(path_prefix=path_prefix)\n users = _users.list_users_response.list_users_result.users\n marker = getattr(\n _users.list_users_response.list_users_result, 'marker', None\n )\n while marker:\n _users = conn.get_all_users(path_prefix=path_prefix, marker=marker)\n users = users + _users.list_users_response.list_users_result.users\n marker = getattr(\n _users.list_users_response.list_users_result, 'marker', None\n )\n return users\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon IAM .. versionadded:: 2014.7.0 :configuration: This module accepts explicit iam 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 iam.keyid: GKTADJGHEIQSXMKKRBJ08H iam.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs iam.region: 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: boto ''' # keep lint from choking on _get_conn and _cache_id #pylint: disable=E0602 # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import salt libs from salt.ext import six import salt.utils.compat import salt.utils.json import salt.utils.odict as odict import salt.utils.versions from salt.exceptions import SaltInvocationError # Import third party libs # pylint: disable=unused-import from salt.ext.six.moves.urllib.parse import unquote as _unquote # pylint: disable=no-name-in-module try: import boto import boto.iam import boto3 import botocore logging.getLogger('boto').setLevel(logging.CRITICAL) logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=unused-import log = logging.getLogger(__name__) def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'iam', pack=__salt__) def instance_profile_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an instance profile exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: # Boto weirdly returns an exception here if an instance profile doesn't # exist. conn.get_instance_profile(name) return True except boto.exception.BotoServerError: return False def create_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Create an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.create_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if instance_profile_exists(name, region, key, keyid, profile): return True try: # This call returns an instance profile if successful and an exception # if not. It's annoying. conn.create_instance_profile(name) log.info('Created %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create %s instance profile.', name) return False return True def delete_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Delete an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not instance_profile_exists(name, region, key, keyid, profile): return True try: conn.delete_instance_profile(name) log.info('Deleted %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s instance profile.', name) return False return True def role_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an IAM role exists. CLI Example: .. code-block:: bash salt myminion boto_iam.role_exists myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_role(name) return True except boto.exception.BotoServerError: return False def describe_role(name, region=None, key=None, keyid=None, profile=None): ''' Get information for a role. CLI Example: .. code-block:: bash salt myminion boto_iam.describe_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_role(name) if not info: return False role = info.get_role_response.get_role_result.role role['assume_role_policy_document'] = salt.utils.json.loads(_unquote( role.assume_role_policy_document )) # If Sid wasn't defined by the user, boto will still return a Sid in # each policy. To properly check idempotently, let's remove the Sid # from the return if it's not actually set. for policy_key, policy in role['assume_role_policy_document'].items(): if policy_key == 'Statement': for val in policy: if 'Sid' in val and not val['Sid']: del val['Sid'] return role except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get %s information.', name) return False def create_user(user_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_user myuser ''' if not path: path = '/' if get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_user(user_name, path) log.info('Created IAM user : %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM user %s.', user_name) return False def get_all_access_keys(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all access keys from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_access_keys myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.get_all_access_keys(user_name, marker, max_items) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get access keys for IAM user %s.', user_name) return six.text_type(e) def create_access_key(user_name, region=None, key=None, keyid=None, profile=None): ''' Create access key id for a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.create_access_key(user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create access key.') return six.text_type(e) def delete_access_key(access_key_id, user_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete access key id from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_access_key(access_key_id, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete access key id %s.', access_key_id) return six.text_type(e) def delete_user(user_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user myuser ''' if not get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.delete_user(user_name) log.info('Deleted IAM user : %s .', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM user %s', user_name) return six.text_type(e) def get_user(user_name=None, region=None, key=None, keyid=None, profile=None): ''' Get user information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user(user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM user %s info.', user_name) return False def create_group(group_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_group group ''' if not path: path = '/' if get_group(group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_group(group_name, path) log.info('Created IAM group : %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM group %s.', group_name) return False def get_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group(group_name, max_items=1) if not info: return False return info['get_group_response']['get_group_result']['group'] except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_group_members(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: marker = None truncated = True users = [] while truncated: info = conn.get_group(group_name, marker=marker, max_items=1000) if not info: return False truncated = bool(info['get_group_response']['get_group_result']['is_truncated']) if truncated and 'marker' in info['get_group_response']['get_group_result']: marker = info['get_group_response']['get_group_result']['marker'] else: marker = None truncated = False users += info['get_group_response']['get_group_result']['users'] return users except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get members for IAM group %s.', group_name) return False def add_user_to_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Add user to group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.add_user_to_group myuser mygroup ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('Username : %s does not exist.', user_name) return False if user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.add_user_to_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add IAM user %s to group %s.', user_name, group_name) return False def user_exists_in_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Check if user exists in group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.user_exists_in_group myuser mygroup ''' # TODO this should probably use boto.iam.get_groups_for_user users = get_group_members( group_name=group_name, region=region, key=key, keyid=keyid, profile=profile ) if users: for _user in users: if user_name == _user['user_name']: log.debug('IAM user %s is already in IAM group %s.', user_name, group_name) return True return False def remove_user_from_group(group_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Remove user from group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.remove_user_from_group mygroup myuser ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist.', user_name) return False if not user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.remove_user_from_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove IAM user %s from group %s', user_name, group_name) return False def put_group_policy(group_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_group_policy mygroup policyname policyrules ''' group = get_group(group_name, region=region, key=key, keyid=keyid, profile=profile) if not group: log.error('Group %s does not exist', group_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_group_policy(group_name, policy_name, policy_json) if created: log.info('Created policy for IAM group %s.', group_name) return True log.error('Could not create policy for IAM group %s', group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy for IAM group %s', group_name) return False def delete_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group_policy mygroup mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_group_policy( group_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_group_policy(group_name, policy_name) log.info('Successfully deleted policy %s for IAM group %s.', policy_name, group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM group %s.', policy_name, group_name) return False def get_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group_policy mygroup policyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group_policy(group_name, policy_name) log.debug('info for group policy is : %s', info) if not info: return False info = info.get_group_policy_response.get_group_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_all_groups(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM group details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_groups ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _groups = conn.get_all_groups(path_prefix=path_prefix) groups = _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) while marker: _groups = conn.get_all_groups(path_prefix=path_prefix, marker=marker) groups = groups + _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) return groups def get_all_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.get_all_instance_profiles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) marker = False profiles = [] while marker is not None: marker = marker if marker else None p = conn.list_instance_profiles(path_prefix=path_prefix, marker=marker) res = p.list_instance_profiles_response.list_instance_profiles_result profiles += res.instance_profiles marker = getattr(res, 'marker', None) return profiles def list_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' List all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.list_instance_profiles ''' p = get_all_instance_profiles(path_prefix, region, key, keyid, profile) return [i['instance_profile_name'] for i in p] def get_all_group_policies(group_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a group. CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_group_policies mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False try: response = conn.get_all_group_policies(group_name) _list = response.list_group_policies_response.list_group_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def delete_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _group = get_group( group_name, region, key, keyid, profile ) if not _group: return True try: conn.delete_group(group_name) log.info('Successfully deleted IAM group %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM group %s.', group_name) return False def create_login_profile(user_name, password, region=None, key=None, keyid=None, profile=None): ''' Creates a login profile for the specified user, give the user the ability to access AWS services and the AWS Management Console. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_login_profile user_name password ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.create_login_profile(user_name, password) log.info('Created profile for IAM user %s.', user_name) return info except boto.exception.BotoServerError as e: log.debug(e) if 'Conflict' in e: log.info('Profile already exists for IAM user %s.', user_name) return 'Conflict' log.error('Failed to update profile for IAM user %s.', user_name) return False def delete_login_profile(user_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a login profile for the specified user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_login_profile user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.delete_login_profile(user_name) log.info('Deleted login profile for IAM user %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Login profile already deleted for IAM user %s.', user_name) return True log.error('Failed to delete login profile for IAM user %s.', user_name) return False def get_all_mfa_devices(user_name, region=None, key=None, keyid=None, profile=None): ''' Get all MFA devices associated with an IAM user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_mfa_devices user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: result = conn.get_all_mfa_devices(user_name) devices = result['list_mfa_devices_response']['list_mfa_devices_result']['mfa_devices'] return devices except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Could not find IAM user %s.', user_name) return [] log.error('Failed to get all MFA devices for IAM user %s.', user_name) return False def deactivate_mfa_device(user_name, serial, region=None, key=None, keyid=None, profile=None): ''' Deactivates the specified MFA device and removes it from association with the user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.deactivate_mfa_device user_name serial_num ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.deactivate_mfa_device(user_name, serial) log.info('Deactivated MFA device %s for IAM user %s.', serial, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('MFA device %s not associated with IAM user %s.', serial, user_name) return True log.error('Failed to deactivate MFA device %s for IAM user %s.', serial, user_name) return False def delete_virtual_mfa_device(serial, region=None, key=None, keyid=None, profile=None): ''' Deletes the specified virtual MFA device. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_virtual_mfa_device serial_num ''' conn = __utils__['boto3.get_connection_func']('iam')() try: conn.delete_virtual_mfa_device(SerialNumber=serial) log.info('Deleted virtual MFA device %s.', serial) return True except botocore.exceptions.ClientError as e: log.debug(e) if 'NoSuchEntity' in six.text_type(e): log.info('Virtual MFA device %s not found.', serial) return True log.error('Failed to delete virtual MFA device %s.', serial) return False def update_account_password_policy(allow_users_to_change_password=None, hard_expiry=None, max_password_age=None, minimum_password_length=None, password_reuse_prevention=None, require_lowercase_characters=None, require_numbers=None, require_symbols=None, require_uppercase_characters=None, region=None, key=None, keyid=None, profile=None): ''' Update the password policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_account_password_policy True ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.update_account_password_policy(allow_users_to_change_password, hard_expiry, max_password_age, minimum_password_length, password_reuse_prevention, require_lowercase_characters, require_numbers, require_symbols, require_uppercase_characters) log.info('The password policy has been updated.') return True except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy' log.error(msg) return False def get_account_policy(region=None, key=None, keyid=None, profile=None): ''' Get account policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_account_password_policy() return info.get_account_password_policy_response.get_account_password_policy_result.password_policy except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy.' log.error(msg) return False def create_role(name, policy_document=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Create an instance role. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if role_exists(name, region, key, keyid, profile): return True if not policy_document: policy_document = None try: conn.create_role(name, assume_role_policy_document=policy_document, path=path) log.info('Created IAM role %s.', name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to create IAM role %s.', name) return False def delete_role(name, region=None, key=None, keyid=None, profile=None): ''' Delete an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(name, region, key, keyid, profile): return True try: conn.delete_role(name) log.info('Deleted %s IAM role.', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s IAM role.', name) return False def profile_associated(role_name, profile_name, region, key, keyid, profile): ''' Check to see if an instance profile is associated with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.profile_associated myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # The IAM module of boto doesn't return objects. Instead you need to grab # values through its properties. Sigh. try: profiles = conn.list_instance_profiles_for_role(role_name) except boto.exception.BotoServerError as e: log.debug(e) return False profiles = profiles.list_instance_profiles_for_role_response profiles = profiles.list_instance_profiles_for_role_result profiles = profiles.instance_profiles for profile in profiles: if profile.instance_profile_name == profile_name: return True return False def associate_profile_to_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Associate an instance profile with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.associate_profile_to_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if associated: return True else: try: conn.add_role_to_instance_profile(profile_name, role_name) log.info('Added %s instance profile to IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add %s instance profile to IAM role %s', profile_name, role_name) return False def disassociate_profile_from_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Disassociate an instance profile from an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.disassociate_profile_from_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if not associated: return True else: try: conn.remove_role_from_instance_profile(profile_name, role_name) log.info('Removed %s instance profile from IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove %s instance profile from IAM role %s.', profile_name, role_name) return False def list_role_policies(role_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_role_policies myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_role_policies(role_name) _list = response.list_role_policies_response.list_role_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def get_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.get_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: _policy = conn.get_role_policy(role_name, policy_name) # I _hate_ you for not giving me an object boto. _policy = _policy.get_role_policy_response.policy_document # Policy is url encoded _policy = _unquote(_policy) _policy = salt.utils.json.loads(_policy, object_pairs_hook=odict.OrderedDict) return _policy except boto.exception.BotoServerError: return {} def create_role_policy(role_name, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Create or modify a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role_policy myirole mypolicy '{"MyPolicy": "Statement": [{"Action": ["sqs:*"], "Effect": "Allow", "Resource": ["arn:aws:sqs:*:*:*"], "Sid": "MyPolicySqs1"}]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) mode = 'create' if _policy: if _policy == policy: return True mode = 'modify' if isinstance(policy, six.string_types): policy = salt.utils.json.loads(policy, object_pairs_hook=odict.OrderedDict) try: _policy = salt.utils.json.dumps(policy) conn.put_role_policy(role_name, policy_name, _policy) if mode == 'create': msg = 'Successfully added policy %s to IAM role %s.' else: msg = 'Successfully modified policy %s for IAM role %s.' log.info(msg, policy_name, role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to %s policy %s for IAM role %s.', mode, policy_name, role_name) return False def delete_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) if not _policy: return True try: conn.delete_role_policy(role_name, policy_name) log.info('Successfully deleted policy %s for IAM role %s.', policy_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM role %s.', policy_name, role_name) return False def update_assume_role_policy(role_name, policy_document, region=None, key=None, keyid=None, profile=None): ''' Update an assume role policy for a role. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_assume_role_policy myrole '{"Statement":"..."}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(policy_document, six.string_types): policy_document = salt.utils.json.loads(policy_document, object_pairs_hook=odict.OrderedDict) try: _policy_document = salt.utils.json.dumps(policy_document) conn.update_assume_role_policy(role_name, _policy_document) log.info('Successfully updated assume role policy for IAM role %s.', role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to update assume role policy for IAM role %s.', role_name) return False def build_policy(region=None, key=None, keyid=None, profile=None): ''' Build a default assume role policy. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.build_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if hasattr(conn, 'build_policy'): policy = salt.utils.json.loads(conn.build_policy()) elif hasattr(conn, '_build_policy'): policy = salt.utils.json.loads(conn._build_policy()) else: return {} # The format we get from build_policy isn't going to be what we get back # from AWS for the exact same policy. AWS converts single item list values # into strings, so let's do the same here. for key, policy_val in policy.items(): for statement in policy_val: if (isinstance(statement['Action'], list) and len(statement['Action']) == 1): statement['Action'] = statement['Action'][0] if (isinstance(statement['Principal']['Service'], list) and len(statement['Principal']['Service']) == 1): statement['Principal']['Service'] = statement['Principal']['Service'][0] # build_policy doesn't add a version field, which AWS is going to set to a # default value, when we get it back, so let's set it. policy['Version'] = '2008-10-17' return policy def get_account_id(region=None, key=None, keyid=None, profile=None): ''' Get a the AWS account id associated with the used credentials. CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_id ''' cache_key = 'boto_iam.account_id' if cache_key not in __context__: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_user() # The get_user call returns an user ARN: # arn:aws:iam::027050522557:user/salt-test arn = ret['get_user_response']['get_user_result']['user']['arn'] account_id = arn.split(':')[4] except boto.exception.BotoServerError: # If call failed, then let's try to get the ARN from the metadata timeout = boto.config.getfloat( 'Boto', 'metadata_service_timeout', 1.0 ) attempts = boto.config.getint( 'Boto', 'metadata_service_num_attempts', 1 ) identity = boto.utils.get_instance_identity( timeout=timeout, num_retries=attempts ) try: account_id = identity['document']['accountId'] except KeyError: log.error('Failed to get account id from instance_identity in' ' boto_iam.get_account_id.') __context__[cache_key] = account_id return __context__[cache_key] def get_all_roles(path_prefix=None, region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM role details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_roles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _roles = conn.list_roles(path_prefix=path_prefix) roles = _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) while marker: _roles = conn.list_roles(path_prefix=path_prefix, marker=marker) roles = roles + _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) return roles def get_all_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM user details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_users ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _users = conn.get_all_users(path_prefix=path_prefix) users = _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) while marker: _users = conn.get_all_users(path_prefix=path_prefix, marker=marker) users = users + _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) return users def get_all_user_policies(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all user policies. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_user_policies myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_all_user_policies(user_name, marker, max_items) if not info: return False _list = info.list_user_policies_response.list_user_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policies for user %s.', user_name) return False def get_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user_policy myuser mypolicyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user_policy(user_name, policy_name) log.debug('Info for IAM user %s policy %s: %s.', user_name, policy_name, info) if not info: return False info = info.get_user_policy_response.get_user_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policy %s for IAM user %s.', policy_name, user_name) return False def put_user_policy(user_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_user_policy myuser policyname policyrules ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_user_policy(user_name, policy_name, policy_json) if created: log.info('Created policy %s for IAM user %s.', policy_name, user_name) return True log.error('Could not create policy %s for IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy %s for IAM user %s.', policy_name, user_name) return False def delete_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user_policy myuser mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_user_policy( user_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_user_policy(user_name, policy_name) log.info('Successfully deleted policy %s for IAM user %s.', policy_name, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM user %s.', policy_name, user_name) return False def upload_server_cert(cert_name, cert_body, private_key, cert_chain=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Upload a certificate to Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.upload_server_cert mycert_name crt priv_key :param cert_name: The name for the server certificate. Do not include the path in this value. :param cert_body: The contents of the public key certificate in PEM-encoded format. :param private_key: The contents of the private key in PEM-encoded format. :param cert_chain: The contents of the certificate chain. This is typically a concatenation of the PEM-encoded public key certificates of the chain. :param path: The path for the server certificate. :param region: The name of the region to connect to. :param key: The key to be used in order to connect :param keyid: The keyid to be used in order to connect :param profile: The profile that contains a dict of region, key, keyid :return: True / False ''' exists = get_server_certificate(cert_name, region, key, keyid, profile) if exists: return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.upload_server_cert(cert_name, cert_body, private_key, cert_chain) log.info('Created certificate %s.', cert_name) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to failed to create certificate %s.', cert_name) return False def list_server_certificates(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Lists the server certificates stored in IAM that have the specified path prefix. .. versionadded:: ??? :param path_prefix: The path prefix for filtering the results. For example: /company/servercerts would get all server certificates for which the path starts with /company/servercerts . This parameter is optional. If it is not included, it defaults to a slash (/), listing all server certificates. This parameter allows (per its regex pattern) a string of characters consisting of either a forward slash (/) by itself or a string that must begin and end with forward slashes. In addition, it can contain any ASCII character from the ! (u0021) through the DEL character (u007F), including most punctuation characters, digits, and upper and lowercased letters. CLI Example: .. code-block:: bash salt myminion boto_iam.list_server_certificates path_prefix=/somepath/ ''' retries = 10 sleep = 6 conn = __utils__['boto3.get_connection']('iam', region=region, key=key, keyid=keyid, profile=profile) Items = [] while retries: try: log.debug('Garnering list of IAM Server Certificates') IsTruncated = True while IsTruncated: kwargs = {'PathPrefix': path_prefix} ret = conn.list_server_certificates(**kwargs) Items += ret.get('ServerCertificateMetadataList', []) IsTruncated = ret.get('IsTruncated') kwargs.update({'Marker': ret.get('Marker')}) return Items except botocore.exceptions.ParamValidationError as err: raise SaltInvocationError(str(err)) except botocore.exceptions.ClientError as err: if retries and jmespath.search('Error.Code', err.response) == 'Throttling': retries -= 1 log.debug('Throttled by AWS API, retrying in %s seconds...', sleep) time.sleep(sleep) continue log.error('Failed to list IAM Server Certificates: %s', err.message) return None def get_server_certificate(cert_name, region=None, key=None, keyid=None, profile=None): ''' Returns certificate information from Amazon .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_server_certificate mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_server_certificate(cert_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get certificate %s information.', cert_name) return False def delete_server_cert(cert_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a certificate from Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_server_cert mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_server_cert(cert_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete certificate %s.', cert_name) return False def export_roles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM role details. Produces results that can be used to create an sls file. CLI Example: salt-call boto_iam.export_roles --out=txt | sed "s/local: //" > iam_roles.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() roles = get_all_roles(path_prefix, region, key, keyid, profile) for role in roles: name = role.role_name _policies = conn.list_role_policies(name, max_items=100) _policies = _policies.list_role_policies_response.list_role_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_role_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_role_policy_response.get_role_policy_result.policy_document )) policies[policy_name] = _policy role_sls = [] role_sls.append({"name": name}) role_sls.append({"policies": policies}) role_sls.append({'policy_document': salt.utils.json.loads(_unquote(role.assume_role_policy_document))}) role_sls.append({"path": role.path}) results["manage role " + name] = {"boto_iam_role.present": role_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def _get_policy_arn(name, region=None, key=None, keyid=None, profile=None): if name.startswith('arn:aws:iam:'): return name account_id = get_account_id( region=region, key=key, keyid=keyid, profile=profile ) return 'arn:aws:iam::{0}:policy/{1}'.format(account_id, name) def policy_exists(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return True except boto.exception.BotoServerError: return False def get_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return ret.get('get_policy_response', {}).get('get_policy_result', {}) except boto.exception.BotoServerError: return None def create_policy(policy_name, policy_document, path=None, description=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in 'path', 'description': if locals()[arg] is not None: params[arg] = locals()[arg] if policy_exists(policy_name, region, key, keyid, profile): return True try: conn.create_policy(policy_name, policy_document, **params) log.info('Created IAM policy %s.', policy_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s.', policy_name) return False return True def delete_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_exists(policy_arn, region, key, keyid, profile): return True try: conn.delete_policy(policy_arn) log.info('Deleted %s policy.', policy_name) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete %s policy: %s.', policy_name, aws.get('message')) return False return True def list_policies(region=None, key=None, keyid=None, profile=None): ''' List policies. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policies ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: policies = [] for ret in __utils__['boto.paged_call'](conn.list_policies): policies.append(ret.get('list_policies_response', {}).get('list_policies_result', {}).get('policies')) return policies except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to list policy versions.' log.error(msg) return [] def policy_version_exists(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.get_policy_version(policy_arn, version_id) return True except boto.exception.BotoServerError: return False def get_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy_version(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile), version_id) retval = ret.get('get_policy_version_response', {}).get('get_policy_version_result', {}).get('policy_version', {}) retval['document'] = _unquote(retval.get('document')) return {'policy_version': retval} except boto.exception.BotoServerError: return None def create_policy_version(policy_name, policy_document, set_as_default=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy version. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy_version mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in ('set_as_default',): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.create_policy_version(policy_arn, policy_document, **params) vid = ret.get('create_policy_version_response', {}).get('create_policy_version_result', {}).get('policy_version', {}).get('version_id') log.info('Created IAM policy %s version %s.', policy_name, vid) return {'created': True, 'version_id': vid} except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s version %s.', policy_name, vid) return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Delete a policy version. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_version_exists(policy_arn, version_id, region, key, keyid, profile): return True try: conn.delete_policy_version(policy_arn, version_id) log.info('Deleted IAM policy %s version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete IAM policy %s version %s: %s', policy_name, version_id, aws.get('message')) return False return True def list_policy_versions(policy_name, region=None, key=None, keyid=None, profile=None): ''' List versions of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policy_versions mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.list_policy_versions(policy_arn) return ret.get('list_policy_versions_response', {}).get('list_policy_versions_result', {}).get('versions') except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list versions for IAM policy %s.', policy_name) return [] def set_default_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Set the default version of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.set_default_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.set_default_policy_version(policy_arn, version_id) log.info('Set %s policy to version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to set %s policy to version %s: %s', policy_name, version_id, aws.get('message')) return False return True def attach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_user_policy(policy_arn, user_name) log.info('Attached policy %s to IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach %s policy to IAM user %s.', policy_name, user_name) return False return True def detach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_user_policy(policy_arn, user_name) log.info('Detached %s policy from IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach %s policy from IAM user %s.', policy_name, user_name) return False return True def attach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_group_policy(policy_arn, group_name) log.info('Attached policy %s to IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM group %s.', policy_name, group_name) return False return True def detach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_group_policy(policy_arn, group_name) log.info('Detached policy %s from IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM group %s.', policy_name, group_name) return False return True def attach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_role_policy(policy_arn, role_name) log.info('Attached policy %s to IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM role %s.', policy_name, role_name) return False return True def detach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_role_policy(policy_arn, role_name) log.info('Detached policy %s from IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM role %s.', policy_name, role_name) return False return True def list_entities_for_policy(policy_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities that a policy is attached to. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 params = {} for arg in ('path_prefix', 'entity_filter'): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) while retries: try: allret = { 'policy_groups': [], 'policy_users': [], 'policy_roles': [], } for ret in __utils__['boto.paged_call'](conn.list_entities_for_policy, policy_arn=policy_arn, **params): for k, v in six.iteritems(allret): v.extend(ret.get('list_entities_for_policy_response', {}).get('list_entities_for_policy_result', {}).get(k)) return allret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('Failed to list entities for IAM policy %s: %s', policy_name, e.message) return {} return {} def list_attached_user_policies(user_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given user. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'UserName': user_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedUserPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_user_policies_response', {}).get('list_attached_user_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM user %s.', user_name) return [] def list_attached_group_policies(group_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given group. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'GroupName': group_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedGroupPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_group_policies_response', {}).get('list_attached_group_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM group %s.', group_name) return [] def list_attached_role_policies(role_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'RoleName': role_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedRolePolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_role_policies_response', {}).get('list_attached_role_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM role %s.', role_name) return [] def create_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Create SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.create_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_saml_provider(saml_metadata_document, name) log.info('Successfully created %s SAML provider.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to create SAML provider %s.', name) return False def get_saml_provider_arn(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider_arn my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_saml_providers() for saml_provider in response.list_saml_providers_response.list_saml_providers_result.saml_provider_list: if saml_provider['arn'].endswith(':saml-provider/' + name): return saml_provider['arn'] return False except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to get ARN of SAML provider %s.', name) return False def delete_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Delete SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.delete_saml_provider my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return True conn.delete_saml_provider(saml_provider_arn) log.info('Successfully deleted SAML provider %s.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete SAML provider %s.', name) return False def list_saml_providers(region=None, key=None, keyid=None, profile=None): ''' List SAML providers. CLI Example: .. code-block:: bash salt myminion boto_iam.list_saml_providers ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: providers = [] info = conn.list_saml_providers() for arn in info['list_saml_providers_response']['list_saml_providers_result']['saml_provider_list']: providers.append(arn['arn'].rsplit('/', 1)[1]) return providers except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get list of SAML providers.') return False def get_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider document. CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider arn ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: provider = conn.get_saml_provider(name) return provider['get_saml_provider_response']['get_saml_provider_result']['saml_metadata_document'] except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get SAML provider document %s.', name) return False def update_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Update SAML provider. CLI Example: .. code-block:: bash salt myminion boto_iam.update_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return False if conn.update_saml_provider(name, saml_metadata_document): return True return False except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to update SAML provider %s.', name) return False
saltstack/salt
salt/modules/boto_iam.py
export_roles
python
def export_roles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM role details. Produces results that can be used to create an sls file. CLI Example: salt-call boto_iam.export_roles --out=txt | sed "s/local: //" > iam_roles.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() roles = get_all_roles(path_prefix, region, key, keyid, profile) for role in roles: name = role.role_name _policies = conn.list_role_policies(name, max_items=100) _policies = _policies.list_role_policies_response.list_role_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_role_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_role_policy_response.get_role_policy_result.policy_document )) policies[policy_name] = _policy role_sls = [] role_sls.append({"name": name}) role_sls.append({"policies": policies}) role_sls.append({'policy_document': salt.utils.json.loads(_unquote(role.assume_role_policy_document))}) role_sls.append({"path": role.path}) results["manage role " + name] = {"boto_iam_role.present": role_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2)
Get all IAM role details. Produces results that can be used to create an sls file. CLI Example: salt-call boto_iam.export_roles --out=txt | sed "s/local: //" > iam_roles.sls
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iam.py#L1659-L1693
[ "def loads(s, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.loads and prevents a traceback in the event that a bytestring is\n passed to the function. (Python < 3.6 cannot load bytestrings)\n\n You can pass an alternate json module (loaded via import_json() above)\n using the _json_module argument)\n '''\n json_module = kwargs.pop('_json_module', json)\n try:\n return json_module.loads(s, **kwargs)\n except TypeError as exc:\n # json.loads cannot load bytestrings in Python < 3.6\n if six.PY3 and isinstance(s, bytes):\n return json_module.loads(salt.utils.stringutils.to_unicode(s), **kwargs)\n else:\n raise exc\n", "def get_all_roles(path_prefix=None, region=None, key=None, keyid=None,\n profile=None):\n '''\n Get and return all IAM role details, starting at the optional path.\n\n .. versionadded:: 2016.3.0\n\n CLI Example:\n\n salt-call boto_iam.get_all_roles\n '''\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n if not conn:\n return None\n _roles = conn.list_roles(path_prefix=path_prefix)\n roles = _roles.list_roles_response.list_roles_result.roles\n marker = getattr(\n _roles.list_roles_response.list_roles_result, 'marker', None\n )\n while marker:\n _roles = conn.list_roles(path_prefix=path_prefix, marker=marker)\n roles = roles + _roles.list_roles_response.list_roles_result.roles\n marker = getattr(\n _roles.list_roles_response.list_roles_result, 'marker', None\n )\n return roles\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon IAM .. versionadded:: 2014.7.0 :configuration: This module accepts explicit iam 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 iam.keyid: GKTADJGHEIQSXMKKRBJ08H iam.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs iam.region: 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: boto ''' # keep lint from choking on _get_conn and _cache_id #pylint: disable=E0602 # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import salt libs from salt.ext import six import salt.utils.compat import salt.utils.json import salt.utils.odict as odict import salt.utils.versions from salt.exceptions import SaltInvocationError # Import third party libs # pylint: disable=unused-import from salt.ext.six.moves.urllib.parse import unquote as _unquote # pylint: disable=no-name-in-module try: import boto import boto.iam import boto3 import botocore logging.getLogger('boto').setLevel(logging.CRITICAL) logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=unused-import log = logging.getLogger(__name__) def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'iam', pack=__salt__) def instance_profile_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an instance profile exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: # Boto weirdly returns an exception here if an instance profile doesn't # exist. conn.get_instance_profile(name) return True except boto.exception.BotoServerError: return False def create_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Create an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.create_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if instance_profile_exists(name, region, key, keyid, profile): return True try: # This call returns an instance profile if successful and an exception # if not. It's annoying. conn.create_instance_profile(name) log.info('Created %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create %s instance profile.', name) return False return True def delete_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Delete an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not instance_profile_exists(name, region, key, keyid, profile): return True try: conn.delete_instance_profile(name) log.info('Deleted %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s instance profile.', name) return False return True def role_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an IAM role exists. CLI Example: .. code-block:: bash salt myminion boto_iam.role_exists myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_role(name) return True except boto.exception.BotoServerError: return False def describe_role(name, region=None, key=None, keyid=None, profile=None): ''' Get information for a role. CLI Example: .. code-block:: bash salt myminion boto_iam.describe_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_role(name) if not info: return False role = info.get_role_response.get_role_result.role role['assume_role_policy_document'] = salt.utils.json.loads(_unquote( role.assume_role_policy_document )) # If Sid wasn't defined by the user, boto will still return a Sid in # each policy. To properly check idempotently, let's remove the Sid # from the return if it's not actually set. for policy_key, policy in role['assume_role_policy_document'].items(): if policy_key == 'Statement': for val in policy: if 'Sid' in val and not val['Sid']: del val['Sid'] return role except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get %s information.', name) return False def create_user(user_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_user myuser ''' if not path: path = '/' if get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_user(user_name, path) log.info('Created IAM user : %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM user %s.', user_name) return False def get_all_access_keys(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all access keys from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_access_keys myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.get_all_access_keys(user_name, marker, max_items) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get access keys for IAM user %s.', user_name) return six.text_type(e) def create_access_key(user_name, region=None, key=None, keyid=None, profile=None): ''' Create access key id for a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.create_access_key(user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create access key.') return six.text_type(e) def delete_access_key(access_key_id, user_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete access key id from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_access_key(access_key_id, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete access key id %s.', access_key_id) return six.text_type(e) def delete_user(user_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user myuser ''' if not get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.delete_user(user_name) log.info('Deleted IAM user : %s .', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM user %s', user_name) return six.text_type(e) def get_user(user_name=None, region=None, key=None, keyid=None, profile=None): ''' Get user information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user(user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM user %s info.', user_name) return False def create_group(group_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_group group ''' if not path: path = '/' if get_group(group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_group(group_name, path) log.info('Created IAM group : %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM group %s.', group_name) return False def get_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group(group_name, max_items=1) if not info: return False return info['get_group_response']['get_group_result']['group'] except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_group_members(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: marker = None truncated = True users = [] while truncated: info = conn.get_group(group_name, marker=marker, max_items=1000) if not info: return False truncated = bool(info['get_group_response']['get_group_result']['is_truncated']) if truncated and 'marker' in info['get_group_response']['get_group_result']: marker = info['get_group_response']['get_group_result']['marker'] else: marker = None truncated = False users += info['get_group_response']['get_group_result']['users'] return users except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get members for IAM group %s.', group_name) return False def add_user_to_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Add user to group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.add_user_to_group myuser mygroup ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('Username : %s does not exist.', user_name) return False if user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.add_user_to_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add IAM user %s to group %s.', user_name, group_name) return False def user_exists_in_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Check if user exists in group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.user_exists_in_group myuser mygroup ''' # TODO this should probably use boto.iam.get_groups_for_user users = get_group_members( group_name=group_name, region=region, key=key, keyid=keyid, profile=profile ) if users: for _user in users: if user_name == _user['user_name']: log.debug('IAM user %s is already in IAM group %s.', user_name, group_name) return True return False def remove_user_from_group(group_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Remove user from group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.remove_user_from_group mygroup myuser ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist.', user_name) return False if not user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.remove_user_from_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove IAM user %s from group %s', user_name, group_name) return False def put_group_policy(group_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_group_policy mygroup policyname policyrules ''' group = get_group(group_name, region=region, key=key, keyid=keyid, profile=profile) if not group: log.error('Group %s does not exist', group_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_group_policy(group_name, policy_name, policy_json) if created: log.info('Created policy for IAM group %s.', group_name) return True log.error('Could not create policy for IAM group %s', group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy for IAM group %s', group_name) return False def delete_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group_policy mygroup mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_group_policy( group_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_group_policy(group_name, policy_name) log.info('Successfully deleted policy %s for IAM group %s.', policy_name, group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM group %s.', policy_name, group_name) return False def get_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group_policy mygroup policyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group_policy(group_name, policy_name) log.debug('info for group policy is : %s', info) if not info: return False info = info.get_group_policy_response.get_group_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_all_groups(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM group details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_groups ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _groups = conn.get_all_groups(path_prefix=path_prefix) groups = _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) while marker: _groups = conn.get_all_groups(path_prefix=path_prefix, marker=marker) groups = groups + _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) return groups def get_all_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.get_all_instance_profiles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) marker = False profiles = [] while marker is not None: marker = marker if marker else None p = conn.list_instance_profiles(path_prefix=path_prefix, marker=marker) res = p.list_instance_profiles_response.list_instance_profiles_result profiles += res.instance_profiles marker = getattr(res, 'marker', None) return profiles def list_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' List all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.list_instance_profiles ''' p = get_all_instance_profiles(path_prefix, region, key, keyid, profile) return [i['instance_profile_name'] for i in p] def get_all_group_policies(group_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a group. CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_group_policies mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False try: response = conn.get_all_group_policies(group_name) _list = response.list_group_policies_response.list_group_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def delete_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _group = get_group( group_name, region, key, keyid, profile ) if not _group: return True try: conn.delete_group(group_name) log.info('Successfully deleted IAM group %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM group %s.', group_name) return False def create_login_profile(user_name, password, region=None, key=None, keyid=None, profile=None): ''' Creates a login profile for the specified user, give the user the ability to access AWS services and the AWS Management Console. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_login_profile user_name password ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.create_login_profile(user_name, password) log.info('Created profile for IAM user %s.', user_name) return info except boto.exception.BotoServerError as e: log.debug(e) if 'Conflict' in e: log.info('Profile already exists for IAM user %s.', user_name) return 'Conflict' log.error('Failed to update profile for IAM user %s.', user_name) return False def delete_login_profile(user_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a login profile for the specified user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_login_profile user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.delete_login_profile(user_name) log.info('Deleted login profile for IAM user %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Login profile already deleted for IAM user %s.', user_name) return True log.error('Failed to delete login profile for IAM user %s.', user_name) return False def get_all_mfa_devices(user_name, region=None, key=None, keyid=None, profile=None): ''' Get all MFA devices associated with an IAM user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_mfa_devices user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: result = conn.get_all_mfa_devices(user_name) devices = result['list_mfa_devices_response']['list_mfa_devices_result']['mfa_devices'] return devices except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Could not find IAM user %s.', user_name) return [] log.error('Failed to get all MFA devices for IAM user %s.', user_name) return False def deactivate_mfa_device(user_name, serial, region=None, key=None, keyid=None, profile=None): ''' Deactivates the specified MFA device and removes it from association with the user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.deactivate_mfa_device user_name serial_num ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.deactivate_mfa_device(user_name, serial) log.info('Deactivated MFA device %s for IAM user %s.', serial, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('MFA device %s not associated with IAM user %s.', serial, user_name) return True log.error('Failed to deactivate MFA device %s for IAM user %s.', serial, user_name) return False def delete_virtual_mfa_device(serial, region=None, key=None, keyid=None, profile=None): ''' Deletes the specified virtual MFA device. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_virtual_mfa_device serial_num ''' conn = __utils__['boto3.get_connection_func']('iam')() try: conn.delete_virtual_mfa_device(SerialNumber=serial) log.info('Deleted virtual MFA device %s.', serial) return True except botocore.exceptions.ClientError as e: log.debug(e) if 'NoSuchEntity' in six.text_type(e): log.info('Virtual MFA device %s not found.', serial) return True log.error('Failed to delete virtual MFA device %s.', serial) return False def update_account_password_policy(allow_users_to_change_password=None, hard_expiry=None, max_password_age=None, minimum_password_length=None, password_reuse_prevention=None, require_lowercase_characters=None, require_numbers=None, require_symbols=None, require_uppercase_characters=None, region=None, key=None, keyid=None, profile=None): ''' Update the password policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_account_password_policy True ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.update_account_password_policy(allow_users_to_change_password, hard_expiry, max_password_age, minimum_password_length, password_reuse_prevention, require_lowercase_characters, require_numbers, require_symbols, require_uppercase_characters) log.info('The password policy has been updated.') return True except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy' log.error(msg) return False def get_account_policy(region=None, key=None, keyid=None, profile=None): ''' Get account policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_account_password_policy() return info.get_account_password_policy_response.get_account_password_policy_result.password_policy except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy.' log.error(msg) return False def create_role(name, policy_document=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Create an instance role. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if role_exists(name, region, key, keyid, profile): return True if not policy_document: policy_document = None try: conn.create_role(name, assume_role_policy_document=policy_document, path=path) log.info('Created IAM role %s.', name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to create IAM role %s.', name) return False def delete_role(name, region=None, key=None, keyid=None, profile=None): ''' Delete an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(name, region, key, keyid, profile): return True try: conn.delete_role(name) log.info('Deleted %s IAM role.', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s IAM role.', name) return False def profile_associated(role_name, profile_name, region, key, keyid, profile): ''' Check to see if an instance profile is associated with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.profile_associated myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # The IAM module of boto doesn't return objects. Instead you need to grab # values through its properties. Sigh. try: profiles = conn.list_instance_profiles_for_role(role_name) except boto.exception.BotoServerError as e: log.debug(e) return False profiles = profiles.list_instance_profiles_for_role_response profiles = profiles.list_instance_profiles_for_role_result profiles = profiles.instance_profiles for profile in profiles: if profile.instance_profile_name == profile_name: return True return False def associate_profile_to_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Associate an instance profile with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.associate_profile_to_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if associated: return True else: try: conn.add_role_to_instance_profile(profile_name, role_name) log.info('Added %s instance profile to IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add %s instance profile to IAM role %s', profile_name, role_name) return False def disassociate_profile_from_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Disassociate an instance profile from an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.disassociate_profile_from_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if not associated: return True else: try: conn.remove_role_from_instance_profile(profile_name, role_name) log.info('Removed %s instance profile from IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove %s instance profile from IAM role %s.', profile_name, role_name) return False def list_role_policies(role_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_role_policies myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_role_policies(role_name) _list = response.list_role_policies_response.list_role_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def get_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.get_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: _policy = conn.get_role_policy(role_name, policy_name) # I _hate_ you for not giving me an object boto. _policy = _policy.get_role_policy_response.policy_document # Policy is url encoded _policy = _unquote(_policy) _policy = salt.utils.json.loads(_policy, object_pairs_hook=odict.OrderedDict) return _policy except boto.exception.BotoServerError: return {} def create_role_policy(role_name, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Create or modify a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role_policy myirole mypolicy '{"MyPolicy": "Statement": [{"Action": ["sqs:*"], "Effect": "Allow", "Resource": ["arn:aws:sqs:*:*:*"], "Sid": "MyPolicySqs1"}]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) mode = 'create' if _policy: if _policy == policy: return True mode = 'modify' if isinstance(policy, six.string_types): policy = salt.utils.json.loads(policy, object_pairs_hook=odict.OrderedDict) try: _policy = salt.utils.json.dumps(policy) conn.put_role_policy(role_name, policy_name, _policy) if mode == 'create': msg = 'Successfully added policy %s to IAM role %s.' else: msg = 'Successfully modified policy %s for IAM role %s.' log.info(msg, policy_name, role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to %s policy %s for IAM role %s.', mode, policy_name, role_name) return False def delete_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) if not _policy: return True try: conn.delete_role_policy(role_name, policy_name) log.info('Successfully deleted policy %s for IAM role %s.', policy_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM role %s.', policy_name, role_name) return False def update_assume_role_policy(role_name, policy_document, region=None, key=None, keyid=None, profile=None): ''' Update an assume role policy for a role. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_assume_role_policy myrole '{"Statement":"..."}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(policy_document, six.string_types): policy_document = salt.utils.json.loads(policy_document, object_pairs_hook=odict.OrderedDict) try: _policy_document = salt.utils.json.dumps(policy_document) conn.update_assume_role_policy(role_name, _policy_document) log.info('Successfully updated assume role policy for IAM role %s.', role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to update assume role policy for IAM role %s.', role_name) return False def build_policy(region=None, key=None, keyid=None, profile=None): ''' Build a default assume role policy. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.build_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if hasattr(conn, 'build_policy'): policy = salt.utils.json.loads(conn.build_policy()) elif hasattr(conn, '_build_policy'): policy = salt.utils.json.loads(conn._build_policy()) else: return {} # The format we get from build_policy isn't going to be what we get back # from AWS for the exact same policy. AWS converts single item list values # into strings, so let's do the same here. for key, policy_val in policy.items(): for statement in policy_val: if (isinstance(statement['Action'], list) and len(statement['Action']) == 1): statement['Action'] = statement['Action'][0] if (isinstance(statement['Principal']['Service'], list) and len(statement['Principal']['Service']) == 1): statement['Principal']['Service'] = statement['Principal']['Service'][0] # build_policy doesn't add a version field, which AWS is going to set to a # default value, when we get it back, so let's set it. policy['Version'] = '2008-10-17' return policy def get_account_id(region=None, key=None, keyid=None, profile=None): ''' Get a the AWS account id associated with the used credentials. CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_id ''' cache_key = 'boto_iam.account_id' if cache_key not in __context__: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_user() # The get_user call returns an user ARN: # arn:aws:iam::027050522557:user/salt-test arn = ret['get_user_response']['get_user_result']['user']['arn'] account_id = arn.split(':')[4] except boto.exception.BotoServerError: # If call failed, then let's try to get the ARN from the metadata timeout = boto.config.getfloat( 'Boto', 'metadata_service_timeout', 1.0 ) attempts = boto.config.getint( 'Boto', 'metadata_service_num_attempts', 1 ) identity = boto.utils.get_instance_identity( timeout=timeout, num_retries=attempts ) try: account_id = identity['document']['accountId'] except KeyError: log.error('Failed to get account id from instance_identity in' ' boto_iam.get_account_id.') __context__[cache_key] = account_id return __context__[cache_key] def get_all_roles(path_prefix=None, region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM role details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_roles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _roles = conn.list_roles(path_prefix=path_prefix) roles = _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) while marker: _roles = conn.list_roles(path_prefix=path_prefix, marker=marker) roles = roles + _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) return roles def get_all_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM user details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_users ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _users = conn.get_all_users(path_prefix=path_prefix) users = _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) while marker: _users = conn.get_all_users(path_prefix=path_prefix, marker=marker) users = users + _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) return users def get_all_user_policies(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all user policies. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_user_policies myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_all_user_policies(user_name, marker, max_items) if not info: return False _list = info.list_user_policies_response.list_user_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policies for user %s.', user_name) return False def get_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user_policy myuser mypolicyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user_policy(user_name, policy_name) log.debug('Info for IAM user %s policy %s: %s.', user_name, policy_name, info) if not info: return False info = info.get_user_policy_response.get_user_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policy %s for IAM user %s.', policy_name, user_name) return False def put_user_policy(user_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_user_policy myuser policyname policyrules ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_user_policy(user_name, policy_name, policy_json) if created: log.info('Created policy %s for IAM user %s.', policy_name, user_name) return True log.error('Could not create policy %s for IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy %s for IAM user %s.', policy_name, user_name) return False def delete_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user_policy myuser mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_user_policy( user_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_user_policy(user_name, policy_name) log.info('Successfully deleted policy %s for IAM user %s.', policy_name, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM user %s.', policy_name, user_name) return False def upload_server_cert(cert_name, cert_body, private_key, cert_chain=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Upload a certificate to Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.upload_server_cert mycert_name crt priv_key :param cert_name: The name for the server certificate. Do not include the path in this value. :param cert_body: The contents of the public key certificate in PEM-encoded format. :param private_key: The contents of the private key in PEM-encoded format. :param cert_chain: The contents of the certificate chain. This is typically a concatenation of the PEM-encoded public key certificates of the chain. :param path: The path for the server certificate. :param region: The name of the region to connect to. :param key: The key to be used in order to connect :param keyid: The keyid to be used in order to connect :param profile: The profile that contains a dict of region, key, keyid :return: True / False ''' exists = get_server_certificate(cert_name, region, key, keyid, profile) if exists: return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.upload_server_cert(cert_name, cert_body, private_key, cert_chain) log.info('Created certificate %s.', cert_name) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to failed to create certificate %s.', cert_name) return False def list_server_certificates(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Lists the server certificates stored in IAM that have the specified path prefix. .. versionadded:: ??? :param path_prefix: The path prefix for filtering the results. For example: /company/servercerts would get all server certificates for which the path starts with /company/servercerts . This parameter is optional. If it is not included, it defaults to a slash (/), listing all server certificates. This parameter allows (per its regex pattern) a string of characters consisting of either a forward slash (/) by itself or a string that must begin and end with forward slashes. In addition, it can contain any ASCII character from the ! (u0021) through the DEL character (u007F), including most punctuation characters, digits, and upper and lowercased letters. CLI Example: .. code-block:: bash salt myminion boto_iam.list_server_certificates path_prefix=/somepath/ ''' retries = 10 sleep = 6 conn = __utils__['boto3.get_connection']('iam', region=region, key=key, keyid=keyid, profile=profile) Items = [] while retries: try: log.debug('Garnering list of IAM Server Certificates') IsTruncated = True while IsTruncated: kwargs = {'PathPrefix': path_prefix} ret = conn.list_server_certificates(**kwargs) Items += ret.get('ServerCertificateMetadataList', []) IsTruncated = ret.get('IsTruncated') kwargs.update({'Marker': ret.get('Marker')}) return Items except botocore.exceptions.ParamValidationError as err: raise SaltInvocationError(str(err)) except botocore.exceptions.ClientError as err: if retries and jmespath.search('Error.Code', err.response) == 'Throttling': retries -= 1 log.debug('Throttled by AWS API, retrying in %s seconds...', sleep) time.sleep(sleep) continue log.error('Failed to list IAM Server Certificates: %s', err.message) return None def get_server_certificate(cert_name, region=None, key=None, keyid=None, profile=None): ''' Returns certificate information from Amazon .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_server_certificate mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_server_certificate(cert_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get certificate %s information.', cert_name) return False def delete_server_cert(cert_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a certificate from Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_server_cert mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_server_cert(cert_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete certificate %s.', cert_name) return False def export_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM user details. Produces results that can be used to create an sls file. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.export_users --out=txt | sed "s/local: //" > iam_users.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() users = get_all_users(path_prefix, region, key, keyid, profile) for user in users: name = user.user_name _policies = conn.get_all_user_policies(name, max_items=100) _policies = _policies.list_user_policies_response.list_user_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_user_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_user_policy_response.get_user_policy_result.policy_document )) policies[policy_name] = _policy user_sls = [] user_sls.append({"name": name}) user_sls.append({"policies": policies}) user_sls.append({"path": user.path}) results["manage user " + name] = {"boto_iam.user_present": user_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def _get_policy_arn(name, region=None, key=None, keyid=None, profile=None): if name.startswith('arn:aws:iam:'): return name account_id = get_account_id( region=region, key=key, keyid=keyid, profile=profile ) return 'arn:aws:iam::{0}:policy/{1}'.format(account_id, name) def policy_exists(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return True except boto.exception.BotoServerError: return False def get_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return ret.get('get_policy_response', {}).get('get_policy_result', {}) except boto.exception.BotoServerError: return None def create_policy(policy_name, policy_document, path=None, description=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in 'path', 'description': if locals()[arg] is not None: params[arg] = locals()[arg] if policy_exists(policy_name, region, key, keyid, profile): return True try: conn.create_policy(policy_name, policy_document, **params) log.info('Created IAM policy %s.', policy_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s.', policy_name) return False return True def delete_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_exists(policy_arn, region, key, keyid, profile): return True try: conn.delete_policy(policy_arn) log.info('Deleted %s policy.', policy_name) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete %s policy: %s.', policy_name, aws.get('message')) return False return True def list_policies(region=None, key=None, keyid=None, profile=None): ''' List policies. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policies ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: policies = [] for ret in __utils__['boto.paged_call'](conn.list_policies): policies.append(ret.get('list_policies_response', {}).get('list_policies_result', {}).get('policies')) return policies except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to list policy versions.' log.error(msg) return [] def policy_version_exists(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.get_policy_version(policy_arn, version_id) return True except boto.exception.BotoServerError: return False def get_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy_version(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile), version_id) retval = ret.get('get_policy_version_response', {}).get('get_policy_version_result', {}).get('policy_version', {}) retval['document'] = _unquote(retval.get('document')) return {'policy_version': retval} except boto.exception.BotoServerError: return None def create_policy_version(policy_name, policy_document, set_as_default=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy version. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy_version mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in ('set_as_default',): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.create_policy_version(policy_arn, policy_document, **params) vid = ret.get('create_policy_version_response', {}).get('create_policy_version_result', {}).get('policy_version', {}).get('version_id') log.info('Created IAM policy %s version %s.', policy_name, vid) return {'created': True, 'version_id': vid} except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s version %s.', policy_name, vid) return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Delete a policy version. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_version_exists(policy_arn, version_id, region, key, keyid, profile): return True try: conn.delete_policy_version(policy_arn, version_id) log.info('Deleted IAM policy %s version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete IAM policy %s version %s: %s', policy_name, version_id, aws.get('message')) return False return True def list_policy_versions(policy_name, region=None, key=None, keyid=None, profile=None): ''' List versions of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policy_versions mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.list_policy_versions(policy_arn) return ret.get('list_policy_versions_response', {}).get('list_policy_versions_result', {}).get('versions') except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list versions for IAM policy %s.', policy_name) return [] def set_default_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Set the default version of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.set_default_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.set_default_policy_version(policy_arn, version_id) log.info('Set %s policy to version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to set %s policy to version %s: %s', policy_name, version_id, aws.get('message')) return False return True def attach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_user_policy(policy_arn, user_name) log.info('Attached policy %s to IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach %s policy to IAM user %s.', policy_name, user_name) return False return True def detach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_user_policy(policy_arn, user_name) log.info('Detached %s policy from IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach %s policy from IAM user %s.', policy_name, user_name) return False return True def attach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_group_policy(policy_arn, group_name) log.info('Attached policy %s to IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM group %s.', policy_name, group_name) return False return True def detach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_group_policy(policy_arn, group_name) log.info('Detached policy %s from IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM group %s.', policy_name, group_name) return False return True def attach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_role_policy(policy_arn, role_name) log.info('Attached policy %s to IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM role %s.', policy_name, role_name) return False return True def detach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_role_policy(policy_arn, role_name) log.info('Detached policy %s from IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM role %s.', policy_name, role_name) return False return True def list_entities_for_policy(policy_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities that a policy is attached to. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 params = {} for arg in ('path_prefix', 'entity_filter'): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) while retries: try: allret = { 'policy_groups': [], 'policy_users': [], 'policy_roles': [], } for ret in __utils__['boto.paged_call'](conn.list_entities_for_policy, policy_arn=policy_arn, **params): for k, v in six.iteritems(allret): v.extend(ret.get('list_entities_for_policy_response', {}).get('list_entities_for_policy_result', {}).get(k)) return allret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('Failed to list entities for IAM policy %s: %s', policy_name, e.message) return {} return {} def list_attached_user_policies(user_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given user. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'UserName': user_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedUserPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_user_policies_response', {}).get('list_attached_user_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM user %s.', user_name) return [] def list_attached_group_policies(group_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given group. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'GroupName': group_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedGroupPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_group_policies_response', {}).get('list_attached_group_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM group %s.', group_name) return [] def list_attached_role_policies(role_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'RoleName': role_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedRolePolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_role_policies_response', {}).get('list_attached_role_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM role %s.', role_name) return [] def create_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Create SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.create_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_saml_provider(saml_metadata_document, name) log.info('Successfully created %s SAML provider.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to create SAML provider %s.', name) return False def get_saml_provider_arn(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider_arn my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_saml_providers() for saml_provider in response.list_saml_providers_response.list_saml_providers_result.saml_provider_list: if saml_provider['arn'].endswith(':saml-provider/' + name): return saml_provider['arn'] return False except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to get ARN of SAML provider %s.', name) return False def delete_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Delete SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.delete_saml_provider my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return True conn.delete_saml_provider(saml_provider_arn) log.info('Successfully deleted SAML provider %s.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete SAML provider %s.', name) return False def list_saml_providers(region=None, key=None, keyid=None, profile=None): ''' List SAML providers. CLI Example: .. code-block:: bash salt myminion boto_iam.list_saml_providers ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: providers = [] info = conn.list_saml_providers() for arn in info['list_saml_providers_response']['list_saml_providers_result']['saml_provider_list']: providers.append(arn['arn'].rsplit('/', 1)[1]) return providers except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get list of SAML providers.') return False def get_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider document. CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider arn ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: provider = conn.get_saml_provider(name) return provider['get_saml_provider_response']['get_saml_provider_result']['saml_metadata_document'] except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get SAML provider document %s.', name) return False def update_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Update SAML provider. CLI Example: .. code-block:: bash salt myminion boto_iam.update_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return False if conn.update_saml_provider(name, saml_metadata_document): return True return False except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to update SAML provider %s.', name) return False
saltstack/salt
salt/modules/boto_iam.py
policy_exists
python
def policy_exists(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return True except boto.exception.BotoServerError: return False
Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iam.py#L1706-L1724
[ "def _get_policy_arn(name, region=None, key=None, keyid=None, profile=None):\n if name.startswith('arn:aws:iam:'):\n return name\n\n account_id = get_account_id(\n region=region, key=key, keyid=keyid, profile=profile\n )\n return 'arn:aws:iam::{0}:policy/{1}'.format(account_id, name)\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon IAM .. versionadded:: 2014.7.0 :configuration: This module accepts explicit iam 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 iam.keyid: GKTADJGHEIQSXMKKRBJ08H iam.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs iam.region: 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: boto ''' # keep lint from choking on _get_conn and _cache_id #pylint: disable=E0602 # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import salt libs from salt.ext import six import salt.utils.compat import salt.utils.json import salt.utils.odict as odict import salt.utils.versions from salt.exceptions import SaltInvocationError # Import third party libs # pylint: disable=unused-import from salt.ext.six.moves.urllib.parse import unquote as _unquote # pylint: disable=no-name-in-module try: import boto import boto.iam import boto3 import botocore logging.getLogger('boto').setLevel(logging.CRITICAL) logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=unused-import log = logging.getLogger(__name__) def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'iam', pack=__salt__) def instance_profile_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an instance profile exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: # Boto weirdly returns an exception here if an instance profile doesn't # exist. conn.get_instance_profile(name) return True except boto.exception.BotoServerError: return False def create_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Create an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.create_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if instance_profile_exists(name, region, key, keyid, profile): return True try: # This call returns an instance profile if successful and an exception # if not. It's annoying. conn.create_instance_profile(name) log.info('Created %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create %s instance profile.', name) return False return True def delete_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Delete an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not instance_profile_exists(name, region, key, keyid, profile): return True try: conn.delete_instance_profile(name) log.info('Deleted %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s instance profile.', name) return False return True def role_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an IAM role exists. CLI Example: .. code-block:: bash salt myminion boto_iam.role_exists myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_role(name) return True except boto.exception.BotoServerError: return False def describe_role(name, region=None, key=None, keyid=None, profile=None): ''' Get information for a role. CLI Example: .. code-block:: bash salt myminion boto_iam.describe_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_role(name) if not info: return False role = info.get_role_response.get_role_result.role role['assume_role_policy_document'] = salt.utils.json.loads(_unquote( role.assume_role_policy_document )) # If Sid wasn't defined by the user, boto will still return a Sid in # each policy. To properly check idempotently, let's remove the Sid # from the return if it's not actually set. for policy_key, policy in role['assume_role_policy_document'].items(): if policy_key == 'Statement': for val in policy: if 'Sid' in val and not val['Sid']: del val['Sid'] return role except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get %s information.', name) return False def create_user(user_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_user myuser ''' if not path: path = '/' if get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_user(user_name, path) log.info('Created IAM user : %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM user %s.', user_name) return False def get_all_access_keys(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all access keys from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_access_keys myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.get_all_access_keys(user_name, marker, max_items) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get access keys for IAM user %s.', user_name) return six.text_type(e) def create_access_key(user_name, region=None, key=None, keyid=None, profile=None): ''' Create access key id for a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.create_access_key(user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create access key.') return six.text_type(e) def delete_access_key(access_key_id, user_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete access key id from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_access_key(access_key_id, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete access key id %s.', access_key_id) return six.text_type(e) def delete_user(user_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user myuser ''' if not get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.delete_user(user_name) log.info('Deleted IAM user : %s .', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM user %s', user_name) return six.text_type(e) def get_user(user_name=None, region=None, key=None, keyid=None, profile=None): ''' Get user information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user(user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM user %s info.', user_name) return False def create_group(group_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_group group ''' if not path: path = '/' if get_group(group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_group(group_name, path) log.info('Created IAM group : %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM group %s.', group_name) return False def get_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group(group_name, max_items=1) if not info: return False return info['get_group_response']['get_group_result']['group'] except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_group_members(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: marker = None truncated = True users = [] while truncated: info = conn.get_group(group_name, marker=marker, max_items=1000) if not info: return False truncated = bool(info['get_group_response']['get_group_result']['is_truncated']) if truncated and 'marker' in info['get_group_response']['get_group_result']: marker = info['get_group_response']['get_group_result']['marker'] else: marker = None truncated = False users += info['get_group_response']['get_group_result']['users'] return users except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get members for IAM group %s.', group_name) return False def add_user_to_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Add user to group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.add_user_to_group myuser mygroup ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('Username : %s does not exist.', user_name) return False if user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.add_user_to_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add IAM user %s to group %s.', user_name, group_name) return False def user_exists_in_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Check if user exists in group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.user_exists_in_group myuser mygroup ''' # TODO this should probably use boto.iam.get_groups_for_user users = get_group_members( group_name=group_name, region=region, key=key, keyid=keyid, profile=profile ) if users: for _user in users: if user_name == _user['user_name']: log.debug('IAM user %s is already in IAM group %s.', user_name, group_name) return True return False def remove_user_from_group(group_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Remove user from group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.remove_user_from_group mygroup myuser ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist.', user_name) return False if not user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.remove_user_from_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove IAM user %s from group %s', user_name, group_name) return False def put_group_policy(group_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_group_policy mygroup policyname policyrules ''' group = get_group(group_name, region=region, key=key, keyid=keyid, profile=profile) if not group: log.error('Group %s does not exist', group_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_group_policy(group_name, policy_name, policy_json) if created: log.info('Created policy for IAM group %s.', group_name) return True log.error('Could not create policy for IAM group %s', group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy for IAM group %s', group_name) return False def delete_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group_policy mygroup mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_group_policy( group_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_group_policy(group_name, policy_name) log.info('Successfully deleted policy %s for IAM group %s.', policy_name, group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM group %s.', policy_name, group_name) return False def get_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group_policy mygroup policyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group_policy(group_name, policy_name) log.debug('info for group policy is : %s', info) if not info: return False info = info.get_group_policy_response.get_group_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_all_groups(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM group details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_groups ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _groups = conn.get_all_groups(path_prefix=path_prefix) groups = _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) while marker: _groups = conn.get_all_groups(path_prefix=path_prefix, marker=marker) groups = groups + _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) return groups def get_all_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.get_all_instance_profiles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) marker = False profiles = [] while marker is not None: marker = marker if marker else None p = conn.list_instance_profiles(path_prefix=path_prefix, marker=marker) res = p.list_instance_profiles_response.list_instance_profiles_result profiles += res.instance_profiles marker = getattr(res, 'marker', None) return profiles def list_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' List all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.list_instance_profiles ''' p = get_all_instance_profiles(path_prefix, region, key, keyid, profile) return [i['instance_profile_name'] for i in p] def get_all_group_policies(group_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a group. CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_group_policies mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False try: response = conn.get_all_group_policies(group_name) _list = response.list_group_policies_response.list_group_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def delete_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _group = get_group( group_name, region, key, keyid, profile ) if not _group: return True try: conn.delete_group(group_name) log.info('Successfully deleted IAM group %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM group %s.', group_name) return False def create_login_profile(user_name, password, region=None, key=None, keyid=None, profile=None): ''' Creates a login profile for the specified user, give the user the ability to access AWS services and the AWS Management Console. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_login_profile user_name password ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.create_login_profile(user_name, password) log.info('Created profile for IAM user %s.', user_name) return info except boto.exception.BotoServerError as e: log.debug(e) if 'Conflict' in e: log.info('Profile already exists for IAM user %s.', user_name) return 'Conflict' log.error('Failed to update profile for IAM user %s.', user_name) return False def delete_login_profile(user_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a login profile for the specified user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_login_profile user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.delete_login_profile(user_name) log.info('Deleted login profile for IAM user %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Login profile already deleted for IAM user %s.', user_name) return True log.error('Failed to delete login profile for IAM user %s.', user_name) return False def get_all_mfa_devices(user_name, region=None, key=None, keyid=None, profile=None): ''' Get all MFA devices associated with an IAM user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_mfa_devices user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: result = conn.get_all_mfa_devices(user_name) devices = result['list_mfa_devices_response']['list_mfa_devices_result']['mfa_devices'] return devices except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Could not find IAM user %s.', user_name) return [] log.error('Failed to get all MFA devices for IAM user %s.', user_name) return False def deactivate_mfa_device(user_name, serial, region=None, key=None, keyid=None, profile=None): ''' Deactivates the specified MFA device and removes it from association with the user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.deactivate_mfa_device user_name serial_num ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.deactivate_mfa_device(user_name, serial) log.info('Deactivated MFA device %s for IAM user %s.', serial, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('MFA device %s not associated with IAM user %s.', serial, user_name) return True log.error('Failed to deactivate MFA device %s for IAM user %s.', serial, user_name) return False def delete_virtual_mfa_device(serial, region=None, key=None, keyid=None, profile=None): ''' Deletes the specified virtual MFA device. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_virtual_mfa_device serial_num ''' conn = __utils__['boto3.get_connection_func']('iam')() try: conn.delete_virtual_mfa_device(SerialNumber=serial) log.info('Deleted virtual MFA device %s.', serial) return True except botocore.exceptions.ClientError as e: log.debug(e) if 'NoSuchEntity' in six.text_type(e): log.info('Virtual MFA device %s not found.', serial) return True log.error('Failed to delete virtual MFA device %s.', serial) return False def update_account_password_policy(allow_users_to_change_password=None, hard_expiry=None, max_password_age=None, minimum_password_length=None, password_reuse_prevention=None, require_lowercase_characters=None, require_numbers=None, require_symbols=None, require_uppercase_characters=None, region=None, key=None, keyid=None, profile=None): ''' Update the password policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_account_password_policy True ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.update_account_password_policy(allow_users_to_change_password, hard_expiry, max_password_age, minimum_password_length, password_reuse_prevention, require_lowercase_characters, require_numbers, require_symbols, require_uppercase_characters) log.info('The password policy has been updated.') return True except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy' log.error(msg) return False def get_account_policy(region=None, key=None, keyid=None, profile=None): ''' Get account policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_account_password_policy() return info.get_account_password_policy_response.get_account_password_policy_result.password_policy except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy.' log.error(msg) return False def create_role(name, policy_document=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Create an instance role. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if role_exists(name, region, key, keyid, profile): return True if not policy_document: policy_document = None try: conn.create_role(name, assume_role_policy_document=policy_document, path=path) log.info('Created IAM role %s.', name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to create IAM role %s.', name) return False def delete_role(name, region=None, key=None, keyid=None, profile=None): ''' Delete an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(name, region, key, keyid, profile): return True try: conn.delete_role(name) log.info('Deleted %s IAM role.', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s IAM role.', name) return False def profile_associated(role_name, profile_name, region, key, keyid, profile): ''' Check to see if an instance profile is associated with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.profile_associated myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # The IAM module of boto doesn't return objects. Instead you need to grab # values through its properties. Sigh. try: profiles = conn.list_instance_profiles_for_role(role_name) except boto.exception.BotoServerError as e: log.debug(e) return False profiles = profiles.list_instance_profiles_for_role_response profiles = profiles.list_instance_profiles_for_role_result profiles = profiles.instance_profiles for profile in profiles: if profile.instance_profile_name == profile_name: return True return False def associate_profile_to_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Associate an instance profile with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.associate_profile_to_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if associated: return True else: try: conn.add_role_to_instance_profile(profile_name, role_name) log.info('Added %s instance profile to IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add %s instance profile to IAM role %s', profile_name, role_name) return False def disassociate_profile_from_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Disassociate an instance profile from an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.disassociate_profile_from_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if not associated: return True else: try: conn.remove_role_from_instance_profile(profile_name, role_name) log.info('Removed %s instance profile from IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove %s instance profile from IAM role %s.', profile_name, role_name) return False def list_role_policies(role_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_role_policies myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_role_policies(role_name) _list = response.list_role_policies_response.list_role_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def get_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.get_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: _policy = conn.get_role_policy(role_name, policy_name) # I _hate_ you for not giving me an object boto. _policy = _policy.get_role_policy_response.policy_document # Policy is url encoded _policy = _unquote(_policy) _policy = salt.utils.json.loads(_policy, object_pairs_hook=odict.OrderedDict) return _policy except boto.exception.BotoServerError: return {} def create_role_policy(role_name, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Create or modify a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role_policy myirole mypolicy '{"MyPolicy": "Statement": [{"Action": ["sqs:*"], "Effect": "Allow", "Resource": ["arn:aws:sqs:*:*:*"], "Sid": "MyPolicySqs1"}]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) mode = 'create' if _policy: if _policy == policy: return True mode = 'modify' if isinstance(policy, six.string_types): policy = salt.utils.json.loads(policy, object_pairs_hook=odict.OrderedDict) try: _policy = salt.utils.json.dumps(policy) conn.put_role_policy(role_name, policy_name, _policy) if mode == 'create': msg = 'Successfully added policy %s to IAM role %s.' else: msg = 'Successfully modified policy %s for IAM role %s.' log.info(msg, policy_name, role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to %s policy %s for IAM role %s.', mode, policy_name, role_name) return False def delete_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) if not _policy: return True try: conn.delete_role_policy(role_name, policy_name) log.info('Successfully deleted policy %s for IAM role %s.', policy_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM role %s.', policy_name, role_name) return False def update_assume_role_policy(role_name, policy_document, region=None, key=None, keyid=None, profile=None): ''' Update an assume role policy for a role. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_assume_role_policy myrole '{"Statement":"..."}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(policy_document, six.string_types): policy_document = salt.utils.json.loads(policy_document, object_pairs_hook=odict.OrderedDict) try: _policy_document = salt.utils.json.dumps(policy_document) conn.update_assume_role_policy(role_name, _policy_document) log.info('Successfully updated assume role policy for IAM role %s.', role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to update assume role policy for IAM role %s.', role_name) return False def build_policy(region=None, key=None, keyid=None, profile=None): ''' Build a default assume role policy. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.build_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if hasattr(conn, 'build_policy'): policy = salt.utils.json.loads(conn.build_policy()) elif hasattr(conn, '_build_policy'): policy = salt.utils.json.loads(conn._build_policy()) else: return {} # The format we get from build_policy isn't going to be what we get back # from AWS for the exact same policy. AWS converts single item list values # into strings, so let's do the same here. for key, policy_val in policy.items(): for statement in policy_val: if (isinstance(statement['Action'], list) and len(statement['Action']) == 1): statement['Action'] = statement['Action'][0] if (isinstance(statement['Principal']['Service'], list) and len(statement['Principal']['Service']) == 1): statement['Principal']['Service'] = statement['Principal']['Service'][0] # build_policy doesn't add a version field, which AWS is going to set to a # default value, when we get it back, so let's set it. policy['Version'] = '2008-10-17' return policy def get_account_id(region=None, key=None, keyid=None, profile=None): ''' Get a the AWS account id associated with the used credentials. CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_id ''' cache_key = 'boto_iam.account_id' if cache_key not in __context__: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_user() # The get_user call returns an user ARN: # arn:aws:iam::027050522557:user/salt-test arn = ret['get_user_response']['get_user_result']['user']['arn'] account_id = arn.split(':')[4] except boto.exception.BotoServerError: # If call failed, then let's try to get the ARN from the metadata timeout = boto.config.getfloat( 'Boto', 'metadata_service_timeout', 1.0 ) attempts = boto.config.getint( 'Boto', 'metadata_service_num_attempts', 1 ) identity = boto.utils.get_instance_identity( timeout=timeout, num_retries=attempts ) try: account_id = identity['document']['accountId'] except KeyError: log.error('Failed to get account id from instance_identity in' ' boto_iam.get_account_id.') __context__[cache_key] = account_id return __context__[cache_key] def get_all_roles(path_prefix=None, region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM role details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_roles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _roles = conn.list_roles(path_prefix=path_prefix) roles = _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) while marker: _roles = conn.list_roles(path_prefix=path_prefix, marker=marker) roles = roles + _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) return roles def get_all_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM user details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_users ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _users = conn.get_all_users(path_prefix=path_prefix) users = _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) while marker: _users = conn.get_all_users(path_prefix=path_prefix, marker=marker) users = users + _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) return users def get_all_user_policies(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all user policies. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_user_policies myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_all_user_policies(user_name, marker, max_items) if not info: return False _list = info.list_user_policies_response.list_user_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policies for user %s.', user_name) return False def get_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user_policy myuser mypolicyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user_policy(user_name, policy_name) log.debug('Info for IAM user %s policy %s: %s.', user_name, policy_name, info) if not info: return False info = info.get_user_policy_response.get_user_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policy %s for IAM user %s.', policy_name, user_name) return False def put_user_policy(user_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_user_policy myuser policyname policyrules ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_user_policy(user_name, policy_name, policy_json) if created: log.info('Created policy %s for IAM user %s.', policy_name, user_name) return True log.error('Could not create policy %s for IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy %s for IAM user %s.', policy_name, user_name) return False def delete_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user_policy myuser mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_user_policy( user_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_user_policy(user_name, policy_name) log.info('Successfully deleted policy %s for IAM user %s.', policy_name, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM user %s.', policy_name, user_name) return False def upload_server_cert(cert_name, cert_body, private_key, cert_chain=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Upload a certificate to Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.upload_server_cert mycert_name crt priv_key :param cert_name: The name for the server certificate. Do not include the path in this value. :param cert_body: The contents of the public key certificate in PEM-encoded format. :param private_key: The contents of the private key in PEM-encoded format. :param cert_chain: The contents of the certificate chain. This is typically a concatenation of the PEM-encoded public key certificates of the chain. :param path: The path for the server certificate. :param region: The name of the region to connect to. :param key: The key to be used in order to connect :param keyid: The keyid to be used in order to connect :param profile: The profile that contains a dict of region, key, keyid :return: True / False ''' exists = get_server_certificate(cert_name, region, key, keyid, profile) if exists: return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.upload_server_cert(cert_name, cert_body, private_key, cert_chain) log.info('Created certificate %s.', cert_name) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to failed to create certificate %s.', cert_name) return False def list_server_certificates(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Lists the server certificates stored in IAM that have the specified path prefix. .. versionadded:: ??? :param path_prefix: The path prefix for filtering the results. For example: /company/servercerts would get all server certificates for which the path starts with /company/servercerts . This parameter is optional. If it is not included, it defaults to a slash (/), listing all server certificates. This parameter allows (per its regex pattern) a string of characters consisting of either a forward slash (/) by itself or a string that must begin and end with forward slashes. In addition, it can contain any ASCII character from the ! (u0021) through the DEL character (u007F), including most punctuation characters, digits, and upper and lowercased letters. CLI Example: .. code-block:: bash salt myminion boto_iam.list_server_certificates path_prefix=/somepath/ ''' retries = 10 sleep = 6 conn = __utils__['boto3.get_connection']('iam', region=region, key=key, keyid=keyid, profile=profile) Items = [] while retries: try: log.debug('Garnering list of IAM Server Certificates') IsTruncated = True while IsTruncated: kwargs = {'PathPrefix': path_prefix} ret = conn.list_server_certificates(**kwargs) Items += ret.get('ServerCertificateMetadataList', []) IsTruncated = ret.get('IsTruncated') kwargs.update({'Marker': ret.get('Marker')}) return Items except botocore.exceptions.ParamValidationError as err: raise SaltInvocationError(str(err)) except botocore.exceptions.ClientError as err: if retries and jmespath.search('Error.Code', err.response) == 'Throttling': retries -= 1 log.debug('Throttled by AWS API, retrying in %s seconds...', sleep) time.sleep(sleep) continue log.error('Failed to list IAM Server Certificates: %s', err.message) return None def get_server_certificate(cert_name, region=None, key=None, keyid=None, profile=None): ''' Returns certificate information from Amazon .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_server_certificate mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_server_certificate(cert_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get certificate %s information.', cert_name) return False def delete_server_cert(cert_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a certificate from Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_server_cert mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_server_cert(cert_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete certificate %s.', cert_name) return False def export_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM user details. Produces results that can be used to create an sls file. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.export_users --out=txt | sed "s/local: //" > iam_users.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() users = get_all_users(path_prefix, region, key, keyid, profile) for user in users: name = user.user_name _policies = conn.get_all_user_policies(name, max_items=100) _policies = _policies.list_user_policies_response.list_user_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_user_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_user_policy_response.get_user_policy_result.policy_document )) policies[policy_name] = _policy user_sls = [] user_sls.append({"name": name}) user_sls.append({"policies": policies}) user_sls.append({"path": user.path}) results["manage user " + name] = {"boto_iam.user_present": user_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def export_roles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM role details. Produces results that can be used to create an sls file. CLI Example: salt-call boto_iam.export_roles --out=txt | sed "s/local: //" > iam_roles.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() roles = get_all_roles(path_prefix, region, key, keyid, profile) for role in roles: name = role.role_name _policies = conn.list_role_policies(name, max_items=100) _policies = _policies.list_role_policies_response.list_role_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_role_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_role_policy_response.get_role_policy_result.policy_document )) policies[policy_name] = _policy role_sls = [] role_sls.append({"name": name}) role_sls.append({"policies": policies}) role_sls.append({'policy_document': salt.utils.json.loads(_unquote(role.assume_role_policy_document))}) role_sls.append({"path": role.path}) results["manage role " + name] = {"boto_iam_role.present": role_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def _get_policy_arn(name, region=None, key=None, keyid=None, profile=None): if name.startswith('arn:aws:iam:'): return name account_id = get_account_id( region=region, key=key, keyid=keyid, profile=profile ) return 'arn:aws:iam::{0}:policy/{1}'.format(account_id, name) def get_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return ret.get('get_policy_response', {}).get('get_policy_result', {}) except boto.exception.BotoServerError: return None def create_policy(policy_name, policy_document, path=None, description=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in 'path', 'description': if locals()[arg] is not None: params[arg] = locals()[arg] if policy_exists(policy_name, region, key, keyid, profile): return True try: conn.create_policy(policy_name, policy_document, **params) log.info('Created IAM policy %s.', policy_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s.', policy_name) return False return True def delete_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_exists(policy_arn, region, key, keyid, profile): return True try: conn.delete_policy(policy_arn) log.info('Deleted %s policy.', policy_name) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete %s policy: %s.', policy_name, aws.get('message')) return False return True def list_policies(region=None, key=None, keyid=None, profile=None): ''' List policies. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policies ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: policies = [] for ret in __utils__['boto.paged_call'](conn.list_policies): policies.append(ret.get('list_policies_response', {}).get('list_policies_result', {}).get('policies')) return policies except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to list policy versions.' log.error(msg) return [] def policy_version_exists(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.get_policy_version(policy_arn, version_id) return True except boto.exception.BotoServerError: return False def get_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy_version(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile), version_id) retval = ret.get('get_policy_version_response', {}).get('get_policy_version_result', {}).get('policy_version', {}) retval['document'] = _unquote(retval.get('document')) return {'policy_version': retval} except boto.exception.BotoServerError: return None def create_policy_version(policy_name, policy_document, set_as_default=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy version. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy_version mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in ('set_as_default',): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.create_policy_version(policy_arn, policy_document, **params) vid = ret.get('create_policy_version_response', {}).get('create_policy_version_result', {}).get('policy_version', {}).get('version_id') log.info('Created IAM policy %s version %s.', policy_name, vid) return {'created': True, 'version_id': vid} except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s version %s.', policy_name, vid) return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Delete a policy version. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_version_exists(policy_arn, version_id, region, key, keyid, profile): return True try: conn.delete_policy_version(policy_arn, version_id) log.info('Deleted IAM policy %s version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete IAM policy %s version %s: %s', policy_name, version_id, aws.get('message')) return False return True def list_policy_versions(policy_name, region=None, key=None, keyid=None, profile=None): ''' List versions of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policy_versions mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.list_policy_versions(policy_arn) return ret.get('list_policy_versions_response', {}).get('list_policy_versions_result', {}).get('versions') except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list versions for IAM policy %s.', policy_name) return [] def set_default_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Set the default version of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.set_default_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.set_default_policy_version(policy_arn, version_id) log.info('Set %s policy to version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to set %s policy to version %s: %s', policy_name, version_id, aws.get('message')) return False return True def attach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_user_policy(policy_arn, user_name) log.info('Attached policy %s to IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach %s policy to IAM user %s.', policy_name, user_name) return False return True def detach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_user_policy(policy_arn, user_name) log.info('Detached %s policy from IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach %s policy from IAM user %s.', policy_name, user_name) return False return True def attach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_group_policy(policy_arn, group_name) log.info('Attached policy %s to IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM group %s.', policy_name, group_name) return False return True def detach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_group_policy(policy_arn, group_name) log.info('Detached policy %s from IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM group %s.', policy_name, group_name) return False return True def attach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_role_policy(policy_arn, role_name) log.info('Attached policy %s to IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM role %s.', policy_name, role_name) return False return True def detach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_role_policy(policy_arn, role_name) log.info('Detached policy %s from IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM role %s.', policy_name, role_name) return False return True def list_entities_for_policy(policy_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities that a policy is attached to. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 params = {} for arg in ('path_prefix', 'entity_filter'): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) while retries: try: allret = { 'policy_groups': [], 'policy_users': [], 'policy_roles': [], } for ret in __utils__['boto.paged_call'](conn.list_entities_for_policy, policy_arn=policy_arn, **params): for k, v in six.iteritems(allret): v.extend(ret.get('list_entities_for_policy_response', {}).get('list_entities_for_policy_result', {}).get(k)) return allret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('Failed to list entities for IAM policy %s: %s', policy_name, e.message) return {} return {} def list_attached_user_policies(user_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given user. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'UserName': user_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedUserPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_user_policies_response', {}).get('list_attached_user_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM user %s.', user_name) return [] def list_attached_group_policies(group_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given group. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'GroupName': group_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedGroupPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_group_policies_response', {}).get('list_attached_group_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM group %s.', group_name) return [] def list_attached_role_policies(role_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'RoleName': role_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedRolePolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_role_policies_response', {}).get('list_attached_role_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM role %s.', role_name) return [] def create_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Create SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.create_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_saml_provider(saml_metadata_document, name) log.info('Successfully created %s SAML provider.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to create SAML provider %s.', name) return False def get_saml_provider_arn(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider_arn my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_saml_providers() for saml_provider in response.list_saml_providers_response.list_saml_providers_result.saml_provider_list: if saml_provider['arn'].endswith(':saml-provider/' + name): return saml_provider['arn'] return False except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to get ARN of SAML provider %s.', name) return False def delete_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Delete SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.delete_saml_provider my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return True conn.delete_saml_provider(saml_provider_arn) log.info('Successfully deleted SAML provider %s.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete SAML provider %s.', name) return False def list_saml_providers(region=None, key=None, keyid=None, profile=None): ''' List SAML providers. CLI Example: .. code-block:: bash salt myminion boto_iam.list_saml_providers ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: providers = [] info = conn.list_saml_providers() for arn in info['list_saml_providers_response']['list_saml_providers_result']['saml_provider_list']: providers.append(arn['arn'].rsplit('/', 1)[1]) return providers except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get list of SAML providers.') return False def get_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider document. CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider arn ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: provider = conn.get_saml_provider(name) return provider['get_saml_provider_response']['get_saml_provider_result']['saml_metadata_document'] except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get SAML provider document %s.', name) return False def update_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Update SAML provider. CLI Example: .. code-block:: bash salt myminion boto_iam.update_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return False if conn.update_saml_provider(name, saml_metadata_document): return True return False except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to update SAML provider %s.', name) return False
saltstack/salt
salt/modules/boto_iam.py
get_policy
python
def get_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return ret.get('get_policy_response', {}).get('get_policy_result', {}) except boto.exception.BotoServerError: return None
Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iam.py#L1727-L1745
[ "def _get_policy_arn(name, region=None, key=None, keyid=None, profile=None):\n if name.startswith('arn:aws:iam:'):\n return name\n\n account_id = get_account_id(\n region=region, key=key, keyid=keyid, profile=profile\n )\n return 'arn:aws:iam::{0}:policy/{1}'.format(account_id, name)\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon IAM .. versionadded:: 2014.7.0 :configuration: This module accepts explicit iam 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 iam.keyid: GKTADJGHEIQSXMKKRBJ08H iam.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs iam.region: 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: boto ''' # keep lint from choking on _get_conn and _cache_id #pylint: disable=E0602 # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import salt libs from salt.ext import six import salt.utils.compat import salt.utils.json import salt.utils.odict as odict import salt.utils.versions from salt.exceptions import SaltInvocationError # Import third party libs # pylint: disable=unused-import from salt.ext.six.moves.urllib.parse import unquote as _unquote # pylint: disable=no-name-in-module try: import boto import boto.iam import boto3 import botocore logging.getLogger('boto').setLevel(logging.CRITICAL) logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=unused-import log = logging.getLogger(__name__) def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'iam', pack=__salt__) def instance_profile_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an instance profile exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: # Boto weirdly returns an exception here if an instance profile doesn't # exist. conn.get_instance_profile(name) return True except boto.exception.BotoServerError: return False def create_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Create an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.create_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if instance_profile_exists(name, region, key, keyid, profile): return True try: # This call returns an instance profile if successful and an exception # if not. It's annoying. conn.create_instance_profile(name) log.info('Created %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create %s instance profile.', name) return False return True def delete_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Delete an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not instance_profile_exists(name, region, key, keyid, profile): return True try: conn.delete_instance_profile(name) log.info('Deleted %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s instance profile.', name) return False return True def role_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an IAM role exists. CLI Example: .. code-block:: bash salt myminion boto_iam.role_exists myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_role(name) return True except boto.exception.BotoServerError: return False def describe_role(name, region=None, key=None, keyid=None, profile=None): ''' Get information for a role. CLI Example: .. code-block:: bash salt myminion boto_iam.describe_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_role(name) if not info: return False role = info.get_role_response.get_role_result.role role['assume_role_policy_document'] = salt.utils.json.loads(_unquote( role.assume_role_policy_document )) # If Sid wasn't defined by the user, boto will still return a Sid in # each policy. To properly check idempotently, let's remove the Sid # from the return if it's not actually set. for policy_key, policy in role['assume_role_policy_document'].items(): if policy_key == 'Statement': for val in policy: if 'Sid' in val and not val['Sid']: del val['Sid'] return role except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get %s information.', name) return False def create_user(user_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_user myuser ''' if not path: path = '/' if get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_user(user_name, path) log.info('Created IAM user : %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM user %s.', user_name) return False def get_all_access_keys(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all access keys from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_access_keys myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.get_all_access_keys(user_name, marker, max_items) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get access keys for IAM user %s.', user_name) return six.text_type(e) def create_access_key(user_name, region=None, key=None, keyid=None, profile=None): ''' Create access key id for a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.create_access_key(user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create access key.') return six.text_type(e) def delete_access_key(access_key_id, user_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete access key id from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_access_key(access_key_id, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete access key id %s.', access_key_id) return six.text_type(e) def delete_user(user_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user myuser ''' if not get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.delete_user(user_name) log.info('Deleted IAM user : %s .', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM user %s', user_name) return six.text_type(e) def get_user(user_name=None, region=None, key=None, keyid=None, profile=None): ''' Get user information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user(user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM user %s info.', user_name) return False def create_group(group_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_group group ''' if not path: path = '/' if get_group(group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_group(group_name, path) log.info('Created IAM group : %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM group %s.', group_name) return False def get_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group(group_name, max_items=1) if not info: return False return info['get_group_response']['get_group_result']['group'] except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_group_members(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: marker = None truncated = True users = [] while truncated: info = conn.get_group(group_name, marker=marker, max_items=1000) if not info: return False truncated = bool(info['get_group_response']['get_group_result']['is_truncated']) if truncated and 'marker' in info['get_group_response']['get_group_result']: marker = info['get_group_response']['get_group_result']['marker'] else: marker = None truncated = False users += info['get_group_response']['get_group_result']['users'] return users except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get members for IAM group %s.', group_name) return False def add_user_to_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Add user to group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.add_user_to_group myuser mygroup ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('Username : %s does not exist.', user_name) return False if user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.add_user_to_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add IAM user %s to group %s.', user_name, group_name) return False def user_exists_in_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Check if user exists in group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.user_exists_in_group myuser mygroup ''' # TODO this should probably use boto.iam.get_groups_for_user users = get_group_members( group_name=group_name, region=region, key=key, keyid=keyid, profile=profile ) if users: for _user in users: if user_name == _user['user_name']: log.debug('IAM user %s is already in IAM group %s.', user_name, group_name) return True return False def remove_user_from_group(group_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Remove user from group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.remove_user_from_group mygroup myuser ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist.', user_name) return False if not user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.remove_user_from_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove IAM user %s from group %s', user_name, group_name) return False def put_group_policy(group_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_group_policy mygroup policyname policyrules ''' group = get_group(group_name, region=region, key=key, keyid=keyid, profile=profile) if not group: log.error('Group %s does not exist', group_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_group_policy(group_name, policy_name, policy_json) if created: log.info('Created policy for IAM group %s.', group_name) return True log.error('Could not create policy for IAM group %s', group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy for IAM group %s', group_name) return False def delete_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group_policy mygroup mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_group_policy( group_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_group_policy(group_name, policy_name) log.info('Successfully deleted policy %s for IAM group %s.', policy_name, group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM group %s.', policy_name, group_name) return False def get_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group_policy mygroup policyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group_policy(group_name, policy_name) log.debug('info for group policy is : %s', info) if not info: return False info = info.get_group_policy_response.get_group_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_all_groups(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM group details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_groups ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _groups = conn.get_all_groups(path_prefix=path_prefix) groups = _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) while marker: _groups = conn.get_all_groups(path_prefix=path_prefix, marker=marker) groups = groups + _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) return groups def get_all_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.get_all_instance_profiles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) marker = False profiles = [] while marker is not None: marker = marker if marker else None p = conn.list_instance_profiles(path_prefix=path_prefix, marker=marker) res = p.list_instance_profiles_response.list_instance_profiles_result profiles += res.instance_profiles marker = getattr(res, 'marker', None) return profiles def list_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' List all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.list_instance_profiles ''' p = get_all_instance_profiles(path_prefix, region, key, keyid, profile) return [i['instance_profile_name'] for i in p] def get_all_group_policies(group_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a group. CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_group_policies mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False try: response = conn.get_all_group_policies(group_name) _list = response.list_group_policies_response.list_group_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def delete_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _group = get_group( group_name, region, key, keyid, profile ) if not _group: return True try: conn.delete_group(group_name) log.info('Successfully deleted IAM group %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM group %s.', group_name) return False def create_login_profile(user_name, password, region=None, key=None, keyid=None, profile=None): ''' Creates a login profile for the specified user, give the user the ability to access AWS services and the AWS Management Console. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_login_profile user_name password ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.create_login_profile(user_name, password) log.info('Created profile for IAM user %s.', user_name) return info except boto.exception.BotoServerError as e: log.debug(e) if 'Conflict' in e: log.info('Profile already exists for IAM user %s.', user_name) return 'Conflict' log.error('Failed to update profile for IAM user %s.', user_name) return False def delete_login_profile(user_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a login profile for the specified user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_login_profile user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.delete_login_profile(user_name) log.info('Deleted login profile for IAM user %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Login profile already deleted for IAM user %s.', user_name) return True log.error('Failed to delete login profile for IAM user %s.', user_name) return False def get_all_mfa_devices(user_name, region=None, key=None, keyid=None, profile=None): ''' Get all MFA devices associated with an IAM user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_mfa_devices user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: result = conn.get_all_mfa_devices(user_name) devices = result['list_mfa_devices_response']['list_mfa_devices_result']['mfa_devices'] return devices except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Could not find IAM user %s.', user_name) return [] log.error('Failed to get all MFA devices for IAM user %s.', user_name) return False def deactivate_mfa_device(user_name, serial, region=None, key=None, keyid=None, profile=None): ''' Deactivates the specified MFA device and removes it from association with the user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.deactivate_mfa_device user_name serial_num ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.deactivate_mfa_device(user_name, serial) log.info('Deactivated MFA device %s for IAM user %s.', serial, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('MFA device %s not associated with IAM user %s.', serial, user_name) return True log.error('Failed to deactivate MFA device %s for IAM user %s.', serial, user_name) return False def delete_virtual_mfa_device(serial, region=None, key=None, keyid=None, profile=None): ''' Deletes the specified virtual MFA device. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_virtual_mfa_device serial_num ''' conn = __utils__['boto3.get_connection_func']('iam')() try: conn.delete_virtual_mfa_device(SerialNumber=serial) log.info('Deleted virtual MFA device %s.', serial) return True except botocore.exceptions.ClientError as e: log.debug(e) if 'NoSuchEntity' in six.text_type(e): log.info('Virtual MFA device %s not found.', serial) return True log.error('Failed to delete virtual MFA device %s.', serial) return False def update_account_password_policy(allow_users_to_change_password=None, hard_expiry=None, max_password_age=None, minimum_password_length=None, password_reuse_prevention=None, require_lowercase_characters=None, require_numbers=None, require_symbols=None, require_uppercase_characters=None, region=None, key=None, keyid=None, profile=None): ''' Update the password policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_account_password_policy True ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.update_account_password_policy(allow_users_to_change_password, hard_expiry, max_password_age, minimum_password_length, password_reuse_prevention, require_lowercase_characters, require_numbers, require_symbols, require_uppercase_characters) log.info('The password policy has been updated.') return True except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy' log.error(msg) return False def get_account_policy(region=None, key=None, keyid=None, profile=None): ''' Get account policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_account_password_policy() return info.get_account_password_policy_response.get_account_password_policy_result.password_policy except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy.' log.error(msg) return False def create_role(name, policy_document=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Create an instance role. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if role_exists(name, region, key, keyid, profile): return True if not policy_document: policy_document = None try: conn.create_role(name, assume_role_policy_document=policy_document, path=path) log.info('Created IAM role %s.', name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to create IAM role %s.', name) return False def delete_role(name, region=None, key=None, keyid=None, profile=None): ''' Delete an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(name, region, key, keyid, profile): return True try: conn.delete_role(name) log.info('Deleted %s IAM role.', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s IAM role.', name) return False def profile_associated(role_name, profile_name, region, key, keyid, profile): ''' Check to see if an instance profile is associated with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.profile_associated myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # The IAM module of boto doesn't return objects. Instead you need to grab # values through its properties. Sigh. try: profiles = conn.list_instance_profiles_for_role(role_name) except boto.exception.BotoServerError as e: log.debug(e) return False profiles = profiles.list_instance_profiles_for_role_response profiles = profiles.list_instance_profiles_for_role_result profiles = profiles.instance_profiles for profile in profiles: if profile.instance_profile_name == profile_name: return True return False def associate_profile_to_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Associate an instance profile with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.associate_profile_to_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if associated: return True else: try: conn.add_role_to_instance_profile(profile_name, role_name) log.info('Added %s instance profile to IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add %s instance profile to IAM role %s', profile_name, role_name) return False def disassociate_profile_from_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Disassociate an instance profile from an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.disassociate_profile_from_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if not associated: return True else: try: conn.remove_role_from_instance_profile(profile_name, role_name) log.info('Removed %s instance profile from IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove %s instance profile from IAM role %s.', profile_name, role_name) return False def list_role_policies(role_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_role_policies myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_role_policies(role_name) _list = response.list_role_policies_response.list_role_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def get_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.get_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: _policy = conn.get_role_policy(role_name, policy_name) # I _hate_ you for not giving me an object boto. _policy = _policy.get_role_policy_response.policy_document # Policy is url encoded _policy = _unquote(_policy) _policy = salt.utils.json.loads(_policy, object_pairs_hook=odict.OrderedDict) return _policy except boto.exception.BotoServerError: return {} def create_role_policy(role_name, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Create or modify a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role_policy myirole mypolicy '{"MyPolicy": "Statement": [{"Action": ["sqs:*"], "Effect": "Allow", "Resource": ["arn:aws:sqs:*:*:*"], "Sid": "MyPolicySqs1"}]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) mode = 'create' if _policy: if _policy == policy: return True mode = 'modify' if isinstance(policy, six.string_types): policy = salt.utils.json.loads(policy, object_pairs_hook=odict.OrderedDict) try: _policy = salt.utils.json.dumps(policy) conn.put_role_policy(role_name, policy_name, _policy) if mode == 'create': msg = 'Successfully added policy %s to IAM role %s.' else: msg = 'Successfully modified policy %s for IAM role %s.' log.info(msg, policy_name, role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to %s policy %s for IAM role %s.', mode, policy_name, role_name) return False def delete_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) if not _policy: return True try: conn.delete_role_policy(role_name, policy_name) log.info('Successfully deleted policy %s for IAM role %s.', policy_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM role %s.', policy_name, role_name) return False def update_assume_role_policy(role_name, policy_document, region=None, key=None, keyid=None, profile=None): ''' Update an assume role policy for a role. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_assume_role_policy myrole '{"Statement":"..."}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(policy_document, six.string_types): policy_document = salt.utils.json.loads(policy_document, object_pairs_hook=odict.OrderedDict) try: _policy_document = salt.utils.json.dumps(policy_document) conn.update_assume_role_policy(role_name, _policy_document) log.info('Successfully updated assume role policy for IAM role %s.', role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to update assume role policy for IAM role %s.', role_name) return False def build_policy(region=None, key=None, keyid=None, profile=None): ''' Build a default assume role policy. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.build_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if hasattr(conn, 'build_policy'): policy = salt.utils.json.loads(conn.build_policy()) elif hasattr(conn, '_build_policy'): policy = salt.utils.json.loads(conn._build_policy()) else: return {} # The format we get from build_policy isn't going to be what we get back # from AWS for the exact same policy. AWS converts single item list values # into strings, so let's do the same here. for key, policy_val in policy.items(): for statement in policy_val: if (isinstance(statement['Action'], list) and len(statement['Action']) == 1): statement['Action'] = statement['Action'][0] if (isinstance(statement['Principal']['Service'], list) and len(statement['Principal']['Service']) == 1): statement['Principal']['Service'] = statement['Principal']['Service'][0] # build_policy doesn't add a version field, which AWS is going to set to a # default value, when we get it back, so let's set it. policy['Version'] = '2008-10-17' return policy def get_account_id(region=None, key=None, keyid=None, profile=None): ''' Get a the AWS account id associated with the used credentials. CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_id ''' cache_key = 'boto_iam.account_id' if cache_key not in __context__: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_user() # The get_user call returns an user ARN: # arn:aws:iam::027050522557:user/salt-test arn = ret['get_user_response']['get_user_result']['user']['arn'] account_id = arn.split(':')[4] except boto.exception.BotoServerError: # If call failed, then let's try to get the ARN from the metadata timeout = boto.config.getfloat( 'Boto', 'metadata_service_timeout', 1.0 ) attempts = boto.config.getint( 'Boto', 'metadata_service_num_attempts', 1 ) identity = boto.utils.get_instance_identity( timeout=timeout, num_retries=attempts ) try: account_id = identity['document']['accountId'] except KeyError: log.error('Failed to get account id from instance_identity in' ' boto_iam.get_account_id.') __context__[cache_key] = account_id return __context__[cache_key] def get_all_roles(path_prefix=None, region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM role details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_roles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _roles = conn.list_roles(path_prefix=path_prefix) roles = _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) while marker: _roles = conn.list_roles(path_prefix=path_prefix, marker=marker) roles = roles + _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) return roles def get_all_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM user details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_users ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _users = conn.get_all_users(path_prefix=path_prefix) users = _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) while marker: _users = conn.get_all_users(path_prefix=path_prefix, marker=marker) users = users + _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) return users def get_all_user_policies(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all user policies. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_user_policies myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_all_user_policies(user_name, marker, max_items) if not info: return False _list = info.list_user_policies_response.list_user_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policies for user %s.', user_name) return False def get_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user_policy myuser mypolicyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user_policy(user_name, policy_name) log.debug('Info for IAM user %s policy %s: %s.', user_name, policy_name, info) if not info: return False info = info.get_user_policy_response.get_user_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policy %s for IAM user %s.', policy_name, user_name) return False def put_user_policy(user_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_user_policy myuser policyname policyrules ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_user_policy(user_name, policy_name, policy_json) if created: log.info('Created policy %s for IAM user %s.', policy_name, user_name) return True log.error('Could not create policy %s for IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy %s for IAM user %s.', policy_name, user_name) return False def delete_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user_policy myuser mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_user_policy( user_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_user_policy(user_name, policy_name) log.info('Successfully deleted policy %s for IAM user %s.', policy_name, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM user %s.', policy_name, user_name) return False def upload_server_cert(cert_name, cert_body, private_key, cert_chain=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Upload a certificate to Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.upload_server_cert mycert_name crt priv_key :param cert_name: The name for the server certificate. Do not include the path in this value. :param cert_body: The contents of the public key certificate in PEM-encoded format. :param private_key: The contents of the private key in PEM-encoded format. :param cert_chain: The contents of the certificate chain. This is typically a concatenation of the PEM-encoded public key certificates of the chain. :param path: The path for the server certificate. :param region: The name of the region to connect to. :param key: The key to be used in order to connect :param keyid: The keyid to be used in order to connect :param profile: The profile that contains a dict of region, key, keyid :return: True / False ''' exists = get_server_certificate(cert_name, region, key, keyid, profile) if exists: return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.upload_server_cert(cert_name, cert_body, private_key, cert_chain) log.info('Created certificate %s.', cert_name) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to failed to create certificate %s.', cert_name) return False def list_server_certificates(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Lists the server certificates stored in IAM that have the specified path prefix. .. versionadded:: ??? :param path_prefix: The path prefix for filtering the results. For example: /company/servercerts would get all server certificates for which the path starts with /company/servercerts . This parameter is optional. If it is not included, it defaults to a slash (/), listing all server certificates. This parameter allows (per its regex pattern) a string of characters consisting of either a forward slash (/) by itself or a string that must begin and end with forward slashes. In addition, it can contain any ASCII character from the ! (u0021) through the DEL character (u007F), including most punctuation characters, digits, and upper and lowercased letters. CLI Example: .. code-block:: bash salt myminion boto_iam.list_server_certificates path_prefix=/somepath/ ''' retries = 10 sleep = 6 conn = __utils__['boto3.get_connection']('iam', region=region, key=key, keyid=keyid, profile=profile) Items = [] while retries: try: log.debug('Garnering list of IAM Server Certificates') IsTruncated = True while IsTruncated: kwargs = {'PathPrefix': path_prefix} ret = conn.list_server_certificates(**kwargs) Items += ret.get('ServerCertificateMetadataList', []) IsTruncated = ret.get('IsTruncated') kwargs.update({'Marker': ret.get('Marker')}) return Items except botocore.exceptions.ParamValidationError as err: raise SaltInvocationError(str(err)) except botocore.exceptions.ClientError as err: if retries and jmespath.search('Error.Code', err.response) == 'Throttling': retries -= 1 log.debug('Throttled by AWS API, retrying in %s seconds...', sleep) time.sleep(sleep) continue log.error('Failed to list IAM Server Certificates: %s', err.message) return None def get_server_certificate(cert_name, region=None, key=None, keyid=None, profile=None): ''' Returns certificate information from Amazon .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_server_certificate mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_server_certificate(cert_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get certificate %s information.', cert_name) return False def delete_server_cert(cert_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a certificate from Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_server_cert mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_server_cert(cert_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete certificate %s.', cert_name) return False def export_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM user details. Produces results that can be used to create an sls file. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.export_users --out=txt | sed "s/local: //" > iam_users.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() users = get_all_users(path_prefix, region, key, keyid, profile) for user in users: name = user.user_name _policies = conn.get_all_user_policies(name, max_items=100) _policies = _policies.list_user_policies_response.list_user_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_user_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_user_policy_response.get_user_policy_result.policy_document )) policies[policy_name] = _policy user_sls = [] user_sls.append({"name": name}) user_sls.append({"policies": policies}) user_sls.append({"path": user.path}) results["manage user " + name] = {"boto_iam.user_present": user_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def export_roles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM role details. Produces results that can be used to create an sls file. CLI Example: salt-call boto_iam.export_roles --out=txt | sed "s/local: //" > iam_roles.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() roles = get_all_roles(path_prefix, region, key, keyid, profile) for role in roles: name = role.role_name _policies = conn.list_role_policies(name, max_items=100) _policies = _policies.list_role_policies_response.list_role_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_role_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_role_policy_response.get_role_policy_result.policy_document )) policies[policy_name] = _policy role_sls = [] role_sls.append({"name": name}) role_sls.append({"policies": policies}) role_sls.append({'policy_document': salt.utils.json.loads(_unquote(role.assume_role_policy_document))}) role_sls.append({"path": role.path}) results["manage role " + name] = {"boto_iam_role.present": role_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def _get_policy_arn(name, region=None, key=None, keyid=None, profile=None): if name.startswith('arn:aws:iam:'): return name account_id = get_account_id( region=region, key=key, keyid=keyid, profile=profile ) return 'arn:aws:iam::{0}:policy/{1}'.format(account_id, name) def policy_exists(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return True except boto.exception.BotoServerError: return False def create_policy(policy_name, policy_document, path=None, description=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in 'path', 'description': if locals()[arg] is not None: params[arg] = locals()[arg] if policy_exists(policy_name, region, key, keyid, profile): return True try: conn.create_policy(policy_name, policy_document, **params) log.info('Created IAM policy %s.', policy_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s.', policy_name) return False return True def delete_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_exists(policy_arn, region, key, keyid, profile): return True try: conn.delete_policy(policy_arn) log.info('Deleted %s policy.', policy_name) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete %s policy: %s.', policy_name, aws.get('message')) return False return True def list_policies(region=None, key=None, keyid=None, profile=None): ''' List policies. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policies ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: policies = [] for ret in __utils__['boto.paged_call'](conn.list_policies): policies.append(ret.get('list_policies_response', {}).get('list_policies_result', {}).get('policies')) return policies except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to list policy versions.' log.error(msg) return [] def policy_version_exists(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.get_policy_version(policy_arn, version_id) return True except boto.exception.BotoServerError: return False def get_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy_version(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile), version_id) retval = ret.get('get_policy_version_response', {}).get('get_policy_version_result', {}).get('policy_version', {}) retval['document'] = _unquote(retval.get('document')) return {'policy_version': retval} except boto.exception.BotoServerError: return None def create_policy_version(policy_name, policy_document, set_as_default=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy version. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy_version mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in ('set_as_default',): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.create_policy_version(policy_arn, policy_document, **params) vid = ret.get('create_policy_version_response', {}).get('create_policy_version_result', {}).get('policy_version', {}).get('version_id') log.info('Created IAM policy %s version %s.', policy_name, vid) return {'created': True, 'version_id': vid} except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s version %s.', policy_name, vid) return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Delete a policy version. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_version_exists(policy_arn, version_id, region, key, keyid, profile): return True try: conn.delete_policy_version(policy_arn, version_id) log.info('Deleted IAM policy %s version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete IAM policy %s version %s: %s', policy_name, version_id, aws.get('message')) return False return True def list_policy_versions(policy_name, region=None, key=None, keyid=None, profile=None): ''' List versions of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policy_versions mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.list_policy_versions(policy_arn) return ret.get('list_policy_versions_response', {}).get('list_policy_versions_result', {}).get('versions') except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list versions for IAM policy %s.', policy_name) return [] def set_default_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Set the default version of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.set_default_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.set_default_policy_version(policy_arn, version_id) log.info('Set %s policy to version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to set %s policy to version %s: %s', policy_name, version_id, aws.get('message')) return False return True def attach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_user_policy(policy_arn, user_name) log.info('Attached policy %s to IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach %s policy to IAM user %s.', policy_name, user_name) return False return True def detach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_user_policy(policy_arn, user_name) log.info('Detached %s policy from IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach %s policy from IAM user %s.', policy_name, user_name) return False return True def attach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_group_policy(policy_arn, group_name) log.info('Attached policy %s to IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM group %s.', policy_name, group_name) return False return True def detach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_group_policy(policy_arn, group_name) log.info('Detached policy %s from IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM group %s.', policy_name, group_name) return False return True def attach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_role_policy(policy_arn, role_name) log.info('Attached policy %s to IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM role %s.', policy_name, role_name) return False return True def detach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_role_policy(policy_arn, role_name) log.info('Detached policy %s from IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM role %s.', policy_name, role_name) return False return True def list_entities_for_policy(policy_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities that a policy is attached to. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 params = {} for arg in ('path_prefix', 'entity_filter'): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) while retries: try: allret = { 'policy_groups': [], 'policy_users': [], 'policy_roles': [], } for ret in __utils__['boto.paged_call'](conn.list_entities_for_policy, policy_arn=policy_arn, **params): for k, v in six.iteritems(allret): v.extend(ret.get('list_entities_for_policy_response', {}).get('list_entities_for_policy_result', {}).get(k)) return allret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('Failed to list entities for IAM policy %s: %s', policy_name, e.message) return {} return {} def list_attached_user_policies(user_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given user. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'UserName': user_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedUserPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_user_policies_response', {}).get('list_attached_user_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM user %s.', user_name) return [] def list_attached_group_policies(group_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given group. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'GroupName': group_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedGroupPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_group_policies_response', {}).get('list_attached_group_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM group %s.', group_name) return [] def list_attached_role_policies(role_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'RoleName': role_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedRolePolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_role_policies_response', {}).get('list_attached_role_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM role %s.', role_name) return [] def create_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Create SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.create_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_saml_provider(saml_metadata_document, name) log.info('Successfully created %s SAML provider.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to create SAML provider %s.', name) return False def get_saml_provider_arn(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider_arn my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_saml_providers() for saml_provider in response.list_saml_providers_response.list_saml_providers_result.saml_provider_list: if saml_provider['arn'].endswith(':saml-provider/' + name): return saml_provider['arn'] return False except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to get ARN of SAML provider %s.', name) return False def delete_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Delete SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.delete_saml_provider my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return True conn.delete_saml_provider(saml_provider_arn) log.info('Successfully deleted SAML provider %s.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete SAML provider %s.', name) return False def list_saml_providers(region=None, key=None, keyid=None, profile=None): ''' List SAML providers. CLI Example: .. code-block:: bash salt myminion boto_iam.list_saml_providers ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: providers = [] info = conn.list_saml_providers() for arn in info['list_saml_providers_response']['list_saml_providers_result']['saml_provider_list']: providers.append(arn['arn'].rsplit('/', 1)[1]) return providers except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get list of SAML providers.') return False def get_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider document. CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider arn ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: provider = conn.get_saml_provider(name) return provider['get_saml_provider_response']['get_saml_provider_result']['saml_metadata_document'] except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get SAML provider document %s.', name) return False def update_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Update SAML provider. CLI Example: .. code-block:: bash salt myminion boto_iam.update_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return False if conn.update_saml_provider(name, saml_metadata_document): return True return False except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to update SAML provider %s.', name) return False
saltstack/salt
salt/modules/boto_iam.py
create_policy
python
def create_policy(policy_name, policy_document, path=None, description=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in 'path', 'description': if locals()[arg] is not None: params[arg] = locals()[arg] if policy_exists(policy_name, region, key, keyid, profile): return True try: conn.create_policy(policy_name, policy_document, **params) log.info('Created IAM policy %s.', policy_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s.', policy_name) return False return True
Create a policy. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iam.py#L1748-L1776
[ "def dumps(obj, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.dumps, and assumes that ensure_ascii is False (unless explicitly\n passed as True) for unicode compatibility. Note that setting it to True\n will mess up any unicode characters, as they will be dumped as the string\n literal version of the unicode code point.\n\n On Python 2, encodes the result to a str since json.dumps does not want\n unicode types.\n\n You can pass an alternate json module (loaded via import_json() above)\n using the _json_module argument)\n '''\n json_module = kwargs.pop('_json_module', json)\n orig_enc_func = kwargs.pop('default', lambda x: x)\n\n def _enc_func(obj):\n obj = ThreadLocalProxy.unproxy(obj)\n return orig_enc_func(obj)\n\n if 'ensure_ascii' not in kwargs:\n kwargs['ensure_ascii'] = False\n if six.PY2:\n obj = salt.utils.data.encode(obj)\n return json_module.dumps(obj, default=_enc_func, **kwargs) # future lint: blacklisted-function\n", "def policy_exists(policy_name,\n region=None, key=None, keyid=None, profile=None):\n '''\n Check to see if policy exists.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_iam.instance_profile_exists myiprofile\n '''\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n\n try:\n conn.get_policy(_get_policy_arn(policy_name,\n region=region, key=key, keyid=keyid, profile=profile))\n return True\n except boto.exception.BotoServerError:\n return False\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon IAM .. versionadded:: 2014.7.0 :configuration: This module accepts explicit iam 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 iam.keyid: GKTADJGHEIQSXMKKRBJ08H iam.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs iam.region: 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: boto ''' # keep lint from choking on _get_conn and _cache_id #pylint: disable=E0602 # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import salt libs from salt.ext import six import salt.utils.compat import salt.utils.json import salt.utils.odict as odict import salt.utils.versions from salt.exceptions import SaltInvocationError # Import third party libs # pylint: disable=unused-import from salt.ext.six.moves.urllib.parse import unquote as _unquote # pylint: disable=no-name-in-module try: import boto import boto.iam import boto3 import botocore logging.getLogger('boto').setLevel(logging.CRITICAL) logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=unused-import log = logging.getLogger(__name__) def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'iam', pack=__salt__) def instance_profile_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an instance profile exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: # Boto weirdly returns an exception here if an instance profile doesn't # exist. conn.get_instance_profile(name) return True except boto.exception.BotoServerError: return False def create_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Create an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.create_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if instance_profile_exists(name, region, key, keyid, profile): return True try: # This call returns an instance profile if successful and an exception # if not. It's annoying. conn.create_instance_profile(name) log.info('Created %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create %s instance profile.', name) return False return True def delete_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Delete an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not instance_profile_exists(name, region, key, keyid, profile): return True try: conn.delete_instance_profile(name) log.info('Deleted %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s instance profile.', name) return False return True def role_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an IAM role exists. CLI Example: .. code-block:: bash salt myminion boto_iam.role_exists myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_role(name) return True except boto.exception.BotoServerError: return False def describe_role(name, region=None, key=None, keyid=None, profile=None): ''' Get information for a role. CLI Example: .. code-block:: bash salt myminion boto_iam.describe_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_role(name) if not info: return False role = info.get_role_response.get_role_result.role role['assume_role_policy_document'] = salt.utils.json.loads(_unquote( role.assume_role_policy_document )) # If Sid wasn't defined by the user, boto will still return a Sid in # each policy. To properly check idempotently, let's remove the Sid # from the return if it's not actually set. for policy_key, policy in role['assume_role_policy_document'].items(): if policy_key == 'Statement': for val in policy: if 'Sid' in val and not val['Sid']: del val['Sid'] return role except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get %s information.', name) return False def create_user(user_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_user myuser ''' if not path: path = '/' if get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_user(user_name, path) log.info('Created IAM user : %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM user %s.', user_name) return False def get_all_access_keys(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all access keys from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_access_keys myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.get_all_access_keys(user_name, marker, max_items) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get access keys for IAM user %s.', user_name) return six.text_type(e) def create_access_key(user_name, region=None, key=None, keyid=None, profile=None): ''' Create access key id for a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.create_access_key(user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create access key.') return six.text_type(e) def delete_access_key(access_key_id, user_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete access key id from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_access_key(access_key_id, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete access key id %s.', access_key_id) return six.text_type(e) def delete_user(user_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user myuser ''' if not get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.delete_user(user_name) log.info('Deleted IAM user : %s .', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM user %s', user_name) return six.text_type(e) def get_user(user_name=None, region=None, key=None, keyid=None, profile=None): ''' Get user information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user(user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM user %s info.', user_name) return False def create_group(group_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_group group ''' if not path: path = '/' if get_group(group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_group(group_name, path) log.info('Created IAM group : %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM group %s.', group_name) return False def get_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group(group_name, max_items=1) if not info: return False return info['get_group_response']['get_group_result']['group'] except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_group_members(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: marker = None truncated = True users = [] while truncated: info = conn.get_group(group_name, marker=marker, max_items=1000) if not info: return False truncated = bool(info['get_group_response']['get_group_result']['is_truncated']) if truncated and 'marker' in info['get_group_response']['get_group_result']: marker = info['get_group_response']['get_group_result']['marker'] else: marker = None truncated = False users += info['get_group_response']['get_group_result']['users'] return users except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get members for IAM group %s.', group_name) return False def add_user_to_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Add user to group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.add_user_to_group myuser mygroup ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('Username : %s does not exist.', user_name) return False if user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.add_user_to_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add IAM user %s to group %s.', user_name, group_name) return False def user_exists_in_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Check if user exists in group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.user_exists_in_group myuser mygroup ''' # TODO this should probably use boto.iam.get_groups_for_user users = get_group_members( group_name=group_name, region=region, key=key, keyid=keyid, profile=profile ) if users: for _user in users: if user_name == _user['user_name']: log.debug('IAM user %s is already in IAM group %s.', user_name, group_name) return True return False def remove_user_from_group(group_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Remove user from group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.remove_user_from_group mygroup myuser ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist.', user_name) return False if not user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.remove_user_from_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove IAM user %s from group %s', user_name, group_name) return False def put_group_policy(group_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_group_policy mygroup policyname policyrules ''' group = get_group(group_name, region=region, key=key, keyid=keyid, profile=profile) if not group: log.error('Group %s does not exist', group_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_group_policy(group_name, policy_name, policy_json) if created: log.info('Created policy for IAM group %s.', group_name) return True log.error('Could not create policy for IAM group %s', group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy for IAM group %s', group_name) return False def delete_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group_policy mygroup mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_group_policy( group_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_group_policy(group_name, policy_name) log.info('Successfully deleted policy %s for IAM group %s.', policy_name, group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM group %s.', policy_name, group_name) return False def get_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group_policy mygroup policyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group_policy(group_name, policy_name) log.debug('info for group policy is : %s', info) if not info: return False info = info.get_group_policy_response.get_group_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_all_groups(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM group details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_groups ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _groups = conn.get_all_groups(path_prefix=path_prefix) groups = _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) while marker: _groups = conn.get_all_groups(path_prefix=path_prefix, marker=marker) groups = groups + _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) return groups def get_all_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.get_all_instance_profiles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) marker = False profiles = [] while marker is not None: marker = marker if marker else None p = conn.list_instance_profiles(path_prefix=path_prefix, marker=marker) res = p.list_instance_profiles_response.list_instance_profiles_result profiles += res.instance_profiles marker = getattr(res, 'marker', None) return profiles def list_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' List all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.list_instance_profiles ''' p = get_all_instance_profiles(path_prefix, region, key, keyid, profile) return [i['instance_profile_name'] for i in p] def get_all_group_policies(group_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a group. CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_group_policies mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False try: response = conn.get_all_group_policies(group_name) _list = response.list_group_policies_response.list_group_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def delete_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _group = get_group( group_name, region, key, keyid, profile ) if not _group: return True try: conn.delete_group(group_name) log.info('Successfully deleted IAM group %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM group %s.', group_name) return False def create_login_profile(user_name, password, region=None, key=None, keyid=None, profile=None): ''' Creates a login profile for the specified user, give the user the ability to access AWS services and the AWS Management Console. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_login_profile user_name password ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.create_login_profile(user_name, password) log.info('Created profile for IAM user %s.', user_name) return info except boto.exception.BotoServerError as e: log.debug(e) if 'Conflict' in e: log.info('Profile already exists for IAM user %s.', user_name) return 'Conflict' log.error('Failed to update profile for IAM user %s.', user_name) return False def delete_login_profile(user_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a login profile for the specified user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_login_profile user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.delete_login_profile(user_name) log.info('Deleted login profile for IAM user %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Login profile already deleted for IAM user %s.', user_name) return True log.error('Failed to delete login profile for IAM user %s.', user_name) return False def get_all_mfa_devices(user_name, region=None, key=None, keyid=None, profile=None): ''' Get all MFA devices associated with an IAM user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_mfa_devices user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: result = conn.get_all_mfa_devices(user_name) devices = result['list_mfa_devices_response']['list_mfa_devices_result']['mfa_devices'] return devices except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Could not find IAM user %s.', user_name) return [] log.error('Failed to get all MFA devices for IAM user %s.', user_name) return False def deactivate_mfa_device(user_name, serial, region=None, key=None, keyid=None, profile=None): ''' Deactivates the specified MFA device and removes it from association with the user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.deactivate_mfa_device user_name serial_num ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.deactivate_mfa_device(user_name, serial) log.info('Deactivated MFA device %s for IAM user %s.', serial, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('MFA device %s not associated with IAM user %s.', serial, user_name) return True log.error('Failed to deactivate MFA device %s for IAM user %s.', serial, user_name) return False def delete_virtual_mfa_device(serial, region=None, key=None, keyid=None, profile=None): ''' Deletes the specified virtual MFA device. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_virtual_mfa_device serial_num ''' conn = __utils__['boto3.get_connection_func']('iam')() try: conn.delete_virtual_mfa_device(SerialNumber=serial) log.info('Deleted virtual MFA device %s.', serial) return True except botocore.exceptions.ClientError as e: log.debug(e) if 'NoSuchEntity' in six.text_type(e): log.info('Virtual MFA device %s not found.', serial) return True log.error('Failed to delete virtual MFA device %s.', serial) return False def update_account_password_policy(allow_users_to_change_password=None, hard_expiry=None, max_password_age=None, minimum_password_length=None, password_reuse_prevention=None, require_lowercase_characters=None, require_numbers=None, require_symbols=None, require_uppercase_characters=None, region=None, key=None, keyid=None, profile=None): ''' Update the password policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_account_password_policy True ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.update_account_password_policy(allow_users_to_change_password, hard_expiry, max_password_age, minimum_password_length, password_reuse_prevention, require_lowercase_characters, require_numbers, require_symbols, require_uppercase_characters) log.info('The password policy has been updated.') return True except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy' log.error(msg) return False def get_account_policy(region=None, key=None, keyid=None, profile=None): ''' Get account policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_account_password_policy() return info.get_account_password_policy_response.get_account_password_policy_result.password_policy except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy.' log.error(msg) return False def create_role(name, policy_document=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Create an instance role. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if role_exists(name, region, key, keyid, profile): return True if not policy_document: policy_document = None try: conn.create_role(name, assume_role_policy_document=policy_document, path=path) log.info('Created IAM role %s.', name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to create IAM role %s.', name) return False def delete_role(name, region=None, key=None, keyid=None, profile=None): ''' Delete an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(name, region, key, keyid, profile): return True try: conn.delete_role(name) log.info('Deleted %s IAM role.', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s IAM role.', name) return False def profile_associated(role_name, profile_name, region, key, keyid, profile): ''' Check to see if an instance profile is associated with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.profile_associated myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # The IAM module of boto doesn't return objects. Instead you need to grab # values through its properties. Sigh. try: profiles = conn.list_instance_profiles_for_role(role_name) except boto.exception.BotoServerError as e: log.debug(e) return False profiles = profiles.list_instance_profiles_for_role_response profiles = profiles.list_instance_profiles_for_role_result profiles = profiles.instance_profiles for profile in profiles: if profile.instance_profile_name == profile_name: return True return False def associate_profile_to_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Associate an instance profile with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.associate_profile_to_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if associated: return True else: try: conn.add_role_to_instance_profile(profile_name, role_name) log.info('Added %s instance profile to IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add %s instance profile to IAM role %s', profile_name, role_name) return False def disassociate_profile_from_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Disassociate an instance profile from an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.disassociate_profile_from_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if not associated: return True else: try: conn.remove_role_from_instance_profile(profile_name, role_name) log.info('Removed %s instance profile from IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove %s instance profile from IAM role %s.', profile_name, role_name) return False def list_role_policies(role_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_role_policies myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_role_policies(role_name) _list = response.list_role_policies_response.list_role_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def get_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.get_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: _policy = conn.get_role_policy(role_name, policy_name) # I _hate_ you for not giving me an object boto. _policy = _policy.get_role_policy_response.policy_document # Policy is url encoded _policy = _unquote(_policy) _policy = salt.utils.json.loads(_policy, object_pairs_hook=odict.OrderedDict) return _policy except boto.exception.BotoServerError: return {} def create_role_policy(role_name, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Create or modify a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role_policy myirole mypolicy '{"MyPolicy": "Statement": [{"Action": ["sqs:*"], "Effect": "Allow", "Resource": ["arn:aws:sqs:*:*:*"], "Sid": "MyPolicySqs1"}]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) mode = 'create' if _policy: if _policy == policy: return True mode = 'modify' if isinstance(policy, six.string_types): policy = salt.utils.json.loads(policy, object_pairs_hook=odict.OrderedDict) try: _policy = salt.utils.json.dumps(policy) conn.put_role_policy(role_name, policy_name, _policy) if mode == 'create': msg = 'Successfully added policy %s to IAM role %s.' else: msg = 'Successfully modified policy %s for IAM role %s.' log.info(msg, policy_name, role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to %s policy %s for IAM role %s.', mode, policy_name, role_name) return False def delete_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) if not _policy: return True try: conn.delete_role_policy(role_name, policy_name) log.info('Successfully deleted policy %s for IAM role %s.', policy_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM role %s.', policy_name, role_name) return False def update_assume_role_policy(role_name, policy_document, region=None, key=None, keyid=None, profile=None): ''' Update an assume role policy for a role. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_assume_role_policy myrole '{"Statement":"..."}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(policy_document, six.string_types): policy_document = salt.utils.json.loads(policy_document, object_pairs_hook=odict.OrderedDict) try: _policy_document = salt.utils.json.dumps(policy_document) conn.update_assume_role_policy(role_name, _policy_document) log.info('Successfully updated assume role policy for IAM role %s.', role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to update assume role policy for IAM role %s.', role_name) return False def build_policy(region=None, key=None, keyid=None, profile=None): ''' Build a default assume role policy. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.build_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if hasattr(conn, 'build_policy'): policy = salt.utils.json.loads(conn.build_policy()) elif hasattr(conn, '_build_policy'): policy = salt.utils.json.loads(conn._build_policy()) else: return {} # The format we get from build_policy isn't going to be what we get back # from AWS for the exact same policy. AWS converts single item list values # into strings, so let's do the same here. for key, policy_val in policy.items(): for statement in policy_val: if (isinstance(statement['Action'], list) and len(statement['Action']) == 1): statement['Action'] = statement['Action'][0] if (isinstance(statement['Principal']['Service'], list) and len(statement['Principal']['Service']) == 1): statement['Principal']['Service'] = statement['Principal']['Service'][0] # build_policy doesn't add a version field, which AWS is going to set to a # default value, when we get it back, so let's set it. policy['Version'] = '2008-10-17' return policy def get_account_id(region=None, key=None, keyid=None, profile=None): ''' Get a the AWS account id associated with the used credentials. CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_id ''' cache_key = 'boto_iam.account_id' if cache_key not in __context__: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_user() # The get_user call returns an user ARN: # arn:aws:iam::027050522557:user/salt-test arn = ret['get_user_response']['get_user_result']['user']['arn'] account_id = arn.split(':')[4] except boto.exception.BotoServerError: # If call failed, then let's try to get the ARN from the metadata timeout = boto.config.getfloat( 'Boto', 'metadata_service_timeout', 1.0 ) attempts = boto.config.getint( 'Boto', 'metadata_service_num_attempts', 1 ) identity = boto.utils.get_instance_identity( timeout=timeout, num_retries=attempts ) try: account_id = identity['document']['accountId'] except KeyError: log.error('Failed to get account id from instance_identity in' ' boto_iam.get_account_id.') __context__[cache_key] = account_id return __context__[cache_key] def get_all_roles(path_prefix=None, region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM role details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_roles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _roles = conn.list_roles(path_prefix=path_prefix) roles = _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) while marker: _roles = conn.list_roles(path_prefix=path_prefix, marker=marker) roles = roles + _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) return roles def get_all_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM user details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_users ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _users = conn.get_all_users(path_prefix=path_prefix) users = _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) while marker: _users = conn.get_all_users(path_prefix=path_prefix, marker=marker) users = users + _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) return users def get_all_user_policies(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all user policies. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_user_policies myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_all_user_policies(user_name, marker, max_items) if not info: return False _list = info.list_user_policies_response.list_user_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policies for user %s.', user_name) return False def get_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user_policy myuser mypolicyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user_policy(user_name, policy_name) log.debug('Info for IAM user %s policy %s: %s.', user_name, policy_name, info) if not info: return False info = info.get_user_policy_response.get_user_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policy %s for IAM user %s.', policy_name, user_name) return False def put_user_policy(user_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_user_policy myuser policyname policyrules ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_user_policy(user_name, policy_name, policy_json) if created: log.info('Created policy %s for IAM user %s.', policy_name, user_name) return True log.error('Could not create policy %s for IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy %s for IAM user %s.', policy_name, user_name) return False def delete_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user_policy myuser mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_user_policy( user_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_user_policy(user_name, policy_name) log.info('Successfully deleted policy %s for IAM user %s.', policy_name, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM user %s.', policy_name, user_name) return False def upload_server_cert(cert_name, cert_body, private_key, cert_chain=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Upload a certificate to Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.upload_server_cert mycert_name crt priv_key :param cert_name: The name for the server certificate. Do not include the path in this value. :param cert_body: The contents of the public key certificate in PEM-encoded format. :param private_key: The contents of the private key in PEM-encoded format. :param cert_chain: The contents of the certificate chain. This is typically a concatenation of the PEM-encoded public key certificates of the chain. :param path: The path for the server certificate. :param region: The name of the region to connect to. :param key: The key to be used in order to connect :param keyid: The keyid to be used in order to connect :param profile: The profile that contains a dict of region, key, keyid :return: True / False ''' exists = get_server_certificate(cert_name, region, key, keyid, profile) if exists: return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.upload_server_cert(cert_name, cert_body, private_key, cert_chain) log.info('Created certificate %s.', cert_name) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to failed to create certificate %s.', cert_name) return False def list_server_certificates(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Lists the server certificates stored in IAM that have the specified path prefix. .. versionadded:: ??? :param path_prefix: The path prefix for filtering the results. For example: /company/servercerts would get all server certificates for which the path starts with /company/servercerts . This parameter is optional. If it is not included, it defaults to a slash (/), listing all server certificates. This parameter allows (per its regex pattern) a string of characters consisting of either a forward slash (/) by itself or a string that must begin and end with forward slashes. In addition, it can contain any ASCII character from the ! (u0021) through the DEL character (u007F), including most punctuation characters, digits, and upper and lowercased letters. CLI Example: .. code-block:: bash salt myminion boto_iam.list_server_certificates path_prefix=/somepath/ ''' retries = 10 sleep = 6 conn = __utils__['boto3.get_connection']('iam', region=region, key=key, keyid=keyid, profile=profile) Items = [] while retries: try: log.debug('Garnering list of IAM Server Certificates') IsTruncated = True while IsTruncated: kwargs = {'PathPrefix': path_prefix} ret = conn.list_server_certificates(**kwargs) Items += ret.get('ServerCertificateMetadataList', []) IsTruncated = ret.get('IsTruncated') kwargs.update({'Marker': ret.get('Marker')}) return Items except botocore.exceptions.ParamValidationError as err: raise SaltInvocationError(str(err)) except botocore.exceptions.ClientError as err: if retries and jmespath.search('Error.Code', err.response) == 'Throttling': retries -= 1 log.debug('Throttled by AWS API, retrying in %s seconds...', sleep) time.sleep(sleep) continue log.error('Failed to list IAM Server Certificates: %s', err.message) return None def get_server_certificate(cert_name, region=None, key=None, keyid=None, profile=None): ''' Returns certificate information from Amazon .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_server_certificate mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_server_certificate(cert_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get certificate %s information.', cert_name) return False def delete_server_cert(cert_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a certificate from Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_server_cert mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_server_cert(cert_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete certificate %s.', cert_name) return False def export_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM user details. Produces results that can be used to create an sls file. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.export_users --out=txt | sed "s/local: //" > iam_users.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() users = get_all_users(path_prefix, region, key, keyid, profile) for user in users: name = user.user_name _policies = conn.get_all_user_policies(name, max_items=100) _policies = _policies.list_user_policies_response.list_user_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_user_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_user_policy_response.get_user_policy_result.policy_document )) policies[policy_name] = _policy user_sls = [] user_sls.append({"name": name}) user_sls.append({"policies": policies}) user_sls.append({"path": user.path}) results["manage user " + name] = {"boto_iam.user_present": user_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def export_roles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM role details. Produces results that can be used to create an sls file. CLI Example: salt-call boto_iam.export_roles --out=txt | sed "s/local: //" > iam_roles.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() roles = get_all_roles(path_prefix, region, key, keyid, profile) for role in roles: name = role.role_name _policies = conn.list_role_policies(name, max_items=100) _policies = _policies.list_role_policies_response.list_role_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_role_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_role_policy_response.get_role_policy_result.policy_document )) policies[policy_name] = _policy role_sls = [] role_sls.append({"name": name}) role_sls.append({"policies": policies}) role_sls.append({'policy_document': salt.utils.json.loads(_unquote(role.assume_role_policy_document))}) role_sls.append({"path": role.path}) results["manage role " + name] = {"boto_iam_role.present": role_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def _get_policy_arn(name, region=None, key=None, keyid=None, profile=None): if name.startswith('arn:aws:iam:'): return name account_id = get_account_id( region=region, key=key, keyid=keyid, profile=profile ) return 'arn:aws:iam::{0}:policy/{1}'.format(account_id, name) def policy_exists(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return True except boto.exception.BotoServerError: return False def get_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return ret.get('get_policy_response', {}).get('get_policy_result', {}) except boto.exception.BotoServerError: return None def delete_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_exists(policy_arn, region, key, keyid, profile): return True try: conn.delete_policy(policy_arn) log.info('Deleted %s policy.', policy_name) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete %s policy: %s.', policy_name, aws.get('message')) return False return True def list_policies(region=None, key=None, keyid=None, profile=None): ''' List policies. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policies ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: policies = [] for ret in __utils__['boto.paged_call'](conn.list_policies): policies.append(ret.get('list_policies_response', {}).get('list_policies_result', {}).get('policies')) return policies except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to list policy versions.' log.error(msg) return [] def policy_version_exists(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.get_policy_version(policy_arn, version_id) return True except boto.exception.BotoServerError: return False def get_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy_version(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile), version_id) retval = ret.get('get_policy_version_response', {}).get('get_policy_version_result', {}).get('policy_version', {}) retval['document'] = _unquote(retval.get('document')) return {'policy_version': retval} except boto.exception.BotoServerError: return None def create_policy_version(policy_name, policy_document, set_as_default=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy version. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy_version mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in ('set_as_default',): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.create_policy_version(policy_arn, policy_document, **params) vid = ret.get('create_policy_version_response', {}).get('create_policy_version_result', {}).get('policy_version', {}).get('version_id') log.info('Created IAM policy %s version %s.', policy_name, vid) return {'created': True, 'version_id': vid} except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s version %s.', policy_name, vid) return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Delete a policy version. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_version_exists(policy_arn, version_id, region, key, keyid, profile): return True try: conn.delete_policy_version(policy_arn, version_id) log.info('Deleted IAM policy %s version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete IAM policy %s version %s: %s', policy_name, version_id, aws.get('message')) return False return True def list_policy_versions(policy_name, region=None, key=None, keyid=None, profile=None): ''' List versions of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policy_versions mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.list_policy_versions(policy_arn) return ret.get('list_policy_versions_response', {}).get('list_policy_versions_result', {}).get('versions') except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list versions for IAM policy %s.', policy_name) return [] def set_default_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Set the default version of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.set_default_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.set_default_policy_version(policy_arn, version_id) log.info('Set %s policy to version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to set %s policy to version %s: %s', policy_name, version_id, aws.get('message')) return False return True def attach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_user_policy(policy_arn, user_name) log.info('Attached policy %s to IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach %s policy to IAM user %s.', policy_name, user_name) return False return True def detach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_user_policy(policy_arn, user_name) log.info('Detached %s policy from IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach %s policy from IAM user %s.', policy_name, user_name) return False return True def attach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_group_policy(policy_arn, group_name) log.info('Attached policy %s to IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM group %s.', policy_name, group_name) return False return True def detach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_group_policy(policy_arn, group_name) log.info('Detached policy %s from IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM group %s.', policy_name, group_name) return False return True def attach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_role_policy(policy_arn, role_name) log.info('Attached policy %s to IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM role %s.', policy_name, role_name) return False return True def detach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_role_policy(policy_arn, role_name) log.info('Detached policy %s from IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM role %s.', policy_name, role_name) return False return True def list_entities_for_policy(policy_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities that a policy is attached to. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 params = {} for arg in ('path_prefix', 'entity_filter'): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) while retries: try: allret = { 'policy_groups': [], 'policy_users': [], 'policy_roles': [], } for ret in __utils__['boto.paged_call'](conn.list_entities_for_policy, policy_arn=policy_arn, **params): for k, v in six.iteritems(allret): v.extend(ret.get('list_entities_for_policy_response', {}).get('list_entities_for_policy_result', {}).get(k)) return allret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('Failed to list entities for IAM policy %s: %s', policy_name, e.message) return {} return {} def list_attached_user_policies(user_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given user. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'UserName': user_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedUserPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_user_policies_response', {}).get('list_attached_user_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM user %s.', user_name) return [] def list_attached_group_policies(group_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given group. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'GroupName': group_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedGroupPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_group_policies_response', {}).get('list_attached_group_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM group %s.', group_name) return [] def list_attached_role_policies(role_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'RoleName': role_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedRolePolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_role_policies_response', {}).get('list_attached_role_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM role %s.', role_name) return [] def create_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Create SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.create_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_saml_provider(saml_metadata_document, name) log.info('Successfully created %s SAML provider.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to create SAML provider %s.', name) return False def get_saml_provider_arn(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider_arn my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_saml_providers() for saml_provider in response.list_saml_providers_response.list_saml_providers_result.saml_provider_list: if saml_provider['arn'].endswith(':saml-provider/' + name): return saml_provider['arn'] return False except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to get ARN of SAML provider %s.', name) return False def delete_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Delete SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.delete_saml_provider my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return True conn.delete_saml_provider(saml_provider_arn) log.info('Successfully deleted SAML provider %s.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete SAML provider %s.', name) return False def list_saml_providers(region=None, key=None, keyid=None, profile=None): ''' List SAML providers. CLI Example: .. code-block:: bash salt myminion boto_iam.list_saml_providers ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: providers = [] info = conn.list_saml_providers() for arn in info['list_saml_providers_response']['list_saml_providers_result']['saml_provider_list']: providers.append(arn['arn'].rsplit('/', 1)[1]) return providers except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get list of SAML providers.') return False def get_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider document. CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider arn ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: provider = conn.get_saml_provider(name) return provider['get_saml_provider_response']['get_saml_provider_result']['saml_metadata_document'] except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get SAML provider document %s.', name) return False def update_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Update SAML provider. CLI Example: .. code-block:: bash salt myminion boto_iam.update_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return False if conn.update_saml_provider(name, saml_metadata_document): return True return False except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to update SAML provider %s.', name) return False
saltstack/salt
salt/modules/boto_iam.py
list_policies
python
def list_policies(region=None, key=None, keyid=None, profile=None): ''' List policies. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policies ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: policies = [] for ret in __utils__['boto.paged_call'](conn.list_policies): policies.append(ret.get('list_policies_response', {}).get('list_policies_result', {}).get('policies')) return policies except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to list policy versions.' log.error(msg) return []
List policies. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policies
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iam.py#L1806-L1827
null
# -*- coding: utf-8 -*- ''' Connection module for Amazon IAM .. versionadded:: 2014.7.0 :configuration: This module accepts explicit iam 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 iam.keyid: GKTADJGHEIQSXMKKRBJ08H iam.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs iam.region: 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: boto ''' # keep lint from choking on _get_conn and _cache_id #pylint: disable=E0602 # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import salt libs from salt.ext import six import salt.utils.compat import salt.utils.json import salt.utils.odict as odict import salt.utils.versions from salt.exceptions import SaltInvocationError # Import third party libs # pylint: disable=unused-import from salt.ext.six.moves.urllib.parse import unquote as _unquote # pylint: disable=no-name-in-module try: import boto import boto.iam import boto3 import botocore logging.getLogger('boto').setLevel(logging.CRITICAL) logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=unused-import log = logging.getLogger(__name__) def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'iam', pack=__salt__) def instance_profile_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an instance profile exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: # Boto weirdly returns an exception here if an instance profile doesn't # exist. conn.get_instance_profile(name) return True except boto.exception.BotoServerError: return False def create_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Create an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.create_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if instance_profile_exists(name, region, key, keyid, profile): return True try: # This call returns an instance profile if successful and an exception # if not. It's annoying. conn.create_instance_profile(name) log.info('Created %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create %s instance profile.', name) return False return True def delete_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Delete an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not instance_profile_exists(name, region, key, keyid, profile): return True try: conn.delete_instance_profile(name) log.info('Deleted %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s instance profile.', name) return False return True def role_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an IAM role exists. CLI Example: .. code-block:: bash salt myminion boto_iam.role_exists myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_role(name) return True except boto.exception.BotoServerError: return False def describe_role(name, region=None, key=None, keyid=None, profile=None): ''' Get information for a role. CLI Example: .. code-block:: bash salt myminion boto_iam.describe_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_role(name) if not info: return False role = info.get_role_response.get_role_result.role role['assume_role_policy_document'] = salt.utils.json.loads(_unquote( role.assume_role_policy_document )) # If Sid wasn't defined by the user, boto will still return a Sid in # each policy. To properly check idempotently, let's remove the Sid # from the return if it's not actually set. for policy_key, policy in role['assume_role_policy_document'].items(): if policy_key == 'Statement': for val in policy: if 'Sid' in val and not val['Sid']: del val['Sid'] return role except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get %s information.', name) return False def create_user(user_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_user myuser ''' if not path: path = '/' if get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_user(user_name, path) log.info('Created IAM user : %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM user %s.', user_name) return False def get_all_access_keys(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all access keys from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_access_keys myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.get_all_access_keys(user_name, marker, max_items) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get access keys for IAM user %s.', user_name) return six.text_type(e) def create_access_key(user_name, region=None, key=None, keyid=None, profile=None): ''' Create access key id for a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.create_access_key(user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create access key.') return six.text_type(e) def delete_access_key(access_key_id, user_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete access key id from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_access_key(access_key_id, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete access key id %s.', access_key_id) return six.text_type(e) def delete_user(user_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user myuser ''' if not get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.delete_user(user_name) log.info('Deleted IAM user : %s .', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM user %s', user_name) return six.text_type(e) def get_user(user_name=None, region=None, key=None, keyid=None, profile=None): ''' Get user information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user(user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM user %s info.', user_name) return False def create_group(group_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_group group ''' if not path: path = '/' if get_group(group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_group(group_name, path) log.info('Created IAM group : %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM group %s.', group_name) return False def get_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group(group_name, max_items=1) if not info: return False return info['get_group_response']['get_group_result']['group'] except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_group_members(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: marker = None truncated = True users = [] while truncated: info = conn.get_group(group_name, marker=marker, max_items=1000) if not info: return False truncated = bool(info['get_group_response']['get_group_result']['is_truncated']) if truncated and 'marker' in info['get_group_response']['get_group_result']: marker = info['get_group_response']['get_group_result']['marker'] else: marker = None truncated = False users += info['get_group_response']['get_group_result']['users'] return users except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get members for IAM group %s.', group_name) return False def add_user_to_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Add user to group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.add_user_to_group myuser mygroup ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('Username : %s does not exist.', user_name) return False if user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.add_user_to_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add IAM user %s to group %s.', user_name, group_name) return False def user_exists_in_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Check if user exists in group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.user_exists_in_group myuser mygroup ''' # TODO this should probably use boto.iam.get_groups_for_user users = get_group_members( group_name=group_name, region=region, key=key, keyid=keyid, profile=profile ) if users: for _user in users: if user_name == _user['user_name']: log.debug('IAM user %s is already in IAM group %s.', user_name, group_name) return True return False def remove_user_from_group(group_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Remove user from group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.remove_user_from_group mygroup myuser ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist.', user_name) return False if not user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.remove_user_from_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove IAM user %s from group %s', user_name, group_name) return False def put_group_policy(group_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_group_policy mygroup policyname policyrules ''' group = get_group(group_name, region=region, key=key, keyid=keyid, profile=profile) if not group: log.error('Group %s does not exist', group_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_group_policy(group_name, policy_name, policy_json) if created: log.info('Created policy for IAM group %s.', group_name) return True log.error('Could not create policy for IAM group %s', group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy for IAM group %s', group_name) return False def delete_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group_policy mygroup mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_group_policy( group_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_group_policy(group_name, policy_name) log.info('Successfully deleted policy %s for IAM group %s.', policy_name, group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM group %s.', policy_name, group_name) return False def get_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group_policy mygroup policyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group_policy(group_name, policy_name) log.debug('info for group policy is : %s', info) if not info: return False info = info.get_group_policy_response.get_group_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_all_groups(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM group details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_groups ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _groups = conn.get_all_groups(path_prefix=path_prefix) groups = _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) while marker: _groups = conn.get_all_groups(path_prefix=path_prefix, marker=marker) groups = groups + _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) return groups def get_all_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.get_all_instance_profiles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) marker = False profiles = [] while marker is not None: marker = marker if marker else None p = conn.list_instance_profiles(path_prefix=path_prefix, marker=marker) res = p.list_instance_profiles_response.list_instance_profiles_result profiles += res.instance_profiles marker = getattr(res, 'marker', None) return profiles def list_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' List all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.list_instance_profiles ''' p = get_all_instance_profiles(path_prefix, region, key, keyid, profile) return [i['instance_profile_name'] for i in p] def get_all_group_policies(group_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a group. CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_group_policies mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False try: response = conn.get_all_group_policies(group_name) _list = response.list_group_policies_response.list_group_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def delete_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _group = get_group( group_name, region, key, keyid, profile ) if not _group: return True try: conn.delete_group(group_name) log.info('Successfully deleted IAM group %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM group %s.', group_name) return False def create_login_profile(user_name, password, region=None, key=None, keyid=None, profile=None): ''' Creates a login profile for the specified user, give the user the ability to access AWS services and the AWS Management Console. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_login_profile user_name password ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.create_login_profile(user_name, password) log.info('Created profile for IAM user %s.', user_name) return info except boto.exception.BotoServerError as e: log.debug(e) if 'Conflict' in e: log.info('Profile already exists for IAM user %s.', user_name) return 'Conflict' log.error('Failed to update profile for IAM user %s.', user_name) return False def delete_login_profile(user_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a login profile for the specified user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_login_profile user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.delete_login_profile(user_name) log.info('Deleted login profile for IAM user %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Login profile already deleted for IAM user %s.', user_name) return True log.error('Failed to delete login profile for IAM user %s.', user_name) return False def get_all_mfa_devices(user_name, region=None, key=None, keyid=None, profile=None): ''' Get all MFA devices associated with an IAM user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_mfa_devices user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: result = conn.get_all_mfa_devices(user_name) devices = result['list_mfa_devices_response']['list_mfa_devices_result']['mfa_devices'] return devices except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Could not find IAM user %s.', user_name) return [] log.error('Failed to get all MFA devices for IAM user %s.', user_name) return False def deactivate_mfa_device(user_name, serial, region=None, key=None, keyid=None, profile=None): ''' Deactivates the specified MFA device and removes it from association with the user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.deactivate_mfa_device user_name serial_num ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.deactivate_mfa_device(user_name, serial) log.info('Deactivated MFA device %s for IAM user %s.', serial, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('MFA device %s not associated with IAM user %s.', serial, user_name) return True log.error('Failed to deactivate MFA device %s for IAM user %s.', serial, user_name) return False def delete_virtual_mfa_device(serial, region=None, key=None, keyid=None, profile=None): ''' Deletes the specified virtual MFA device. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_virtual_mfa_device serial_num ''' conn = __utils__['boto3.get_connection_func']('iam')() try: conn.delete_virtual_mfa_device(SerialNumber=serial) log.info('Deleted virtual MFA device %s.', serial) return True except botocore.exceptions.ClientError as e: log.debug(e) if 'NoSuchEntity' in six.text_type(e): log.info('Virtual MFA device %s not found.', serial) return True log.error('Failed to delete virtual MFA device %s.', serial) return False def update_account_password_policy(allow_users_to_change_password=None, hard_expiry=None, max_password_age=None, minimum_password_length=None, password_reuse_prevention=None, require_lowercase_characters=None, require_numbers=None, require_symbols=None, require_uppercase_characters=None, region=None, key=None, keyid=None, profile=None): ''' Update the password policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_account_password_policy True ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.update_account_password_policy(allow_users_to_change_password, hard_expiry, max_password_age, minimum_password_length, password_reuse_prevention, require_lowercase_characters, require_numbers, require_symbols, require_uppercase_characters) log.info('The password policy has been updated.') return True except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy' log.error(msg) return False def get_account_policy(region=None, key=None, keyid=None, profile=None): ''' Get account policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_account_password_policy() return info.get_account_password_policy_response.get_account_password_policy_result.password_policy except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy.' log.error(msg) return False def create_role(name, policy_document=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Create an instance role. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if role_exists(name, region, key, keyid, profile): return True if not policy_document: policy_document = None try: conn.create_role(name, assume_role_policy_document=policy_document, path=path) log.info('Created IAM role %s.', name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to create IAM role %s.', name) return False def delete_role(name, region=None, key=None, keyid=None, profile=None): ''' Delete an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(name, region, key, keyid, profile): return True try: conn.delete_role(name) log.info('Deleted %s IAM role.', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s IAM role.', name) return False def profile_associated(role_name, profile_name, region, key, keyid, profile): ''' Check to see if an instance profile is associated with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.profile_associated myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # The IAM module of boto doesn't return objects. Instead you need to grab # values through its properties. Sigh. try: profiles = conn.list_instance_profiles_for_role(role_name) except boto.exception.BotoServerError as e: log.debug(e) return False profiles = profiles.list_instance_profiles_for_role_response profiles = profiles.list_instance_profiles_for_role_result profiles = profiles.instance_profiles for profile in profiles: if profile.instance_profile_name == profile_name: return True return False def associate_profile_to_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Associate an instance profile with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.associate_profile_to_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if associated: return True else: try: conn.add_role_to_instance_profile(profile_name, role_name) log.info('Added %s instance profile to IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add %s instance profile to IAM role %s', profile_name, role_name) return False def disassociate_profile_from_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Disassociate an instance profile from an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.disassociate_profile_from_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if not associated: return True else: try: conn.remove_role_from_instance_profile(profile_name, role_name) log.info('Removed %s instance profile from IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove %s instance profile from IAM role %s.', profile_name, role_name) return False def list_role_policies(role_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_role_policies myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_role_policies(role_name) _list = response.list_role_policies_response.list_role_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def get_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.get_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: _policy = conn.get_role_policy(role_name, policy_name) # I _hate_ you for not giving me an object boto. _policy = _policy.get_role_policy_response.policy_document # Policy is url encoded _policy = _unquote(_policy) _policy = salt.utils.json.loads(_policy, object_pairs_hook=odict.OrderedDict) return _policy except boto.exception.BotoServerError: return {} def create_role_policy(role_name, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Create or modify a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role_policy myirole mypolicy '{"MyPolicy": "Statement": [{"Action": ["sqs:*"], "Effect": "Allow", "Resource": ["arn:aws:sqs:*:*:*"], "Sid": "MyPolicySqs1"}]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) mode = 'create' if _policy: if _policy == policy: return True mode = 'modify' if isinstance(policy, six.string_types): policy = salt.utils.json.loads(policy, object_pairs_hook=odict.OrderedDict) try: _policy = salt.utils.json.dumps(policy) conn.put_role_policy(role_name, policy_name, _policy) if mode == 'create': msg = 'Successfully added policy %s to IAM role %s.' else: msg = 'Successfully modified policy %s for IAM role %s.' log.info(msg, policy_name, role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to %s policy %s for IAM role %s.', mode, policy_name, role_name) return False def delete_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) if not _policy: return True try: conn.delete_role_policy(role_name, policy_name) log.info('Successfully deleted policy %s for IAM role %s.', policy_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM role %s.', policy_name, role_name) return False def update_assume_role_policy(role_name, policy_document, region=None, key=None, keyid=None, profile=None): ''' Update an assume role policy for a role. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_assume_role_policy myrole '{"Statement":"..."}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(policy_document, six.string_types): policy_document = salt.utils.json.loads(policy_document, object_pairs_hook=odict.OrderedDict) try: _policy_document = salt.utils.json.dumps(policy_document) conn.update_assume_role_policy(role_name, _policy_document) log.info('Successfully updated assume role policy for IAM role %s.', role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to update assume role policy for IAM role %s.', role_name) return False def build_policy(region=None, key=None, keyid=None, profile=None): ''' Build a default assume role policy. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.build_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if hasattr(conn, 'build_policy'): policy = salt.utils.json.loads(conn.build_policy()) elif hasattr(conn, '_build_policy'): policy = salt.utils.json.loads(conn._build_policy()) else: return {} # The format we get from build_policy isn't going to be what we get back # from AWS for the exact same policy. AWS converts single item list values # into strings, so let's do the same here. for key, policy_val in policy.items(): for statement in policy_val: if (isinstance(statement['Action'], list) and len(statement['Action']) == 1): statement['Action'] = statement['Action'][0] if (isinstance(statement['Principal']['Service'], list) and len(statement['Principal']['Service']) == 1): statement['Principal']['Service'] = statement['Principal']['Service'][0] # build_policy doesn't add a version field, which AWS is going to set to a # default value, when we get it back, so let's set it. policy['Version'] = '2008-10-17' return policy def get_account_id(region=None, key=None, keyid=None, profile=None): ''' Get a the AWS account id associated with the used credentials. CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_id ''' cache_key = 'boto_iam.account_id' if cache_key not in __context__: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_user() # The get_user call returns an user ARN: # arn:aws:iam::027050522557:user/salt-test arn = ret['get_user_response']['get_user_result']['user']['arn'] account_id = arn.split(':')[4] except boto.exception.BotoServerError: # If call failed, then let's try to get the ARN from the metadata timeout = boto.config.getfloat( 'Boto', 'metadata_service_timeout', 1.0 ) attempts = boto.config.getint( 'Boto', 'metadata_service_num_attempts', 1 ) identity = boto.utils.get_instance_identity( timeout=timeout, num_retries=attempts ) try: account_id = identity['document']['accountId'] except KeyError: log.error('Failed to get account id from instance_identity in' ' boto_iam.get_account_id.') __context__[cache_key] = account_id return __context__[cache_key] def get_all_roles(path_prefix=None, region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM role details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_roles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _roles = conn.list_roles(path_prefix=path_prefix) roles = _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) while marker: _roles = conn.list_roles(path_prefix=path_prefix, marker=marker) roles = roles + _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) return roles def get_all_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM user details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_users ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _users = conn.get_all_users(path_prefix=path_prefix) users = _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) while marker: _users = conn.get_all_users(path_prefix=path_prefix, marker=marker) users = users + _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) return users def get_all_user_policies(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all user policies. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_user_policies myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_all_user_policies(user_name, marker, max_items) if not info: return False _list = info.list_user_policies_response.list_user_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policies for user %s.', user_name) return False def get_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user_policy myuser mypolicyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user_policy(user_name, policy_name) log.debug('Info for IAM user %s policy %s: %s.', user_name, policy_name, info) if not info: return False info = info.get_user_policy_response.get_user_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policy %s for IAM user %s.', policy_name, user_name) return False def put_user_policy(user_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_user_policy myuser policyname policyrules ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_user_policy(user_name, policy_name, policy_json) if created: log.info('Created policy %s for IAM user %s.', policy_name, user_name) return True log.error('Could not create policy %s for IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy %s for IAM user %s.', policy_name, user_name) return False def delete_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user_policy myuser mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_user_policy( user_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_user_policy(user_name, policy_name) log.info('Successfully deleted policy %s for IAM user %s.', policy_name, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM user %s.', policy_name, user_name) return False def upload_server_cert(cert_name, cert_body, private_key, cert_chain=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Upload a certificate to Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.upload_server_cert mycert_name crt priv_key :param cert_name: The name for the server certificate. Do not include the path in this value. :param cert_body: The contents of the public key certificate in PEM-encoded format. :param private_key: The contents of the private key in PEM-encoded format. :param cert_chain: The contents of the certificate chain. This is typically a concatenation of the PEM-encoded public key certificates of the chain. :param path: The path for the server certificate. :param region: The name of the region to connect to. :param key: The key to be used in order to connect :param keyid: The keyid to be used in order to connect :param profile: The profile that contains a dict of region, key, keyid :return: True / False ''' exists = get_server_certificate(cert_name, region, key, keyid, profile) if exists: return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.upload_server_cert(cert_name, cert_body, private_key, cert_chain) log.info('Created certificate %s.', cert_name) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to failed to create certificate %s.', cert_name) return False def list_server_certificates(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Lists the server certificates stored in IAM that have the specified path prefix. .. versionadded:: ??? :param path_prefix: The path prefix for filtering the results. For example: /company/servercerts would get all server certificates for which the path starts with /company/servercerts . This parameter is optional. If it is not included, it defaults to a slash (/), listing all server certificates. This parameter allows (per its regex pattern) a string of characters consisting of either a forward slash (/) by itself or a string that must begin and end with forward slashes. In addition, it can contain any ASCII character from the ! (u0021) through the DEL character (u007F), including most punctuation characters, digits, and upper and lowercased letters. CLI Example: .. code-block:: bash salt myminion boto_iam.list_server_certificates path_prefix=/somepath/ ''' retries = 10 sleep = 6 conn = __utils__['boto3.get_connection']('iam', region=region, key=key, keyid=keyid, profile=profile) Items = [] while retries: try: log.debug('Garnering list of IAM Server Certificates') IsTruncated = True while IsTruncated: kwargs = {'PathPrefix': path_prefix} ret = conn.list_server_certificates(**kwargs) Items += ret.get('ServerCertificateMetadataList', []) IsTruncated = ret.get('IsTruncated') kwargs.update({'Marker': ret.get('Marker')}) return Items except botocore.exceptions.ParamValidationError as err: raise SaltInvocationError(str(err)) except botocore.exceptions.ClientError as err: if retries and jmespath.search('Error.Code', err.response) == 'Throttling': retries -= 1 log.debug('Throttled by AWS API, retrying in %s seconds...', sleep) time.sleep(sleep) continue log.error('Failed to list IAM Server Certificates: %s', err.message) return None def get_server_certificate(cert_name, region=None, key=None, keyid=None, profile=None): ''' Returns certificate information from Amazon .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_server_certificate mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_server_certificate(cert_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get certificate %s information.', cert_name) return False def delete_server_cert(cert_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a certificate from Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_server_cert mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_server_cert(cert_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete certificate %s.', cert_name) return False def export_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM user details. Produces results that can be used to create an sls file. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.export_users --out=txt | sed "s/local: //" > iam_users.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() users = get_all_users(path_prefix, region, key, keyid, profile) for user in users: name = user.user_name _policies = conn.get_all_user_policies(name, max_items=100) _policies = _policies.list_user_policies_response.list_user_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_user_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_user_policy_response.get_user_policy_result.policy_document )) policies[policy_name] = _policy user_sls = [] user_sls.append({"name": name}) user_sls.append({"policies": policies}) user_sls.append({"path": user.path}) results["manage user " + name] = {"boto_iam.user_present": user_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def export_roles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM role details. Produces results that can be used to create an sls file. CLI Example: salt-call boto_iam.export_roles --out=txt | sed "s/local: //" > iam_roles.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() roles = get_all_roles(path_prefix, region, key, keyid, profile) for role in roles: name = role.role_name _policies = conn.list_role_policies(name, max_items=100) _policies = _policies.list_role_policies_response.list_role_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_role_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_role_policy_response.get_role_policy_result.policy_document )) policies[policy_name] = _policy role_sls = [] role_sls.append({"name": name}) role_sls.append({"policies": policies}) role_sls.append({'policy_document': salt.utils.json.loads(_unquote(role.assume_role_policy_document))}) role_sls.append({"path": role.path}) results["manage role " + name] = {"boto_iam_role.present": role_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def _get_policy_arn(name, region=None, key=None, keyid=None, profile=None): if name.startswith('arn:aws:iam:'): return name account_id = get_account_id( region=region, key=key, keyid=keyid, profile=profile ) return 'arn:aws:iam::{0}:policy/{1}'.format(account_id, name) def policy_exists(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return True except boto.exception.BotoServerError: return False def get_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return ret.get('get_policy_response', {}).get('get_policy_result', {}) except boto.exception.BotoServerError: return None def create_policy(policy_name, policy_document, path=None, description=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in 'path', 'description': if locals()[arg] is not None: params[arg] = locals()[arg] if policy_exists(policy_name, region, key, keyid, profile): return True try: conn.create_policy(policy_name, policy_document, **params) log.info('Created IAM policy %s.', policy_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s.', policy_name) return False return True def delete_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_exists(policy_arn, region, key, keyid, profile): return True try: conn.delete_policy(policy_arn) log.info('Deleted %s policy.', policy_name) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete %s policy: %s.', policy_name, aws.get('message')) return False return True def policy_version_exists(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.get_policy_version(policy_arn, version_id) return True except boto.exception.BotoServerError: return False def get_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy_version(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile), version_id) retval = ret.get('get_policy_version_response', {}).get('get_policy_version_result', {}).get('policy_version', {}) retval['document'] = _unquote(retval.get('document')) return {'policy_version': retval} except boto.exception.BotoServerError: return None def create_policy_version(policy_name, policy_document, set_as_default=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy version. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy_version mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in ('set_as_default',): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.create_policy_version(policy_arn, policy_document, **params) vid = ret.get('create_policy_version_response', {}).get('create_policy_version_result', {}).get('policy_version', {}).get('version_id') log.info('Created IAM policy %s version %s.', policy_name, vid) return {'created': True, 'version_id': vid} except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s version %s.', policy_name, vid) return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Delete a policy version. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_version_exists(policy_arn, version_id, region, key, keyid, profile): return True try: conn.delete_policy_version(policy_arn, version_id) log.info('Deleted IAM policy %s version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete IAM policy %s version %s: %s', policy_name, version_id, aws.get('message')) return False return True def list_policy_versions(policy_name, region=None, key=None, keyid=None, profile=None): ''' List versions of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policy_versions mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.list_policy_versions(policy_arn) return ret.get('list_policy_versions_response', {}).get('list_policy_versions_result', {}).get('versions') except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list versions for IAM policy %s.', policy_name) return [] def set_default_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Set the default version of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.set_default_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.set_default_policy_version(policy_arn, version_id) log.info('Set %s policy to version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to set %s policy to version %s: %s', policy_name, version_id, aws.get('message')) return False return True def attach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_user_policy(policy_arn, user_name) log.info('Attached policy %s to IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach %s policy to IAM user %s.', policy_name, user_name) return False return True def detach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_user_policy(policy_arn, user_name) log.info('Detached %s policy from IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach %s policy from IAM user %s.', policy_name, user_name) return False return True def attach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_group_policy(policy_arn, group_name) log.info('Attached policy %s to IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM group %s.', policy_name, group_name) return False return True def detach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_group_policy(policy_arn, group_name) log.info('Detached policy %s from IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM group %s.', policy_name, group_name) return False return True def attach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_role_policy(policy_arn, role_name) log.info('Attached policy %s to IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM role %s.', policy_name, role_name) return False return True def detach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_role_policy(policy_arn, role_name) log.info('Detached policy %s from IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM role %s.', policy_name, role_name) return False return True def list_entities_for_policy(policy_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities that a policy is attached to. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 params = {} for arg in ('path_prefix', 'entity_filter'): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) while retries: try: allret = { 'policy_groups': [], 'policy_users': [], 'policy_roles': [], } for ret in __utils__['boto.paged_call'](conn.list_entities_for_policy, policy_arn=policy_arn, **params): for k, v in six.iteritems(allret): v.extend(ret.get('list_entities_for_policy_response', {}).get('list_entities_for_policy_result', {}).get(k)) return allret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('Failed to list entities for IAM policy %s: %s', policy_name, e.message) return {} return {} def list_attached_user_policies(user_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given user. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'UserName': user_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedUserPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_user_policies_response', {}).get('list_attached_user_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM user %s.', user_name) return [] def list_attached_group_policies(group_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given group. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'GroupName': group_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedGroupPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_group_policies_response', {}).get('list_attached_group_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM group %s.', group_name) return [] def list_attached_role_policies(role_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'RoleName': role_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedRolePolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_role_policies_response', {}).get('list_attached_role_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM role %s.', role_name) return [] def create_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Create SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.create_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_saml_provider(saml_metadata_document, name) log.info('Successfully created %s SAML provider.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to create SAML provider %s.', name) return False def get_saml_provider_arn(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider_arn my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_saml_providers() for saml_provider in response.list_saml_providers_response.list_saml_providers_result.saml_provider_list: if saml_provider['arn'].endswith(':saml-provider/' + name): return saml_provider['arn'] return False except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to get ARN of SAML provider %s.', name) return False def delete_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Delete SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.delete_saml_provider my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return True conn.delete_saml_provider(saml_provider_arn) log.info('Successfully deleted SAML provider %s.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete SAML provider %s.', name) return False def list_saml_providers(region=None, key=None, keyid=None, profile=None): ''' List SAML providers. CLI Example: .. code-block:: bash salt myminion boto_iam.list_saml_providers ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: providers = [] info = conn.list_saml_providers() for arn in info['list_saml_providers_response']['list_saml_providers_result']['saml_provider_list']: providers.append(arn['arn'].rsplit('/', 1)[1]) return providers except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get list of SAML providers.') return False def get_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider document. CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider arn ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: provider = conn.get_saml_provider(name) return provider['get_saml_provider_response']['get_saml_provider_result']['saml_metadata_document'] except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get SAML provider document %s.', name) return False def update_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Update SAML provider. CLI Example: .. code-block:: bash salt myminion boto_iam.update_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return False if conn.update_saml_provider(name, saml_metadata_document): return True return False except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to update SAML provider %s.', name) return False
saltstack/salt
salt/modules/boto_iam.py
policy_version_exists
python
def policy_version_exists(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.get_policy_version(policy_arn, version_id) return True except boto.exception.BotoServerError: return False
Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iam.py#L1830-L1848
[ "def _get_policy_arn(name, region=None, key=None, keyid=None, profile=None):\n if name.startswith('arn:aws:iam:'):\n return name\n\n account_id = get_account_id(\n region=region, key=key, keyid=keyid, profile=profile\n )\n return 'arn:aws:iam::{0}:policy/{1}'.format(account_id, name)\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon IAM .. versionadded:: 2014.7.0 :configuration: This module accepts explicit iam 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 iam.keyid: GKTADJGHEIQSXMKKRBJ08H iam.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs iam.region: 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: boto ''' # keep lint from choking on _get_conn and _cache_id #pylint: disable=E0602 # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import salt libs from salt.ext import six import salt.utils.compat import salt.utils.json import salt.utils.odict as odict import salt.utils.versions from salt.exceptions import SaltInvocationError # Import third party libs # pylint: disable=unused-import from salt.ext.six.moves.urllib.parse import unquote as _unquote # pylint: disable=no-name-in-module try: import boto import boto.iam import boto3 import botocore logging.getLogger('boto').setLevel(logging.CRITICAL) logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=unused-import log = logging.getLogger(__name__) def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'iam', pack=__salt__) def instance_profile_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an instance profile exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: # Boto weirdly returns an exception here if an instance profile doesn't # exist. conn.get_instance_profile(name) return True except boto.exception.BotoServerError: return False def create_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Create an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.create_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if instance_profile_exists(name, region, key, keyid, profile): return True try: # This call returns an instance profile if successful and an exception # if not. It's annoying. conn.create_instance_profile(name) log.info('Created %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create %s instance profile.', name) return False return True def delete_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Delete an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not instance_profile_exists(name, region, key, keyid, profile): return True try: conn.delete_instance_profile(name) log.info('Deleted %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s instance profile.', name) return False return True def role_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an IAM role exists. CLI Example: .. code-block:: bash salt myminion boto_iam.role_exists myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_role(name) return True except boto.exception.BotoServerError: return False def describe_role(name, region=None, key=None, keyid=None, profile=None): ''' Get information for a role. CLI Example: .. code-block:: bash salt myminion boto_iam.describe_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_role(name) if not info: return False role = info.get_role_response.get_role_result.role role['assume_role_policy_document'] = salt.utils.json.loads(_unquote( role.assume_role_policy_document )) # If Sid wasn't defined by the user, boto will still return a Sid in # each policy. To properly check idempotently, let's remove the Sid # from the return if it's not actually set. for policy_key, policy in role['assume_role_policy_document'].items(): if policy_key == 'Statement': for val in policy: if 'Sid' in val and not val['Sid']: del val['Sid'] return role except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get %s information.', name) return False def create_user(user_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_user myuser ''' if not path: path = '/' if get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_user(user_name, path) log.info('Created IAM user : %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM user %s.', user_name) return False def get_all_access_keys(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all access keys from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_access_keys myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.get_all_access_keys(user_name, marker, max_items) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get access keys for IAM user %s.', user_name) return six.text_type(e) def create_access_key(user_name, region=None, key=None, keyid=None, profile=None): ''' Create access key id for a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.create_access_key(user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create access key.') return six.text_type(e) def delete_access_key(access_key_id, user_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete access key id from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_access_key(access_key_id, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete access key id %s.', access_key_id) return six.text_type(e) def delete_user(user_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user myuser ''' if not get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.delete_user(user_name) log.info('Deleted IAM user : %s .', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM user %s', user_name) return six.text_type(e) def get_user(user_name=None, region=None, key=None, keyid=None, profile=None): ''' Get user information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user(user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM user %s info.', user_name) return False def create_group(group_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_group group ''' if not path: path = '/' if get_group(group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_group(group_name, path) log.info('Created IAM group : %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM group %s.', group_name) return False def get_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group(group_name, max_items=1) if not info: return False return info['get_group_response']['get_group_result']['group'] except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_group_members(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: marker = None truncated = True users = [] while truncated: info = conn.get_group(group_name, marker=marker, max_items=1000) if not info: return False truncated = bool(info['get_group_response']['get_group_result']['is_truncated']) if truncated and 'marker' in info['get_group_response']['get_group_result']: marker = info['get_group_response']['get_group_result']['marker'] else: marker = None truncated = False users += info['get_group_response']['get_group_result']['users'] return users except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get members for IAM group %s.', group_name) return False def add_user_to_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Add user to group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.add_user_to_group myuser mygroup ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('Username : %s does not exist.', user_name) return False if user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.add_user_to_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add IAM user %s to group %s.', user_name, group_name) return False def user_exists_in_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Check if user exists in group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.user_exists_in_group myuser mygroup ''' # TODO this should probably use boto.iam.get_groups_for_user users = get_group_members( group_name=group_name, region=region, key=key, keyid=keyid, profile=profile ) if users: for _user in users: if user_name == _user['user_name']: log.debug('IAM user %s is already in IAM group %s.', user_name, group_name) return True return False def remove_user_from_group(group_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Remove user from group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.remove_user_from_group mygroup myuser ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist.', user_name) return False if not user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.remove_user_from_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove IAM user %s from group %s', user_name, group_name) return False def put_group_policy(group_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_group_policy mygroup policyname policyrules ''' group = get_group(group_name, region=region, key=key, keyid=keyid, profile=profile) if not group: log.error('Group %s does not exist', group_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_group_policy(group_name, policy_name, policy_json) if created: log.info('Created policy for IAM group %s.', group_name) return True log.error('Could not create policy for IAM group %s', group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy for IAM group %s', group_name) return False def delete_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group_policy mygroup mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_group_policy( group_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_group_policy(group_name, policy_name) log.info('Successfully deleted policy %s for IAM group %s.', policy_name, group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM group %s.', policy_name, group_name) return False def get_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group_policy mygroup policyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group_policy(group_name, policy_name) log.debug('info for group policy is : %s', info) if not info: return False info = info.get_group_policy_response.get_group_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_all_groups(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM group details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_groups ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _groups = conn.get_all_groups(path_prefix=path_prefix) groups = _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) while marker: _groups = conn.get_all_groups(path_prefix=path_prefix, marker=marker) groups = groups + _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) return groups def get_all_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.get_all_instance_profiles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) marker = False profiles = [] while marker is not None: marker = marker if marker else None p = conn.list_instance_profiles(path_prefix=path_prefix, marker=marker) res = p.list_instance_profiles_response.list_instance_profiles_result profiles += res.instance_profiles marker = getattr(res, 'marker', None) return profiles def list_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' List all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.list_instance_profiles ''' p = get_all_instance_profiles(path_prefix, region, key, keyid, profile) return [i['instance_profile_name'] for i in p] def get_all_group_policies(group_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a group. CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_group_policies mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False try: response = conn.get_all_group_policies(group_name) _list = response.list_group_policies_response.list_group_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def delete_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _group = get_group( group_name, region, key, keyid, profile ) if not _group: return True try: conn.delete_group(group_name) log.info('Successfully deleted IAM group %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM group %s.', group_name) return False def create_login_profile(user_name, password, region=None, key=None, keyid=None, profile=None): ''' Creates a login profile for the specified user, give the user the ability to access AWS services and the AWS Management Console. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_login_profile user_name password ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.create_login_profile(user_name, password) log.info('Created profile for IAM user %s.', user_name) return info except boto.exception.BotoServerError as e: log.debug(e) if 'Conflict' in e: log.info('Profile already exists for IAM user %s.', user_name) return 'Conflict' log.error('Failed to update profile for IAM user %s.', user_name) return False def delete_login_profile(user_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a login profile for the specified user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_login_profile user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.delete_login_profile(user_name) log.info('Deleted login profile for IAM user %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Login profile already deleted for IAM user %s.', user_name) return True log.error('Failed to delete login profile for IAM user %s.', user_name) return False def get_all_mfa_devices(user_name, region=None, key=None, keyid=None, profile=None): ''' Get all MFA devices associated with an IAM user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_mfa_devices user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: result = conn.get_all_mfa_devices(user_name) devices = result['list_mfa_devices_response']['list_mfa_devices_result']['mfa_devices'] return devices except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Could not find IAM user %s.', user_name) return [] log.error('Failed to get all MFA devices for IAM user %s.', user_name) return False def deactivate_mfa_device(user_name, serial, region=None, key=None, keyid=None, profile=None): ''' Deactivates the specified MFA device and removes it from association with the user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.deactivate_mfa_device user_name serial_num ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.deactivate_mfa_device(user_name, serial) log.info('Deactivated MFA device %s for IAM user %s.', serial, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('MFA device %s not associated with IAM user %s.', serial, user_name) return True log.error('Failed to deactivate MFA device %s for IAM user %s.', serial, user_name) return False def delete_virtual_mfa_device(serial, region=None, key=None, keyid=None, profile=None): ''' Deletes the specified virtual MFA device. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_virtual_mfa_device serial_num ''' conn = __utils__['boto3.get_connection_func']('iam')() try: conn.delete_virtual_mfa_device(SerialNumber=serial) log.info('Deleted virtual MFA device %s.', serial) return True except botocore.exceptions.ClientError as e: log.debug(e) if 'NoSuchEntity' in six.text_type(e): log.info('Virtual MFA device %s not found.', serial) return True log.error('Failed to delete virtual MFA device %s.', serial) return False def update_account_password_policy(allow_users_to_change_password=None, hard_expiry=None, max_password_age=None, minimum_password_length=None, password_reuse_prevention=None, require_lowercase_characters=None, require_numbers=None, require_symbols=None, require_uppercase_characters=None, region=None, key=None, keyid=None, profile=None): ''' Update the password policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_account_password_policy True ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.update_account_password_policy(allow_users_to_change_password, hard_expiry, max_password_age, minimum_password_length, password_reuse_prevention, require_lowercase_characters, require_numbers, require_symbols, require_uppercase_characters) log.info('The password policy has been updated.') return True except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy' log.error(msg) return False def get_account_policy(region=None, key=None, keyid=None, profile=None): ''' Get account policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_account_password_policy() return info.get_account_password_policy_response.get_account_password_policy_result.password_policy except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy.' log.error(msg) return False def create_role(name, policy_document=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Create an instance role. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if role_exists(name, region, key, keyid, profile): return True if not policy_document: policy_document = None try: conn.create_role(name, assume_role_policy_document=policy_document, path=path) log.info('Created IAM role %s.', name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to create IAM role %s.', name) return False def delete_role(name, region=None, key=None, keyid=None, profile=None): ''' Delete an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(name, region, key, keyid, profile): return True try: conn.delete_role(name) log.info('Deleted %s IAM role.', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s IAM role.', name) return False def profile_associated(role_name, profile_name, region, key, keyid, profile): ''' Check to see if an instance profile is associated with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.profile_associated myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # The IAM module of boto doesn't return objects. Instead you need to grab # values through its properties. Sigh. try: profiles = conn.list_instance_profiles_for_role(role_name) except boto.exception.BotoServerError as e: log.debug(e) return False profiles = profiles.list_instance_profiles_for_role_response profiles = profiles.list_instance_profiles_for_role_result profiles = profiles.instance_profiles for profile in profiles: if profile.instance_profile_name == profile_name: return True return False def associate_profile_to_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Associate an instance profile with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.associate_profile_to_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if associated: return True else: try: conn.add_role_to_instance_profile(profile_name, role_name) log.info('Added %s instance profile to IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add %s instance profile to IAM role %s', profile_name, role_name) return False def disassociate_profile_from_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Disassociate an instance profile from an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.disassociate_profile_from_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if not associated: return True else: try: conn.remove_role_from_instance_profile(profile_name, role_name) log.info('Removed %s instance profile from IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove %s instance profile from IAM role %s.', profile_name, role_name) return False def list_role_policies(role_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_role_policies myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_role_policies(role_name) _list = response.list_role_policies_response.list_role_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def get_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.get_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: _policy = conn.get_role_policy(role_name, policy_name) # I _hate_ you for not giving me an object boto. _policy = _policy.get_role_policy_response.policy_document # Policy is url encoded _policy = _unquote(_policy) _policy = salt.utils.json.loads(_policy, object_pairs_hook=odict.OrderedDict) return _policy except boto.exception.BotoServerError: return {} def create_role_policy(role_name, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Create or modify a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role_policy myirole mypolicy '{"MyPolicy": "Statement": [{"Action": ["sqs:*"], "Effect": "Allow", "Resource": ["arn:aws:sqs:*:*:*"], "Sid": "MyPolicySqs1"}]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) mode = 'create' if _policy: if _policy == policy: return True mode = 'modify' if isinstance(policy, six.string_types): policy = salt.utils.json.loads(policy, object_pairs_hook=odict.OrderedDict) try: _policy = salt.utils.json.dumps(policy) conn.put_role_policy(role_name, policy_name, _policy) if mode == 'create': msg = 'Successfully added policy %s to IAM role %s.' else: msg = 'Successfully modified policy %s for IAM role %s.' log.info(msg, policy_name, role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to %s policy %s for IAM role %s.', mode, policy_name, role_name) return False def delete_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) if not _policy: return True try: conn.delete_role_policy(role_name, policy_name) log.info('Successfully deleted policy %s for IAM role %s.', policy_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM role %s.', policy_name, role_name) return False def update_assume_role_policy(role_name, policy_document, region=None, key=None, keyid=None, profile=None): ''' Update an assume role policy for a role. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_assume_role_policy myrole '{"Statement":"..."}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(policy_document, six.string_types): policy_document = salt.utils.json.loads(policy_document, object_pairs_hook=odict.OrderedDict) try: _policy_document = salt.utils.json.dumps(policy_document) conn.update_assume_role_policy(role_name, _policy_document) log.info('Successfully updated assume role policy for IAM role %s.', role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to update assume role policy for IAM role %s.', role_name) return False def build_policy(region=None, key=None, keyid=None, profile=None): ''' Build a default assume role policy. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.build_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if hasattr(conn, 'build_policy'): policy = salt.utils.json.loads(conn.build_policy()) elif hasattr(conn, '_build_policy'): policy = salt.utils.json.loads(conn._build_policy()) else: return {} # The format we get from build_policy isn't going to be what we get back # from AWS for the exact same policy. AWS converts single item list values # into strings, so let's do the same here. for key, policy_val in policy.items(): for statement in policy_val: if (isinstance(statement['Action'], list) and len(statement['Action']) == 1): statement['Action'] = statement['Action'][0] if (isinstance(statement['Principal']['Service'], list) and len(statement['Principal']['Service']) == 1): statement['Principal']['Service'] = statement['Principal']['Service'][0] # build_policy doesn't add a version field, which AWS is going to set to a # default value, when we get it back, so let's set it. policy['Version'] = '2008-10-17' return policy def get_account_id(region=None, key=None, keyid=None, profile=None): ''' Get a the AWS account id associated with the used credentials. CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_id ''' cache_key = 'boto_iam.account_id' if cache_key not in __context__: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_user() # The get_user call returns an user ARN: # arn:aws:iam::027050522557:user/salt-test arn = ret['get_user_response']['get_user_result']['user']['arn'] account_id = arn.split(':')[4] except boto.exception.BotoServerError: # If call failed, then let's try to get the ARN from the metadata timeout = boto.config.getfloat( 'Boto', 'metadata_service_timeout', 1.0 ) attempts = boto.config.getint( 'Boto', 'metadata_service_num_attempts', 1 ) identity = boto.utils.get_instance_identity( timeout=timeout, num_retries=attempts ) try: account_id = identity['document']['accountId'] except KeyError: log.error('Failed to get account id from instance_identity in' ' boto_iam.get_account_id.') __context__[cache_key] = account_id return __context__[cache_key] def get_all_roles(path_prefix=None, region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM role details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_roles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _roles = conn.list_roles(path_prefix=path_prefix) roles = _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) while marker: _roles = conn.list_roles(path_prefix=path_prefix, marker=marker) roles = roles + _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) return roles def get_all_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM user details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_users ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _users = conn.get_all_users(path_prefix=path_prefix) users = _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) while marker: _users = conn.get_all_users(path_prefix=path_prefix, marker=marker) users = users + _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) return users def get_all_user_policies(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all user policies. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_user_policies myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_all_user_policies(user_name, marker, max_items) if not info: return False _list = info.list_user_policies_response.list_user_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policies for user %s.', user_name) return False def get_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user_policy myuser mypolicyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user_policy(user_name, policy_name) log.debug('Info for IAM user %s policy %s: %s.', user_name, policy_name, info) if not info: return False info = info.get_user_policy_response.get_user_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policy %s for IAM user %s.', policy_name, user_name) return False def put_user_policy(user_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_user_policy myuser policyname policyrules ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_user_policy(user_name, policy_name, policy_json) if created: log.info('Created policy %s for IAM user %s.', policy_name, user_name) return True log.error('Could not create policy %s for IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy %s for IAM user %s.', policy_name, user_name) return False def delete_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user_policy myuser mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_user_policy( user_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_user_policy(user_name, policy_name) log.info('Successfully deleted policy %s for IAM user %s.', policy_name, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM user %s.', policy_name, user_name) return False def upload_server_cert(cert_name, cert_body, private_key, cert_chain=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Upload a certificate to Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.upload_server_cert mycert_name crt priv_key :param cert_name: The name for the server certificate. Do not include the path in this value. :param cert_body: The contents of the public key certificate in PEM-encoded format. :param private_key: The contents of the private key in PEM-encoded format. :param cert_chain: The contents of the certificate chain. This is typically a concatenation of the PEM-encoded public key certificates of the chain. :param path: The path for the server certificate. :param region: The name of the region to connect to. :param key: The key to be used in order to connect :param keyid: The keyid to be used in order to connect :param profile: The profile that contains a dict of region, key, keyid :return: True / False ''' exists = get_server_certificate(cert_name, region, key, keyid, profile) if exists: return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.upload_server_cert(cert_name, cert_body, private_key, cert_chain) log.info('Created certificate %s.', cert_name) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to failed to create certificate %s.', cert_name) return False def list_server_certificates(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Lists the server certificates stored in IAM that have the specified path prefix. .. versionadded:: ??? :param path_prefix: The path prefix for filtering the results. For example: /company/servercerts would get all server certificates for which the path starts with /company/servercerts . This parameter is optional. If it is not included, it defaults to a slash (/), listing all server certificates. This parameter allows (per its regex pattern) a string of characters consisting of either a forward slash (/) by itself or a string that must begin and end with forward slashes. In addition, it can contain any ASCII character from the ! (u0021) through the DEL character (u007F), including most punctuation characters, digits, and upper and lowercased letters. CLI Example: .. code-block:: bash salt myminion boto_iam.list_server_certificates path_prefix=/somepath/ ''' retries = 10 sleep = 6 conn = __utils__['boto3.get_connection']('iam', region=region, key=key, keyid=keyid, profile=profile) Items = [] while retries: try: log.debug('Garnering list of IAM Server Certificates') IsTruncated = True while IsTruncated: kwargs = {'PathPrefix': path_prefix} ret = conn.list_server_certificates(**kwargs) Items += ret.get('ServerCertificateMetadataList', []) IsTruncated = ret.get('IsTruncated') kwargs.update({'Marker': ret.get('Marker')}) return Items except botocore.exceptions.ParamValidationError as err: raise SaltInvocationError(str(err)) except botocore.exceptions.ClientError as err: if retries and jmespath.search('Error.Code', err.response) == 'Throttling': retries -= 1 log.debug('Throttled by AWS API, retrying in %s seconds...', sleep) time.sleep(sleep) continue log.error('Failed to list IAM Server Certificates: %s', err.message) return None def get_server_certificate(cert_name, region=None, key=None, keyid=None, profile=None): ''' Returns certificate information from Amazon .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_server_certificate mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_server_certificate(cert_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get certificate %s information.', cert_name) return False def delete_server_cert(cert_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a certificate from Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_server_cert mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_server_cert(cert_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete certificate %s.', cert_name) return False def export_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM user details. Produces results that can be used to create an sls file. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.export_users --out=txt | sed "s/local: //" > iam_users.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() users = get_all_users(path_prefix, region, key, keyid, profile) for user in users: name = user.user_name _policies = conn.get_all_user_policies(name, max_items=100) _policies = _policies.list_user_policies_response.list_user_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_user_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_user_policy_response.get_user_policy_result.policy_document )) policies[policy_name] = _policy user_sls = [] user_sls.append({"name": name}) user_sls.append({"policies": policies}) user_sls.append({"path": user.path}) results["manage user " + name] = {"boto_iam.user_present": user_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def export_roles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM role details. Produces results that can be used to create an sls file. CLI Example: salt-call boto_iam.export_roles --out=txt | sed "s/local: //" > iam_roles.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() roles = get_all_roles(path_prefix, region, key, keyid, profile) for role in roles: name = role.role_name _policies = conn.list_role_policies(name, max_items=100) _policies = _policies.list_role_policies_response.list_role_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_role_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_role_policy_response.get_role_policy_result.policy_document )) policies[policy_name] = _policy role_sls = [] role_sls.append({"name": name}) role_sls.append({"policies": policies}) role_sls.append({'policy_document': salt.utils.json.loads(_unquote(role.assume_role_policy_document))}) role_sls.append({"path": role.path}) results["manage role " + name] = {"boto_iam_role.present": role_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def _get_policy_arn(name, region=None, key=None, keyid=None, profile=None): if name.startswith('arn:aws:iam:'): return name account_id = get_account_id( region=region, key=key, keyid=keyid, profile=profile ) return 'arn:aws:iam::{0}:policy/{1}'.format(account_id, name) def policy_exists(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return True except boto.exception.BotoServerError: return False def get_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return ret.get('get_policy_response', {}).get('get_policy_result', {}) except boto.exception.BotoServerError: return None def create_policy(policy_name, policy_document, path=None, description=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in 'path', 'description': if locals()[arg] is not None: params[arg] = locals()[arg] if policy_exists(policy_name, region, key, keyid, profile): return True try: conn.create_policy(policy_name, policy_document, **params) log.info('Created IAM policy %s.', policy_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s.', policy_name) return False return True def delete_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_exists(policy_arn, region, key, keyid, profile): return True try: conn.delete_policy(policy_arn) log.info('Deleted %s policy.', policy_name) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete %s policy: %s.', policy_name, aws.get('message')) return False return True def list_policies(region=None, key=None, keyid=None, profile=None): ''' List policies. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policies ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: policies = [] for ret in __utils__['boto.paged_call'](conn.list_policies): policies.append(ret.get('list_policies_response', {}).get('list_policies_result', {}).get('policies')) return policies except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to list policy versions.' log.error(msg) return [] def get_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy_version(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile), version_id) retval = ret.get('get_policy_version_response', {}).get('get_policy_version_result', {}).get('policy_version', {}) retval['document'] = _unquote(retval.get('document')) return {'policy_version': retval} except boto.exception.BotoServerError: return None def create_policy_version(policy_name, policy_document, set_as_default=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy version. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy_version mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in ('set_as_default',): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.create_policy_version(policy_arn, policy_document, **params) vid = ret.get('create_policy_version_response', {}).get('create_policy_version_result', {}).get('policy_version', {}).get('version_id') log.info('Created IAM policy %s version %s.', policy_name, vid) return {'created': True, 'version_id': vid} except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s version %s.', policy_name, vid) return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Delete a policy version. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_version_exists(policy_arn, version_id, region, key, keyid, profile): return True try: conn.delete_policy_version(policy_arn, version_id) log.info('Deleted IAM policy %s version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete IAM policy %s version %s: %s', policy_name, version_id, aws.get('message')) return False return True def list_policy_versions(policy_name, region=None, key=None, keyid=None, profile=None): ''' List versions of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policy_versions mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.list_policy_versions(policy_arn) return ret.get('list_policy_versions_response', {}).get('list_policy_versions_result', {}).get('versions') except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list versions for IAM policy %s.', policy_name) return [] def set_default_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Set the default version of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.set_default_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.set_default_policy_version(policy_arn, version_id) log.info('Set %s policy to version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to set %s policy to version %s: %s', policy_name, version_id, aws.get('message')) return False return True def attach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_user_policy(policy_arn, user_name) log.info('Attached policy %s to IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach %s policy to IAM user %s.', policy_name, user_name) return False return True def detach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_user_policy(policy_arn, user_name) log.info('Detached %s policy from IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach %s policy from IAM user %s.', policy_name, user_name) return False return True def attach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_group_policy(policy_arn, group_name) log.info('Attached policy %s to IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM group %s.', policy_name, group_name) return False return True def detach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_group_policy(policy_arn, group_name) log.info('Detached policy %s from IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM group %s.', policy_name, group_name) return False return True def attach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_role_policy(policy_arn, role_name) log.info('Attached policy %s to IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM role %s.', policy_name, role_name) return False return True def detach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_role_policy(policy_arn, role_name) log.info('Detached policy %s from IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM role %s.', policy_name, role_name) return False return True def list_entities_for_policy(policy_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities that a policy is attached to. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 params = {} for arg in ('path_prefix', 'entity_filter'): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) while retries: try: allret = { 'policy_groups': [], 'policy_users': [], 'policy_roles': [], } for ret in __utils__['boto.paged_call'](conn.list_entities_for_policy, policy_arn=policy_arn, **params): for k, v in six.iteritems(allret): v.extend(ret.get('list_entities_for_policy_response', {}).get('list_entities_for_policy_result', {}).get(k)) return allret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('Failed to list entities for IAM policy %s: %s', policy_name, e.message) return {} return {} def list_attached_user_policies(user_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given user. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'UserName': user_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedUserPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_user_policies_response', {}).get('list_attached_user_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM user %s.', user_name) return [] def list_attached_group_policies(group_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given group. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'GroupName': group_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedGroupPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_group_policies_response', {}).get('list_attached_group_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM group %s.', group_name) return [] def list_attached_role_policies(role_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'RoleName': role_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedRolePolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_role_policies_response', {}).get('list_attached_role_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM role %s.', role_name) return [] def create_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Create SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.create_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_saml_provider(saml_metadata_document, name) log.info('Successfully created %s SAML provider.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to create SAML provider %s.', name) return False def get_saml_provider_arn(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider_arn my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_saml_providers() for saml_provider in response.list_saml_providers_response.list_saml_providers_result.saml_provider_list: if saml_provider['arn'].endswith(':saml-provider/' + name): return saml_provider['arn'] return False except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to get ARN of SAML provider %s.', name) return False def delete_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Delete SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.delete_saml_provider my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return True conn.delete_saml_provider(saml_provider_arn) log.info('Successfully deleted SAML provider %s.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete SAML provider %s.', name) return False def list_saml_providers(region=None, key=None, keyid=None, profile=None): ''' List SAML providers. CLI Example: .. code-block:: bash salt myminion boto_iam.list_saml_providers ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: providers = [] info = conn.list_saml_providers() for arn in info['list_saml_providers_response']['list_saml_providers_result']['saml_provider_list']: providers.append(arn['arn'].rsplit('/', 1)[1]) return providers except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get list of SAML providers.') return False def get_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider document. CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider arn ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: provider = conn.get_saml_provider(name) return provider['get_saml_provider_response']['get_saml_provider_result']['saml_metadata_document'] except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get SAML provider document %s.', name) return False def update_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Update SAML provider. CLI Example: .. code-block:: bash salt myminion boto_iam.update_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return False if conn.update_saml_provider(name, saml_metadata_document): return True return False except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to update SAML provider %s.', name) return False
saltstack/salt
salt/modules/boto_iam.py
get_policy_version
python
def get_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy_version(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile), version_id) retval = ret.get('get_policy_version_response', {}).get('get_policy_version_result', {}).get('policy_version', {}) retval['document'] = _unquote(retval.get('document')) return {'policy_version': retval} except boto.exception.BotoServerError: return None
Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iam.py#L1851-L1871
[ "def _get_policy_arn(name, region=None, key=None, keyid=None, profile=None):\n if name.startswith('arn:aws:iam:'):\n return name\n\n account_id = get_account_id(\n region=region, key=key, keyid=keyid, profile=profile\n )\n return 'arn:aws:iam::{0}:policy/{1}'.format(account_id, name)\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon IAM .. versionadded:: 2014.7.0 :configuration: This module accepts explicit iam 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 iam.keyid: GKTADJGHEIQSXMKKRBJ08H iam.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs iam.region: 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: boto ''' # keep lint from choking on _get_conn and _cache_id #pylint: disable=E0602 # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import salt libs from salt.ext import six import salt.utils.compat import salt.utils.json import salt.utils.odict as odict import salt.utils.versions from salt.exceptions import SaltInvocationError # Import third party libs # pylint: disable=unused-import from salt.ext.six.moves.urllib.parse import unquote as _unquote # pylint: disable=no-name-in-module try: import boto import boto.iam import boto3 import botocore logging.getLogger('boto').setLevel(logging.CRITICAL) logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=unused-import log = logging.getLogger(__name__) def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'iam', pack=__salt__) def instance_profile_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an instance profile exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: # Boto weirdly returns an exception here if an instance profile doesn't # exist. conn.get_instance_profile(name) return True except boto.exception.BotoServerError: return False def create_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Create an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.create_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if instance_profile_exists(name, region, key, keyid, profile): return True try: # This call returns an instance profile if successful and an exception # if not. It's annoying. conn.create_instance_profile(name) log.info('Created %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create %s instance profile.', name) return False return True def delete_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Delete an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not instance_profile_exists(name, region, key, keyid, profile): return True try: conn.delete_instance_profile(name) log.info('Deleted %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s instance profile.', name) return False return True def role_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an IAM role exists. CLI Example: .. code-block:: bash salt myminion boto_iam.role_exists myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_role(name) return True except boto.exception.BotoServerError: return False def describe_role(name, region=None, key=None, keyid=None, profile=None): ''' Get information for a role. CLI Example: .. code-block:: bash salt myminion boto_iam.describe_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_role(name) if not info: return False role = info.get_role_response.get_role_result.role role['assume_role_policy_document'] = salt.utils.json.loads(_unquote( role.assume_role_policy_document )) # If Sid wasn't defined by the user, boto will still return a Sid in # each policy. To properly check idempotently, let's remove the Sid # from the return if it's not actually set. for policy_key, policy in role['assume_role_policy_document'].items(): if policy_key == 'Statement': for val in policy: if 'Sid' in val and not val['Sid']: del val['Sid'] return role except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get %s information.', name) return False def create_user(user_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_user myuser ''' if not path: path = '/' if get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_user(user_name, path) log.info('Created IAM user : %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM user %s.', user_name) return False def get_all_access_keys(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all access keys from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_access_keys myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.get_all_access_keys(user_name, marker, max_items) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get access keys for IAM user %s.', user_name) return six.text_type(e) def create_access_key(user_name, region=None, key=None, keyid=None, profile=None): ''' Create access key id for a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.create_access_key(user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create access key.') return six.text_type(e) def delete_access_key(access_key_id, user_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete access key id from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_access_key(access_key_id, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete access key id %s.', access_key_id) return six.text_type(e) def delete_user(user_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user myuser ''' if not get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.delete_user(user_name) log.info('Deleted IAM user : %s .', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM user %s', user_name) return six.text_type(e) def get_user(user_name=None, region=None, key=None, keyid=None, profile=None): ''' Get user information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user(user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM user %s info.', user_name) return False def create_group(group_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_group group ''' if not path: path = '/' if get_group(group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_group(group_name, path) log.info('Created IAM group : %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM group %s.', group_name) return False def get_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group(group_name, max_items=1) if not info: return False return info['get_group_response']['get_group_result']['group'] except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_group_members(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: marker = None truncated = True users = [] while truncated: info = conn.get_group(group_name, marker=marker, max_items=1000) if not info: return False truncated = bool(info['get_group_response']['get_group_result']['is_truncated']) if truncated and 'marker' in info['get_group_response']['get_group_result']: marker = info['get_group_response']['get_group_result']['marker'] else: marker = None truncated = False users += info['get_group_response']['get_group_result']['users'] return users except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get members for IAM group %s.', group_name) return False def add_user_to_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Add user to group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.add_user_to_group myuser mygroup ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('Username : %s does not exist.', user_name) return False if user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.add_user_to_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add IAM user %s to group %s.', user_name, group_name) return False def user_exists_in_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Check if user exists in group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.user_exists_in_group myuser mygroup ''' # TODO this should probably use boto.iam.get_groups_for_user users = get_group_members( group_name=group_name, region=region, key=key, keyid=keyid, profile=profile ) if users: for _user in users: if user_name == _user['user_name']: log.debug('IAM user %s is already in IAM group %s.', user_name, group_name) return True return False def remove_user_from_group(group_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Remove user from group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.remove_user_from_group mygroup myuser ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist.', user_name) return False if not user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.remove_user_from_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove IAM user %s from group %s', user_name, group_name) return False def put_group_policy(group_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_group_policy mygroup policyname policyrules ''' group = get_group(group_name, region=region, key=key, keyid=keyid, profile=profile) if not group: log.error('Group %s does not exist', group_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_group_policy(group_name, policy_name, policy_json) if created: log.info('Created policy for IAM group %s.', group_name) return True log.error('Could not create policy for IAM group %s', group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy for IAM group %s', group_name) return False def delete_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group_policy mygroup mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_group_policy( group_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_group_policy(group_name, policy_name) log.info('Successfully deleted policy %s for IAM group %s.', policy_name, group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM group %s.', policy_name, group_name) return False def get_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group_policy mygroup policyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group_policy(group_name, policy_name) log.debug('info for group policy is : %s', info) if not info: return False info = info.get_group_policy_response.get_group_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_all_groups(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM group details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_groups ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _groups = conn.get_all_groups(path_prefix=path_prefix) groups = _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) while marker: _groups = conn.get_all_groups(path_prefix=path_prefix, marker=marker) groups = groups + _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) return groups def get_all_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.get_all_instance_profiles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) marker = False profiles = [] while marker is not None: marker = marker if marker else None p = conn.list_instance_profiles(path_prefix=path_prefix, marker=marker) res = p.list_instance_profiles_response.list_instance_profiles_result profiles += res.instance_profiles marker = getattr(res, 'marker', None) return profiles def list_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' List all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.list_instance_profiles ''' p = get_all_instance_profiles(path_prefix, region, key, keyid, profile) return [i['instance_profile_name'] for i in p] def get_all_group_policies(group_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a group. CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_group_policies mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False try: response = conn.get_all_group_policies(group_name) _list = response.list_group_policies_response.list_group_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def delete_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _group = get_group( group_name, region, key, keyid, profile ) if not _group: return True try: conn.delete_group(group_name) log.info('Successfully deleted IAM group %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM group %s.', group_name) return False def create_login_profile(user_name, password, region=None, key=None, keyid=None, profile=None): ''' Creates a login profile for the specified user, give the user the ability to access AWS services and the AWS Management Console. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_login_profile user_name password ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.create_login_profile(user_name, password) log.info('Created profile for IAM user %s.', user_name) return info except boto.exception.BotoServerError as e: log.debug(e) if 'Conflict' in e: log.info('Profile already exists for IAM user %s.', user_name) return 'Conflict' log.error('Failed to update profile for IAM user %s.', user_name) return False def delete_login_profile(user_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a login profile for the specified user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_login_profile user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.delete_login_profile(user_name) log.info('Deleted login profile for IAM user %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Login profile already deleted for IAM user %s.', user_name) return True log.error('Failed to delete login profile for IAM user %s.', user_name) return False def get_all_mfa_devices(user_name, region=None, key=None, keyid=None, profile=None): ''' Get all MFA devices associated with an IAM user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_mfa_devices user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: result = conn.get_all_mfa_devices(user_name) devices = result['list_mfa_devices_response']['list_mfa_devices_result']['mfa_devices'] return devices except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Could not find IAM user %s.', user_name) return [] log.error('Failed to get all MFA devices for IAM user %s.', user_name) return False def deactivate_mfa_device(user_name, serial, region=None, key=None, keyid=None, profile=None): ''' Deactivates the specified MFA device and removes it from association with the user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.deactivate_mfa_device user_name serial_num ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.deactivate_mfa_device(user_name, serial) log.info('Deactivated MFA device %s for IAM user %s.', serial, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('MFA device %s not associated with IAM user %s.', serial, user_name) return True log.error('Failed to deactivate MFA device %s for IAM user %s.', serial, user_name) return False def delete_virtual_mfa_device(serial, region=None, key=None, keyid=None, profile=None): ''' Deletes the specified virtual MFA device. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_virtual_mfa_device serial_num ''' conn = __utils__['boto3.get_connection_func']('iam')() try: conn.delete_virtual_mfa_device(SerialNumber=serial) log.info('Deleted virtual MFA device %s.', serial) return True except botocore.exceptions.ClientError as e: log.debug(e) if 'NoSuchEntity' in six.text_type(e): log.info('Virtual MFA device %s not found.', serial) return True log.error('Failed to delete virtual MFA device %s.', serial) return False def update_account_password_policy(allow_users_to_change_password=None, hard_expiry=None, max_password_age=None, minimum_password_length=None, password_reuse_prevention=None, require_lowercase_characters=None, require_numbers=None, require_symbols=None, require_uppercase_characters=None, region=None, key=None, keyid=None, profile=None): ''' Update the password policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_account_password_policy True ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.update_account_password_policy(allow_users_to_change_password, hard_expiry, max_password_age, minimum_password_length, password_reuse_prevention, require_lowercase_characters, require_numbers, require_symbols, require_uppercase_characters) log.info('The password policy has been updated.') return True except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy' log.error(msg) return False def get_account_policy(region=None, key=None, keyid=None, profile=None): ''' Get account policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_account_password_policy() return info.get_account_password_policy_response.get_account_password_policy_result.password_policy except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy.' log.error(msg) return False def create_role(name, policy_document=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Create an instance role. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if role_exists(name, region, key, keyid, profile): return True if not policy_document: policy_document = None try: conn.create_role(name, assume_role_policy_document=policy_document, path=path) log.info('Created IAM role %s.', name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to create IAM role %s.', name) return False def delete_role(name, region=None, key=None, keyid=None, profile=None): ''' Delete an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(name, region, key, keyid, profile): return True try: conn.delete_role(name) log.info('Deleted %s IAM role.', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s IAM role.', name) return False def profile_associated(role_name, profile_name, region, key, keyid, profile): ''' Check to see if an instance profile is associated with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.profile_associated myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # The IAM module of boto doesn't return objects. Instead you need to grab # values through its properties. Sigh. try: profiles = conn.list_instance_profiles_for_role(role_name) except boto.exception.BotoServerError as e: log.debug(e) return False profiles = profiles.list_instance_profiles_for_role_response profiles = profiles.list_instance_profiles_for_role_result profiles = profiles.instance_profiles for profile in profiles: if profile.instance_profile_name == profile_name: return True return False def associate_profile_to_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Associate an instance profile with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.associate_profile_to_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if associated: return True else: try: conn.add_role_to_instance_profile(profile_name, role_name) log.info('Added %s instance profile to IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add %s instance profile to IAM role %s', profile_name, role_name) return False def disassociate_profile_from_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Disassociate an instance profile from an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.disassociate_profile_from_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if not associated: return True else: try: conn.remove_role_from_instance_profile(profile_name, role_name) log.info('Removed %s instance profile from IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove %s instance profile from IAM role %s.', profile_name, role_name) return False def list_role_policies(role_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_role_policies myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_role_policies(role_name) _list = response.list_role_policies_response.list_role_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def get_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.get_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: _policy = conn.get_role_policy(role_name, policy_name) # I _hate_ you for not giving me an object boto. _policy = _policy.get_role_policy_response.policy_document # Policy is url encoded _policy = _unquote(_policy) _policy = salt.utils.json.loads(_policy, object_pairs_hook=odict.OrderedDict) return _policy except boto.exception.BotoServerError: return {} def create_role_policy(role_name, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Create or modify a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role_policy myirole mypolicy '{"MyPolicy": "Statement": [{"Action": ["sqs:*"], "Effect": "Allow", "Resource": ["arn:aws:sqs:*:*:*"], "Sid": "MyPolicySqs1"}]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) mode = 'create' if _policy: if _policy == policy: return True mode = 'modify' if isinstance(policy, six.string_types): policy = salt.utils.json.loads(policy, object_pairs_hook=odict.OrderedDict) try: _policy = salt.utils.json.dumps(policy) conn.put_role_policy(role_name, policy_name, _policy) if mode == 'create': msg = 'Successfully added policy %s to IAM role %s.' else: msg = 'Successfully modified policy %s for IAM role %s.' log.info(msg, policy_name, role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to %s policy %s for IAM role %s.', mode, policy_name, role_name) return False def delete_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) if not _policy: return True try: conn.delete_role_policy(role_name, policy_name) log.info('Successfully deleted policy %s for IAM role %s.', policy_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM role %s.', policy_name, role_name) return False def update_assume_role_policy(role_name, policy_document, region=None, key=None, keyid=None, profile=None): ''' Update an assume role policy for a role. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_assume_role_policy myrole '{"Statement":"..."}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(policy_document, six.string_types): policy_document = salt.utils.json.loads(policy_document, object_pairs_hook=odict.OrderedDict) try: _policy_document = salt.utils.json.dumps(policy_document) conn.update_assume_role_policy(role_name, _policy_document) log.info('Successfully updated assume role policy for IAM role %s.', role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to update assume role policy for IAM role %s.', role_name) return False def build_policy(region=None, key=None, keyid=None, profile=None): ''' Build a default assume role policy. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.build_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if hasattr(conn, 'build_policy'): policy = salt.utils.json.loads(conn.build_policy()) elif hasattr(conn, '_build_policy'): policy = salt.utils.json.loads(conn._build_policy()) else: return {} # The format we get from build_policy isn't going to be what we get back # from AWS for the exact same policy. AWS converts single item list values # into strings, so let's do the same here. for key, policy_val in policy.items(): for statement in policy_val: if (isinstance(statement['Action'], list) and len(statement['Action']) == 1): statement['Action'] = statement['Action'][0] if (isinstance(statement['Principal']['Service'], list) and len(statement['Principal']['Service']) == 1): statement['Principal']['Service'] = statement['Principal']['Service'][0] # build_policy doesn't add a version field, which AWS is going to set to a # default value, when we get it back, so let's set it. policy['Version'] = '2008-10-17' return policy def get_account_id(region=None, key=None, keyid=None, profile=None): ''' Get a the AWS account id associated with the used credentials. CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_id ''' cache_key = 'boto_iam.account_id' if cache_key not in __context__: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_user() # The get_user call returns an user ARN: # arn:aws:iam::027050522557:user/salt-test arn = ret['get_user_response']['get_user_result']['user']['arn'] account_id = arn.split(':')[4] except boto.exception.BotoServerError: # If call failed, then let's try to get the ARN from the metadata timeout = boto.config.getfloat( 'Boto', 'metadata_service_timeout', 1.0 ) attempts = boto.config.getint( 'Boto', 'metadata_service_num_attempts', 1 ) identity = boto.utils.get_instance_identity( timeout=timeout, num_retries=attempts ) try: account_id = identity['document']['accountId'] except KeyError: log.error('Failed to get account id from instance_identity in' ' boto_iam.get_account_id.') __context__[cache_key] = account_id return __context__[cache_key] def get_all_roles(path_prefix=None, region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM role details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_roles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _roles = conn.list_roles(path_prefix=path_prefix) roles = _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) while marker: _roles = conn.list_roles(path_prefix=path_prefix, marker=marker) roles = roles + _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) return roles def get_all_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM user details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_users ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _users = conn.get_all_users(path_prefix=path_prefix) users = _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) while marker: _users = conn.get_all_users(path_prefix=path_prefix, marker=marker) users = users + _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) return users def get_all_user_policies(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all user policies. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_user_policies myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_all_user_policies(user_name, marker, max_items) if not info: return False _list = info.list_user_policies_response.list_user_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policies for user %s.', user_name) return False def get_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user_policy myuser mypolicyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user_policy(user_name, policy_name) log.debug('Info for IAM user %s policy %s: %s.', user_name, policy_name, info) if not info: return False info = info.get_user_policy_response.get_user_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policy %s for IAM user %s.', policy_name, user_name) return False def put_user_policy(user_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_user_policy myuser policyname policyrules ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_user_policy(user_name, policy_name, policy_json) if created: log.info('Created policy %s for IAM user %s.', policy_name, user_name) return True log.error('Could not create policy %s for IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy %s for IAM user %s.', policy_name, user_name) return False def delete_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user_policy myuser mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_user_policy( user_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_user_policy(user_name, policy_name) log.info('Successfully deleted policy %s for IAM user %s.', policy_name, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM user %s.', policy_name, user_name) return False def upload_server_cert(cert_name, cert_body, private_key, cert_chain=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Upload a certificate to Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.upload_server_cert mycert_name crt priv_key :param cert_name: The name for the server certificate. Do not include the path in this value. :param cert_body: The contents of the public key certificate in PEM-encoded format. :param private_key: The contents of the private key in PEM-encoded format. :param cert_chain: The contents of the certificate chain. This is typically a concatenation of the PEM-encoded public key certificates of the chain. :param path: The path for the server certificate. :param region: The name of the region to connect to. :param key: The key to be used in order to connect :param keyid: The keyid to be used in order to connect :param profile: The profile that contains a dict of region, key, keyid :return: True / False ''' exists = get_server_certificate(cert_name, region, key, keyid, profile) if exists: return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.upload_server_cert(cert_name, cert_body, private_key, cert_chain) log.info('Created certificate %s.', cert_name) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to failed to create certificate %s.', cert_name) return False def list_server_certificates(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Lists the server certificates stored in IAM that have the specified path prefix. .. versionadded:: ??? :param path_prefix: The path prefix for filtering the results. For example: /company/servercerts would get all server certificates for which the path starts with /company/servercerts . This parameter is optional. If it is not included, it defaults to a slash (/), listing all server certificates. This parameter allows (per its regex pattern) a string of characters consisting of either a forward slash (/) by itself or a string that must begin and end with forward slashes. In addition, it can contain any ASCII character from the ! (u0021) through the DEL character (u007F), including most punctuation characters, digits, and upper and lowercased letters. CLI Example: .. code-block:: bash salt myminion boto_iam.list_server_certificates path_prefix=/somepath/ ''' retries = 10 sleep = 6 conn = __utils__['boto3.get_connection']('iam', region=region, key=key, keyid=keyid, profile=profile) Items = [] while retries: try: log.debug('Garnering list of IAM Server Certificates') IsTruncated = True while IsTruncated: kwargs = {'PathPrefix': path_prefix} ret = conn.list_server_certificates(**kwargs) Items += ret.get('ServerCertificateMetadataList', []) IsTruncated = ret.get('IsTruncated') kwargs.update({'Marker': ret.get('Marker')}) return Items except botocore.exceptions.ParamValidationError as err: raise SaltInvocationError(str(err)) except botocore.exceptions.ClientError as err: if retries and jmespath.search('Error.Code', err.response) == 'Throttling': retries -= 1 log.debug('Throttled by AWS API, retrying in %s seconds...', sleep) time.sleep(sleep) continue log.error('Failed to list IAM Server Certificates: %s', err.message) return None def get_server_certificate(cert_name, region=None, key=None, keyid=None, profile=None): ''' Returns certificate information from Amazon .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_server_certificate mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_server_certificate(cert_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get certificate %s information.', cert_name) return False def delete_server_cert(cert_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a certificate from Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_server_cert mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_server_cert(cert_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete certificate %s.', cert_name) return False def export_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM user details. Produces results that can be used to create an sls file. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.export_users --out=txt | sed "s/local: //" > iam_users.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() users = get_all_users(path_prefix, region, key, keyid, profile) for user in users: name = user.user_name _policies = conn.get_all_user_policies(name, max_items=100) _policies = _policies.list_user_policies_response.list_user_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_user_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_user_policy_response.get_user_policy_result.policy_document )) policies[policy_name] = _policy user_sls = [] user_sls.append({"name": name}) user_sls.append({"policies": policies}) user_sls.append({"path": user.path}) results["manage user " + name] = {"boto_iam.user_present": user_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def export_roles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM role details. Produces results that can be used to create an sls file. CLI Example: salt-call boto_iam.export_roles --out=txt | sed "s/local: //" > iam_roles.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() roles = get_all_roles(path_prefix, region, key, keyid, profile) for role in roles: name = role.role_name _policies = conn.list_role_policies(name, max_items=100) _policies = _policies.list_role_policies_response.list_role_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_role_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_role_policy_response.get_role_policy_result.policy_document )) policies[policy_name] = _policy role_sls = [] role_sls.append({"name": name}) role_sls.append({"policies": policies}) role_sls.append({'policy_document': salt.utils.json.loads(_unquote(role.assume_role_policy_document))}) role_sls.append({"path": role.path}) results["manage role " + name] = {"boto_iam_role.present": role_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def _get_policy_arn(name, region=None, key=None, keyid=None, profile=None): if name.startswith('arn:aws:iam:'): return name account_id = get_account_id( region=region, key=key, keyid=keyid, profile=profile ) return 'arn:aws:iam::{0}:policy/{1}'.format(account_id, name) def policy_exists(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return True except boto.exception.BotoServerError: return False def get_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return ret.get('get_policy_response', {}).get('get_policy_result', {}) except boto.exception.BotoServerError: return None def create_policy(policy_name, policy_document, path=None, description=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in 'path', 'description': if locals()[arg] is not None: params[arg] = locals()[arg] if policy_exists(policy_name, region, key, keyid, profile): return True try: conn.create_policy(policy_name, policy_document, **params) log.info('Created IAM policy %s.', policy_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s.', policy_name) return False return True def delete_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_exists(policy_arn, region, key, keyid, profile): return True try: conn.delete_policy(policy_arn) log.info('Deleted %s policy.', policy_name) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete %s policy: %s.', policy_name, aws.get('message')) return False return True def list_policies(region=None, key=None, keyid=None, profile=None): ''' List policies. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policies ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: policies = [] for ret in __utils__['boto.paged_call'](conn.list_policies): policies.append(ret.get('list_policies_response', {}).get('list_policies_result', {}).get('policies')) return policies except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to list policy versions.' log.error(msg) return [] def policy_version_exists(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.get_policy_version(policy_arn, version_id) return True except boto.exception.BotoServerError: return False def create_policy_version(policy_name, policy_document, set_as_default=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy version. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy_version mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in ('set_as_default',): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.create_policy_version(policy_arn, policy_document, **params) vid = ret.get('create_policy_version_response', {}).get('create_policy_version_result', {}).get('policy_version', {}).get('version_id') log.info('Created IAM policy %s version %s.', policy_name, vid) return {'created': True, 'version_id': vid} except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s version %s.', policy_name, vid) return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Delete a policy version. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_version_exists(policy_arn, version_id, region, key, keyid, profile): return True try: conn.delete_policy_version(policy_arn, version_id) log.info('Deleted IAM policy %s version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete IAM policy %s version %s: %s', policy_name, version_id, aws.get('message')) return False return True def list_policy_versions(policy_name, region=None, key=None, keyid=None, profile=None): ''' List versions of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policy_versions mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.list_policy_versions(policy_arn) return ret.get('list_policy_versions_response', {}).get('list_policy_versions_result', {}).get('versions') except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list versions for IAM policy %s.', policy_name) return [] def set_default_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Set the default version of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.set_default_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.set_default_policy_version(policy_arn, version_id) log.info('Set %s policy to version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to set %s policy to version %s: %s', policy_name, version_id, aws.get('message')) return False return True def attach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_user_policy(policy_arn, user_name) log.info('Attached policy %s to IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach %s policy to IAM user %s.', policy_name, user_name) return False return True def detach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_user_policy(policy_arn, user_name) log.info('Detached %s policy from IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach %s policy from IAM user %s.', policy_name, user_name) return False return True def attach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_group_policy(policy_arn, group_name) log.info('Attached policy %s to IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM group %s.', policy_name, group_name) return False return True def detach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_group_policy(policy_arn, group_name) log.info('Detached policy %s from IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM group %s.', policy_name, group_name) return False return True def attach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_role_policy(policy_arn, role_name) log.info('Attached policy %s to IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM role %s.', policy_name, role_name) return False return True def detach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_role_policy(policy_arn, role_name) log.info('Detached policy %s from IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM role %s.', policy_name, role_name) return False return True def list_entities_for_policy(policy_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities that a policy is attached to. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 params = {} for arg in ('path_prefix', 'entity_filter'): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) while retries: try: allret = { 'policy_groups': [], 'policy_users': [], 'policy_roles': [], } for ret in __utils__['boto.paged_call'](conn.list_entities_for_policy, policy_arn=policy_arn, **params): for k, v in six.iteritems(allret): v.extend(ret.get('list_entities_for_policy_response', {}).get('list_entities_for_policy_result', {}).get(k)) return allret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('Failed to list entities for IAM policy %s: %s', policy_name, e.message) return {} return {} def list_attached_user_policies(user_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given user. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'UserName': user_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedUserPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_user_policies_response', {}).get('list_attached_user_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM user %s.', user_name) return [] def list_attached_group_policies(group_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given group. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'GroupName': group_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedGroupPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_group_policies_response', {}).get('list_attached_group_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM group %s.', group_name) return [] def list_attached_role_policies(role_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'RoleName': role_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedRolePolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_role_policies_response', {}).get('list_attached_role_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM role %s.', role_name) return [] def create_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Create SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.create_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_saml_provider(saml_metadata_document, name) log.info('Successfully created %s SAML provider.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to create SAML provider %s.', name) return False def get_saml_provider_arn(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider_arn my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_saml_providers() for saml_provider in response.list_saml_providers_response.list_saml_providers_result.saml_provider_list: if saml_provider['arn'].endswith(':saml-provider/' + name): return saml_provider['arn'] return False except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to get ARN of SAML provider %s.', name) return False def delete_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Delete SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.delete_saml_provider my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return True conn.delete_saml_provider(saml_provider_arn) log.info('Successfully deleted SAML provider %s.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete SAML provider %s.', name) return False def list_saml_providers(region=None, key=None, keyid=None, profile=None): ''' List SAML providers. CLI Example: .. code-block:: bash salt myminion boto_iam.list_saml_providers ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: providers = [] info = conn.list_saml_providers() for arn in info['list_saml_providers_response']['list_saml_providers_result']['saml_provider_list']: providers.append(arn['arn'].rsplit('/', 1)[1]) return providers except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get list of SAML providers.') return False def get_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider document. CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider arn ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: provider = conn.get_saml_provider(name) return provider['get_saml_provider_response']['get_saml_provider_result']['saml_metadata_document'] except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get SAML provider document %s.', name) return False def update_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Update SAML provider. CLI Example: .. code-block:: bash salt myminion boto_iam.update_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return False if conn.update_saml_provider(name, saml_metadata_document): return True return False except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to update SAML provider %s.', name) return False
saltstack/salt
salt/modules/boto_iam.py
create_policy_version
python
def create_policy_version(policy_name, policy_document, set_as_default=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy version. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy_version mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in ('set_as_default',): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.create_policy_version(policy_arn, policy_document, **params) vid = ret.get('create_policy_version_response', {}).get('create_policy_version_result', {}).get('policy_version', {}).get('version_id') log.info('Created IAM policy %s version %s.', policy_name, vid) return {'created': True, 'version_id': vid} except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s version %s.', policy_name, vid) return {'created': False, 'error': __utils__['boto.get_error'](e)}
Create a policy version. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy_version mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iam.py#L1874-L1902
[ "def dumps(obj, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.dumps, and assumes that ensure_ascii is False (unless explicitly\n passed as True) for unicode compatibility. Note that setting it to True\n will mess up any unicode characters, as they will be dumped as the string\n literal version of the unicode code point.\n\n On Python 2, encodes the result to a str since json.dumps does not want\n unicode types.\n\n You can pass an alternate json module (loaded via import_json() above)\n using the _json_module argument)\n '''\n json_module = kwargs.pop('_json_module', json)\n orig_enc_func = kwargs.pop('default', lambda x: x)\n\n def _enc_func(obj):\n obj = ThreadLocalProxy.unproxy(obj)\n return orig_enc_func(obj)\n\n if 'ensure_ascii' not in kwargs:\n kwargs['ensure_ascii'] = False\n if six.PY2:\n obj = salt.utils.data.encode(obj)\n return json_module.dumps(obj, default=_enc_func, **kwargs) # future lint: blacklisted-function\n", "def _get_policy_arn(name, region=None, key=None, keyid=None, profile=None):\n if name.startswith('arn:aws:iam:'):\n return name\n\n account_id = get_account_id(\n region=region, key=key, keyid=keyid, profile=profile\n )\n return 'arn:aws:iam::{0}:policy/{1}'.format(account_id, name)\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon IAM .. versionadded:: 2014.7.0 :configuration: This module accepts explicit iam 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 iam.keyid: GKTADJGHEIQSXMKKRBJ08H iam.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs iam.region: 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: boto ''' # keep lint from choking on _get_conn and _cache_id #pylint: disable=E0602 # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import salt libs from salt.ext import six import salt.utils.compat import salt.utils.json import salt.utils.odict as odict import salt.utils.versions from salt.exceptions import SaltInvocationError # Import third party libs # pylint: disable=unused-import from salt.ext.six.moves.urllib.parse import unquote as _unquote # pylint: disable=no-name-in-module try: import boto import boto.iam import boto3 import botocore logging.getLogger('boto').setLevel(logging.CRITICAL) logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=unused-import log = logging.getLogger(__name__) def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'iam', pack=__salt__) def instance_profile_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an instance profile exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: # Boto weirdly returns an exception here if an instance profile doesn't # exist. conn.get_instance_profile(name) return True except boto.exception.BotoServerError: return False def create_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Create an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.create_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if instance_profile_exists(name, region, key, keyid, profile): return True try: # This call returns an instance profile if successful and an exception # if not. It's annoying. conn.create_instance_profile(name) log.info('Created %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create %s instance profile.', name) return False return True def delete_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Delete an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not instance_profile_exists(name, region, key, keyid, profile): return True try: conn.delete_instance_profile(name) log.info('Deleted %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s instance profile.', name) return False return True def role_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an IAM role exists. CLI Example: .. code-block:: bash salt myminion boto_iam.role_exists myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_role(name) return True except boto.exception.BotoServerError: return False def describe_role(name, region=None, key=None, keyid=None, profile=None): ''' Get information for a role. CLI Example: .. code-block:: bash salt myminion boto_iam.describe_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_role(name) if not info: return False role = info.get_role_response.get_role_result.role role['assume_role_policy_document'] = salt.utils.json.loads(_unquote( role.assume_role_policy_document )) # If Sid wasn't defined by the user, boto will still return a Sid in # each policy. To properly check idempotently, let's remove the Sid # from the return if it's not actually set. for policy_key, policy in role['assume_role_policy_document'].items(): if policy_key == 'Statement': for val in policy: if 'Sid' in val and not val['Sid']: del val['Sid'] return role except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get %s information.', name) return False def create_user(user_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_user myuser ''' if not path: path = '/' if get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_user(user_name, path) log.info('Created IAM user : %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM user %s.', user_name) return False def get_all_access_keys(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all access keys from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_access_keys myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.get_all_access_keys(user_name, marker, max_items) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get access keys for IAM user %s.', user_name) return six.text_type(e) def create_access_key(user_name, region=None, key=None, keyid=None, profile=None): ''' Create access key id for a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.create_access_key(user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create access key.') return six.text_type(e) def delete_access_key(access_key_id, user_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete access key id from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_access_key(access_key_id, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete access key id %s.', access_key_id) return six.text_type(e) def delete_user(user_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user myuser ''' if not get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.delete_user(user_name) log.info('Deleted IAM user : %s .', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM user %s', user_name) return six.text_type(e) def get_user(user_name=None, region=None, key=None, keyid=None, profile=None): ''' Get user information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user(user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM user %s info.', user_name) return False def create_group(group_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_group group ''' if not path: path = '/' if get_group(group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_group(group_name, path) log.info('Created IAM group : %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM group %s.', group_name) return False def get_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group(group_name, max_items=1) if not info: return False return info['get_group_response']['get_group_result']['group'] except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_group_members(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: marker = None truncated = True users = [] while truncated: info = conn.get_group(group_name, marker=marker, max_items=1000) if not info: return False truncated = bool(info['get_group_response']['get_group_result']['is_truncated']) if truncated and 'marker' in info['get_group_response']['get_group_result']: marker = info['get_group_response']['get_group_result']['marker'] else: marker = None truncated = False users += info['get_group_response']['get_group_result']['users'] return users except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get members for IAM group %s.', group_name) return False def add_user_to_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Add user to group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.add_user_to_group myuser mygroup ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('Username : %s does not exist.', user_name) return False if user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.add_user_to_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add IAM user %s to group %s.', user_name, group_name) return False def user_exists_in_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Check if user exists in group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.user_exists_in_group myuser mygroup ''' # TODO this should probably use boto.iam.get_groups_for_user users = get_group_members( group_name=group_name, region=region, key=key, keyid=keyid, profile=profile ) if users: for _user in users: if user_name == _user['user_name']: log.debug('IAM user %s is already in IAM group %s.', user_name, group_name) return True return False def remove_user_from_group(group_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Remove user from group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.remove_user_from_group mygroup myuser ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist.', user_name) return False if not user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.remove_user_from_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove IAM user %s from group %s', user_name, group_name) return False def put_group_policy(group_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_group_policy mygroup policyname policyrules ''' group = get_group(group_name, region=region, key=key, keyid=keyid, profile=profile) if not group: log.error('Group %s does not exist', group_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_group_policy(group_name, policy_name, policy_json) if created: log.info('Created policy for IAM group %s.', group_name) return True log.error('Could not create policy for IAM group %s', group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy for IAM group %s', group_name) return False def delete_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group_policy mygroup mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_group_policy( group_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_group_policy(group_name, policy_name) log.info('Successfully deleted policy %s for IAM group %s.', policy_name, group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM group %s.', policy_name, group_name) return False def get_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group_policy mygroup policyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group_policy(group_name, policy_name) log.debug('info for group policy is : %s', info) if not info: return False info = info.get_group_policy_response.get_group_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_all_groups(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM group details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_groups ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _groups = conn.get_all_groups(path_prefix=path_prefix) groups = _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) while marker: _groups = conn.get_all_groups(path_prefix=path_prefix, marker=marker) groups = groups + _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) return groups def get_all_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.get_all_instance_profiles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) marker = False profiles = [] while marker is not None: marker = marker if marker else None p = conn.list_instance_profiles(path_prefix=path_prefix, marker=marker) res = p.list_instance_profiles_response.list_instance_profiles_result profiles += res.instance_profiles marker = getattr(res, 'marker', None) return profiles def list_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' List all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.list_instance_profiles ''' p = get_all_instance_profiles(path_prefix, region, key, keyid, profile) return [i['instance_profile_name'] for i in p] def get_all_group_policies(group_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a group. CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_group_policies mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False try: response = conn.get_all_group_policies(group_name) _list = response.list_group_policies_response.list_group_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def delete_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _group = get_group( group_name, region, key, keyid, profile ) if not _group: return True try: conn.delete_group(group_name) log.info('Successfully deleted IAM group %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM group %s.', group_name) return False def create_login_profile(user_name, password, region=None, key=None, keyid=None, profile=None): ''' Creates a login profile for the specified user, give the user the ability to access AWS services and the AWS Management Console. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_login_profile user_name password ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.create_login_profile(user_name, password) log.info('Created profile for IAM user %s.', user_name) return info except boto.exception.BotoServerError as e: log.debug(e) if 'Conflict' in e: log.info('Profile already exists for IAM user %s.', user_name) return 'Conflict' log.error('Failed to update profile for IAM user %s.', user_name) return False def delete_login_profile(user_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a login profile for the specified user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_login_profile user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.delete_login_profile(user_name) log.info('Deleted login profile for IAM user %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Login profile already deleted for IAM user %s.', user_name) return True log.error('Failed to delete login profile for IAM user %s.', user_name) return False def get_all_mfa_devices(user_name, region=None, key=None, keyid=None, profile=None): ''' Get all MFA devices associated with an IAM user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_mfa_devices user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: result = conn.get_all_mfa_devices(user_name) devices = result['list_mfa_devices_response']['list_mfa_devices_result']['mfa_devices'] return devices except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Could not find IAM user %s.', user_name) return [] log.error('Failed to get all MFA devices for IAM user %s.', user_name) return False def deactivate_mfa_device(user_name, serial, region=None, key=None, keyid=None, profile=None): ''' Deactivates the specified MFA device and removes it from association with the user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.deactivate_mfa_device user_name serial_num ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.deactivate_mfa_device(user_name, serial) log.info('Deactivated MFA device %s for IAM user %s.', serial, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('MFA device %s not associated with IAM user %s.', serial, user_name) return True log.error('Failed to deactivate MFA device %s for IAM user %s.', serial, user_name) return False def delete_virtual_mfa_device(serial, region=None, key=None, keyid=None, profile=None): ''' Deletes the specified virtual MFA device. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_virtual_mfa_device serial_num ''' conn = __utils__['boto3.get_connection_func']('iam')() try: conn.delete_virtual_mfa_device(SerialNumber=serial) log.info('Deleted virtual MFA device %s.', serial) return True except botocore.exceptions.ClientError as e: log.debug(e) if 'NoSuchEntity' in six.text_type(e): log.info('Virtual MFA device %s not found.', serial) return True log.error('Failed to delete virtual MFA device %s.', serial) return False def update_account_password_policy(allow_users_to_change_password=None, hard_expiry=None, max_password_age=None, minimum_password_length=None, password_reuse_prevention=None, require_lowercase_characters=None, require_numbers=None, require_symbols=None, require_uppercase_characters=None, region=None, key=None, keyid=None, profile=None): ''' Update the password policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_account_password_policy True ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.update_account_password_policy(allow_users_to_change_password, hard_expiry, max_password_age, minimum_password_length, password_reuse_prevention, require_lowercase_characters, require_numbers, require_symbols, require_uppercase_characters) log.info('The password policy has been updated.') return True except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy' log.error(msg) return False def get_account_policy(region=None, key=None, keyid=None, profile=None): ''' Get account policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_account_password_policy() return info.get_account_password_policy_response.get_account_password_policy_result.password_policy except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy.' log.error(msg) return False def create_role(name, policy_document=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Create an instance role. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if role_exists(name, region, key, keyid, profile): return True if not policy_document: policy_document = None try: conn.create_role(name, assume_role_policy_document=policy_document, path=path) log.info('Created IAM role %s.', name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to create IAM role %s.', name) return False def delete_role(name, region=None, key=None, keyid=None, profile=None): ''' Delete an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(name, region, key, keyid, profile): return True try: conn.delete_role(name) log.info('Deleted %s IAM role.', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s IAM role.', name) return False def profile_associated(role_name, profile_name, region, key, keyid, profile): ''' Check to see if an instance profile is associated with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.profile_associated myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # The IAM module of boto doesn't return objects. Instead you need to grab # values through its properties. Sigh. try: profiles = conn.list_instance_profiles_for_role(role_name) except boto.exception.BotoServerError as e: log.debug(e) return False profiles = profiles.list_instance_profiles_for_role_response profiles = profiles.list_instance_profiles_for_role_result profiles = profiles.instance_profiles for profile in profiles: if profile.instance_profile_name == profile_name: return True return False def associate_profile_to_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Associate an instance profile with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.associate_profile_to_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if associated: return True else: try: conn.add_role_to_instance_profile(profile_name, role_name) log.info('Added %s instance profile to IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add %s instance profile to IAM role %s', profile_name, role_name) return False def disassociate_profile_from_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Disassociate an instance profile from an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.disassociate_profile_from_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if not associated: return True else: try: conn.remove_role_from_instance_profile(profile_name, role_name) log.info('Removed %s instance profile from IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove %s instance profile from IAM role %s.', profile_name, role_name) return False def list_role_policies(role_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_role_policies myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_role_policies(role_name) _list = response.list_role_policies_response.list_role_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def get_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.get_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: _policy = conn.get_role_policy(role_name, policy_name) # I _hate_ you for not giving me an object boto. _policy = _policy.get_role_policy_response.policy_document # Policy is url encoded _policy = _unquote(_policy) _policy = salt.utils.json.loads(_policy, object_pairs_hook=odict.OrderedDict) return _policy except boto.exception.BotoServerError: return {} def create_role_policy(role_name, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Create or modify a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role_policy myirole mypolicy '{"MyPolicy": "Statement": [{"Action": ["sqs:*"], "Effect": "Allow", "Resource": ["arn:aws:sqs:*:*:*"], "Sid": "MyPolicySqs1"}]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) mode = 'create' if _policy: if _policy == policy: return True mode = 'modify' if isinstance(policy, six.string_types): policy = salt.utils.json.loads(policy, object_pairs_hook=odict.OrderedDict) try: _policy = salt.utils.json.dumps(policy) conn.put_role_policy(role_name, policy_name, _policy) if mode == 'create': msg = 'Successfully added policy %s to IAM role %s.' else: msg = 'Successfully modified policy %s for IAM role %s.' log.info(msg, policy_name, role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to %s policy %s for IAM role %s.', mode, policy_name, role_name) return False def delete_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) if not _policy: return True try: conn.delete_role_policy(role_name, policy_name) log.info('Successfully deleted policy %s for IAM role %s.', policy_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM role %s.', policy_name, role_name) return False def update_assume_role_policy(role_name, policy_document, region=None, key=None, keyid=None, profile=None): ''' Update an assume role policy for a role. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_assume_role_policy myrole '{"Statement":"..."}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(policy_document, six.string_types): policy_document = salt.utils.json.loads(policy_document, object_pairs_hook=odict.OrderedDict) try: _policy_document = salt.utils.json.dumps(policy_document) conn.update_assume_role_policy(role_name, _policy_document) log.info('Successfully updated assume role policy for IAM role %s.', role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to update assume role policy for IAM role %s.', role_name) return False def build_policy(region=None, key=None, keyid=None, profile=None): ''' Build a default assume role policy. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.build_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if hasattr(conn, 'build_policy'): policy = salt.utils.json.loads(conn.build_policy()) elif hasattr(conn, '_build_policy'): policy = salt.utils.json.loads(conn._build_policy()) else: return {} # The format we get from build_policy isn't going to be what we get back # from AWS for the exact same policy. AWS converts single item list values # into strings, so let's do the same here. for key, policy_val in policy.items(): for statement in policy_val: if (isinstance(statement['Action'], list) and len(statement['Action']) == 1): statement['Action'] = statement['Action'][0] if (isinstance(statement['Principal']['Service'], list) and len(statement['Principal']['Service']) == 1): statement['Principal']['Service'] = statement['Principal']['Service'][0] # build_policy doesn't add a version field, which AWS is going to set to a # default value, when we get it back, so let's set it. policy['Version'] = '2008-10-17' return policy def get_account_id(region=None, key=None, keyid=None, profile=None): ''' Get a the AWS account id associated with the used credentials. CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_id ''' cache_key = 'boto_iam.account_id' if cache_key not in __context__: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_user() # The get_user call returns an user ARN: # arn:aws:iam::027050522557:user/salt-test arn = ret['get_user_response']['get_user_result']['user']['arn'] account_id = arn.split(':')[4] except boto.exception.BotoServerError: # If call failed, then let's try to get the ARN from the metadata timeout = boto.config.getfloat( 'Boto', 'metadata_service_timeout', 1.0 ) attempts = boto.config.getint( 'Boto', 'metadata_service_num_attempts', 1 ) identity = boto.utils.get_instance_identity( timeout=timeout, num_retries=attempts ) try: account_id = identity['document']['accountId'] except KeyError: log.error('Failed to get account id from instance_identity in' ' boto_iam.get_account_id.') __context__[cache_key] = account_id return __context__[cache_key] def get_all_roles(path_prefix=None, region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM role details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_roles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _roles = conn.list_roles(path_prefix=path_prefix) roles = _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) while marker: _roles = conn.list_roles(path_prefix=path_prefix, marker=marker) roles = roles + _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) return roles def get_all_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM user details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_users ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _users = conn.get_all_users(path_prefix=path_prefix) users = _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) while marker: _users = conn.get_all_users(path_prefix=path_prefix, marker=marker) users = users + _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) return users def get_all_user_policies(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all user policies. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_user_policies myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_all_user_policies(user_name, marker, max_items) if not info: return False _list = info.list_user_policies_response.list_user_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policies for user %s.', user_name) return False def get_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user_policy myuser mypolicyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user_policy(user_name, policy_name) log.debug('Info for IAM user %s policy %s: %s.', user_name, policy_name, info) if not info: return False info = info.get_user_policy_response.get_user_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policy %s for IAM user %s.', policy_name, user_name) return False def put_user_policy(user_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_user_policy myuser policyname policyrules ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_user_policy(user_name, policy_name, policy_json) if created: log.info('Created policy %s for IAM user %s.', policy_name, user_name) return True log.error('Could not create policy %s for IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy %s for IAM user %s.', policy_name, user_name) return False def delete_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user_policy myuser mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_user_policy( user_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_user_policy(user_name, policy_name) log.info('Successfully deleted policy %s for IAM user %s.', policy_name, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM user %s.', policy_name, user_name) return False def upload_server_cert(cert_name, cert_body, private_key, cert_chain=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Upload a certificate to Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.upload_server_cert mycert_name crt priv_key :param cert_name: The name for the server certificate. Do not include the path in this value. :param cert_body: The contents of the public key certificate in PEM-encoded format. :param private_key: The contents of the private key in PEM-encoded format. :param cert_chain: The contents of the certificate chain. This is typically a concatenation of the PEM-encoded public key certificates of the chain. :param path: The path for the server certificate. :param region: The name of the region to connect to. :param key: The key to be used in order to connect :param keyid: The keyid to be used in order to connect :param profile: The profile that contains a dict of region, key, keyid :return: True / False ''' exists = get_server_certificate(cert_name, region, key, keyid, profile) if exists: return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.upload_server_cert(cert_name, cert_body, private_key, cert_chain) log.info('Created certificate %s.', cert_name) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to failed to create certificate %s.', cert_name) return False def list_server_certificates(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Lists the server certificates stored in IAM that have the specified path prefix. .. versionadded:: ??? :param path_prefix: The path prefix for filtering the results. For example: /company/servercerts would get all server certificates for which the path starts with /company/servercerts . This parameter is optional. If it is not included, it defaults to a slash (/), listing all server certificates. This parameter allows (per its regex pattern) a string of characters consisting of either a forward slash (/) by itself or a string that must begin and end with forward slashes. In addition, it can contain any ASCII character from the ! (u0021) through the DEL character (u007F), including most punctuation characters, digits, and upper and lowercased letters. CLI Example: .. code-block:: bash salt myminion boto_iam.list_server_certificates path_prefix=/somepath/ ''' retries = 10 sleep = 6 conn = __utils__['boto3.get_connection']('iam', region=region, key=key, keyid=keyid, profile=profile) Items = [] while retries: try: log.debug('Garnering list of IAM Server Certificates') IsTruncated = True while IsTruncated: kwargs = {'PathPrefix': path_prefix} ret = conn.list_server_certificates(**kwargs) Items += ret.get('ServerCertificateMetadataList', []) IsTruncated = ret.get('IsTruncated') kwargs.update({'Marker': ret.get('Marker')}) return Items except botocore.exceptions.ParamValidationError as err: raise SaltInvocationError(str(err)) except botocore.exceptions.ClientError as err: if retries and jmespath.search('Error.Code', err.response) == 'Throttling': retries -= 1 log.debug('Throttled by AWS API, retrying in %s seconds...', sleep) time.sleep(sleep) continue log.error('Failed to list IAM Server Certificates: %s', err.message) return None def get_server_certificate(cert_name, region=None, key=None, keyid=None, profile=None): ''' Returns certificate information from Amazon .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_server_certificate mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_server_certificate(cert_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get certificate %s information.', cert_name) return False def delete_server_cert(cert_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a certificate from Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_server_cert mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_server_cert(cert_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete certificate %s.', cert_name) return False def export_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM user details. Produces results that can be used to create an sls file. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.export_users --out=txt | sed "s/local: //" > iam_users.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() users = get_all_users(path_prefix, region, key, keyid, profile) for user in users: name = user.user_name _policies = conn.get_all_user_policies(name, max_items=100) _policies = _policies.list_user_policies_response.list_user_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_user_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_user_policy_response.get_user_policy_result.policy_document )) policies[policy_name] = _policy user_sls = [] user_sls.append({"name": name}) user_sls.append({"policies": policies}) user_sls.append({"path": user.path}) results["manage user " + name] = {"boto_iam.user_present": user_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def export_roles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM role details. Produces results that can be used to create an sls file. CLI Example: salt-call boto_iam.export_roles --out=txt | sed "s/local: //" > iam_roles.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() roles = get_all_roles(path_prefix, region, key, keyid, profile) for role in roles: name = role.role_name _policies = conn.list_role_policies(name, max_items=100) _policies = _policies.list_role_policies_response.list_role_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_role_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_role_policy_response.get_role_policy_result.policy_document )) policies[policy_name] = _policy role_sls = [] role_sls.append({"name": name}) role_sls.append({"policies": policies}) role_sls.append({'policy_document': salt.utils.json.loads(_unquote(role.assume_role_policy_document))}) role_sls.append({"path": role.path}) results["manage role " + name] = {"boto_iam_role.present": role_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def _get_policy_arn(name, region=None, key=None, keyid=None, profile=None): if name.startswith('arn:aws:iam:'): return name account_id = get_account_id( region=region, key=key, keyid=keyid, profile=profile ) return 'arn:aws:iam::{0}:policy/{1}'.format(account_id, name) def policy_exists(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return True except boto.exception.BotoServerError: return False def get_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return ret.get('get_policy_response', {}).get('get_policy_result', {}) except boto.exception.BotoServerError: return None def create_policy(policy_name, policy_document, path=None, description=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in 'path', 'description': if locals()[arg] is not None: params[arg] = locals()[arg] if policy_exists(policy_name, region, key, keyid, profile): return True try: conn.create_policy(policy_name, policy_document, **params) log.info('Created IAM policy %s.', policy_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s.', policy_name) return False return True def delete_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_exists(policy_arn, region, key, keyid, profile): return True try: conn.delete_policy(policy_arn) log.info('Deleted %s policy.', policy_name) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete %s policy: %s.', policy_name, aws.get('message')) return False return True def list_policies(region=None, key=None, keyid=None, profile=None): ''' List policies. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policies ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: policies = [] for ret in __utils__['boto.paged_call'](conn.list_policies): policies.append(ret.get('list_policies_response', {}).get('list_policies_result', {}).get('policies')) return policies except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to list policy versions.' log.error(msg) return [] def policy_version_exists(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.get_policy_version(policy_arn, version_id) return True except boto.exception.BotoServerError: return False def get_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy_version(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile), version_id) retval = ret.get('get_policy_version_response', {}).get('get_policy_version_result', {}).get('policy_version', {}) retval['document'] = _unquote(retval.get('document')) return {'policy_version': retval} except boto.exception.BotoServerError: return None def delete_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Delete a policy version. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_version_exists(policy_arn, version_id, region, key, keyid, profile): return True try: conn.delete_policy_version(policy_arn, version_id) log.info('Deleted IAM policy %s version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete IAM policy %s version %s: %s', policy_name, version_id, aws.get('message')) return False return True def list_policy_versions(policy_name, region=None, key=None, keyid=None, profile=None): ''' List versions of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policy_versions mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.list_policy_versions(policy_arn) return ret.get('list_policy_versions_response', {}).get('list_policy_versions_result', {}).get('versions') except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list versions for IAM policy %s.', policy_name) return [] def set_default_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Set the default version of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.set_default_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.set_default_policy_version(policy_arn, version_id) log.info('Set %s policy to version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to set %s policy to version %s: %s', policy_name, version_id, aws.get('message')) return False return True def attach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_user_policy(policy_arn, user_name) log.info('Attached policy %s to IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach %s policy to IAM user %s.', policy_name, user_name) return False return True def detach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_user_policy(policy_arn, user_name) log.info('Detached %s policy from IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach %s policy from IAM user %s.', policy_name, user_name) return False return True def attach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_group_policy(policy_arn, group_name) log.info('Attached policy %s to IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM group %s.', policy_name, group_name) return False return True def detach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_group_policy(policy_arn, group_name) log.info('Detached policy %s from IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM group %s.', policy_name, group_name) return False return True def attach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_role_policy(policy_arn, role_name) log.info('Attached policy %s to IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM role %s.', policy_name, role_name) return False return True def detach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_role_policy(policy_arn, role_name) log.info('Detached policy %s from IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM role %s.', policy_name, role_name) return False return True def list_entities_for_policy(policy_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities that a policy is attached to. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 params = {} for arg in ('path_prefix', 'entity_filter'): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) while retries: try: allret = { 'policy_groups': [], 'policy_users': [], 'policy_roles': [], } for ret in __utils__['boto.paged_call'](conn.list_entities_for_policy, policy_arn=policy_arn, **params): for k, v in six.iteritems(allret): v.extend(ret.get('list_entities_for_policy_response', {}).get('list_entities_for_policy_result', {}).get(k)) return allret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('Failed to list entities for IAM policy %s: %s', policy_name, e.message) return {} return {} def list_attached_user_policies(user_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given user. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'UserName': user_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedUserPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_user_policies_response', {}).get('list_attached_user_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM user %s.', user_name) return [] def list_attached_group_policies(group_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given group. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'GroupName': group_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedGroupPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_group_policies_response', {}).get('list_attached_group_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM group %s.', group_name) return [] def list_attached_role_policies(role_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'RoleName': role_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedRolePolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_role_policies_response', {}).get('list_attached_role_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM role %s.', role_name) return [] def create_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Create SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.create_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_saml_provider(saml_metadata_document, name) log.info('Successfully created %s SAML provider.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to create SAML provider %s.', name) return False def get_saml_provider_arn(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider_arn my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_saml_providers() for saml_provider in response.list_saml_providers_response.list_saml_providers_result.saml_provider_list: if saml_provider['arn'].endswith(':saml-provider/' + name): return saml_provider['arn'] return False except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to get ARN of SAML provider %s.', name) return False def delete_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Delete SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.delete_saml_provider my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return True conn.delete_saml_provider(saml_provider_arn) log.info('Successfully deleted SAML provider %s.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete SAML provider %s.', name) return False def list_saml_providers(region=None, key=None, keyid=None, profile=None): ''' List SAML providers. CLI Example: .. code-block:: bash salt myminion boto_iam.list_saml_providers ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: providers = [] info = conn.list_saml_providers() for arn in info['list_saml_providers_response']['list_saml_providers_result']['saml_provider_list']: providers.append(arn['arn'].rsplit('/', 1)[1]) return providers except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get list of SAML providers.') return False def get_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider document. CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider arn ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: provider = conn.get_saml_provider(name) return provider['get_saml_provider_response']['get_saml_provider_result']['saml_metadata_document'] except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get SAML provider document %s.', name) return False def update_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Update SAML provider. CLI Example: .. code-block:: bash salt myminion boto_iam.update_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return False if conn.update_saml_provider(name, saml_metadata_document): return True return False except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to update SAML provider %s.', name) return False
saltstack/salt
salt/modules/boto_iam.py
delete_policy_version
python
def delete_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Delete a policy version. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_version_exists(policy_arn, version_id, region, key, keyid, profile): return True try: conn.delete_policy_version(policy_arn, version_id) log.info('Deleted IAM policy %s version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete IAM policy %s version %s: %s', policy_name, version_id, aws.get('message')) return False return True
Delete a policy version. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy_version mypolicy v1
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iam.py#L1905-L1930
[ "def _get_policy_arn(name, region=None, key=None, keyid=None, profile=None):\n if name.startswith('arn:aws:iam:'):\n return name\n\n account_id = get_account_id(\n region=region, key=key, keyid=keyid, profile=profile\n )\n return 'arn:aws:iam::{0}:policy/{1}'.format(account_id, name)\n", "def policy_version_exists(policy_name, version_id,\n region=None, key=None, keyid=None, profile=None):\n '''\n Check to see if policy exists.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_iam.instance_profile_exists myiprofile\n '''\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n\n policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile)\n try:\n conn.get_policy_version(policy_arn, version_id)\n return True\n except boto.exception.BotoServerError:\n return False\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon IAM .. versionadded:: 2014.7.0 :configuration: This module accepts explicit iam 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 iam.keyid: GKTADJGHEIQSXMKKRBJ08H iam.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs iam.region: 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: boto ''' # keep lint from choking on _get_conn and _cache_id #pylint: disable=E0602 # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import salt libs from salt.ext import six import salt.utils.compat import salt.utils.json import salt.utils.odict as odict import salt.utils.versions from salt.exceptions import SaltInvocationError # Import third party libs # pylint: disable=unused-import from salt.ext.six.moves.urllib.parse import unquote as _unquote # pylint: disable=no-name-in-module try: import boto import boto.iam import boto3 import botocore logging.getLogger('boto').setLevel(logging.CRITICAL) logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=unused-import log = logging.getLogger(__name__) def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'iam', pack=__salt__) def instance_profile_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an instance profile exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: # Boto weirdly returns an exception here if an instance profile doesn't # exist. conn.get_instance_profile(name) return True except boto.exception.BotoServerError: return False def create_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Create an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.create_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if instance_profile_exists(name, region, key, keyid, profile): return True try: # This call returns an instance profile if successful and an exception # if not. It's annoying. conn.create_instance_profile(name) log.info('Created %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create %s instance profile.', name) return False return True def delete_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Delete an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not instance_profile_exists(name, region, key, keyid, profile): return True try: conn.delete_instance_profile(name) log.info('Deleted %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s instance profile.', name) return False return True def role_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an IAM role exists. CLI Example: .. code-block:: bash salt myminion boto_iam.role_exists myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_role(name) return True except boto.exception.BotoServerError: return False def describe_role(name, region=None, key=None, keyid=None, profile=None): ''' Get information for a role. CLI Example: .. code-block:: bash salt myminion boto_iam.describe_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_role(name) if not info: return False role = info.get_role_response.get_role_result.role role['assume_role_policy_document'] = salt.utils.json.loads(_unquote( role.assume_role_policy_document )) # If Sid wasn't defined by the user, boto will still return a Sid in # each policy. To properly check idempotently, let's remove the Sid # from the return if it's not actually set. for policy_key, policy in role['assume_role_policy_document'].items(): if policy_key == 'Statement': for val in policy: if 'Sid' in val and not val['Sid']: del val['Sid'] return role except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get %s information.', name) return False def create_user(user_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_user myuser ''' if not path: path = '/' if get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_user(user_name, path) log.info('Created IAM user : %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM user %s.', user_name) return False def get_all_access_keys(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all access keys from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_access_keys myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.get_all_access_keys(user_name, marker, max_items) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get access keys for IAM user %s.', user_name) return six.text_type(e) def create_access_key(user_name, region=None, key=None, keyid=None, profile=None): ''' Create access key id for a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.create_access_key(user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create access key.') return six.text_type(e) def delete_access_key(access_key_id, user_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete access key id from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_access_key(access_key_id, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete access key id %s.', access_key_id) return six.text_type(e) def delete_user(user_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user myuser ''' if not get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.delete_user(user_name) log.info('Deleted IAM user : %s .', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM user %s', user_name) return six.text_type(e) def get_user(user_name=None, region=None, key=None, keyid=None, profile=None): ''' Get user information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user(user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM user %s info.', user_name) return False def create_group(group_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_group group ''' if not path: path = '/' if get_group(group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_group(group_name, path) log.info('Created IAM group : %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM group %s.', group_name) return False def get_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group(group_name, max_items=1) if not info: return False return info['get_group_response']['get_group_result']['group'] except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_group_members(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: marker = None truncated = True users = [] while truncated: info = conn.get_group(group_name, marker=marker, max_items=1000) if not info: return False truncated = bool(info['get_group_response']['get_group_result']['is_truncated']) if truncated and 'marker' in info['get_group_response']['get_group_result']: marker = info['get_group_response']['get_group_result']['marker'] else: marker = None truncated = False users += info['get_group_response']['get_group_result']['users'] return users except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get members for IAM group %s.', group_name) return False def add_user_to_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Add user to group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.add_user_to_group myuser mygroup ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('Username : %s does not exist.', user_name) return False if user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.add_user_to_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add IAM user %s to group %s.', user_name, group_name) return False def user_exists_in_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Check if user exists in group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.user_exists_in_group myuser mygroup ''' # TODO this should probably use boto.iam.get_groups_for_user users = get_group_members( group_name=group_name, region=region, key=key, keyid=keyid, profile=profile ) if users: for _user in users: if user_name == _user['user_name']: log.debug('IAM user %s is already in IAM group %s.', user_name, group_name) return True return False def remove_user_from_group(group_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Remove user from group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.remove_user_from_group mygroup myuser ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist.', user_name) return False if not user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.remove_user_from_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove IAM user %s from group %s', user_name, group_name) return False def put_group_policy(group_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_group_policy mygroup policyname policyrules ''' group = get_group(group_name, region=region, key=key, keyid=keyid, profile=profile) if not group: log.error('Group %s does not exist', group_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_group_policy(group_name, policy_name, policy_json) if created: log.info('Created policy for IAM group %s.', group_name) return True log.error('Could not create policy for IAM group %s', group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy for IAM group %s', group_name) return False def delete_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group_policy mygroup mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_group_policy( group_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_group_policy(group_name, policy_name) log.info('Successfully deleted policy %s for IAM group %s.', policy_name, group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM group %s.', policy_name, group_name) return False def get_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group_policy mygroup policyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group_policy(group_name, policy_name) log.debug('info for group policy is : %s', info) if not info: return False info = info.get_group_policy_response.get_group_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_all_groups(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM group details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_groups ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _groups = conn.get_all_groups(path_prefix=path_prefix) groups = _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) while marker: _groups = conn.get_all_groups(path_prefix=path_prefix, marker=marker) groups = groups + _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) return groups def get_all_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.get_all_instance_profiles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) marker = False profiles = [] while marker is not None: marker = marker if marker else None p = conn.list_instance_profiles(path_prefix=path_prefix, marker=marker) res = p.list_instance_profiles_response.list_instance_profiles_result profiles += res.instance_profiles marker = getattr(res, 'marker', None) return profiles def list_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' List all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.list_instance_profiles ''' p = get_all_instance_profiles(path_prefix, region, key, keyid, profile) return [i['instance_profile_name'] for i in p] def get_all_group_policies(group_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a group. CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_group_policies mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False try: response = conn.get_all_group_policies(group_name) _list = response.list_group_policies_response.list_group_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def delete_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _group = get_group( group_name, region, key, keyid, profile ) if not _group: return True try: conn.delete_group(group_name) log.info('Successfully deleted IAM group %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM group %s.', group_name) return False def create_login_profile(user_name, password, region=None, key=None, keyid=None, profile=None): ''' Creates a login profile for the specified user, give the user the ability to access AWS services and the AWS Management Console. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_login_profile user_name password ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.create_login_profile(user_name, password) log.info('Created profile for IAM user %s.', user_name) return info except boto.exception.BotoServerError as e: log.debug(e) if 'Conflict' in e: log.info('Profile already exists for IAM user %s.', user_name) return 'Conflict' log.error('Failed to update profile for IAM user %s.', user_name) return False def delete_login_profile(user_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a login profile for the specified user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_login_profile user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.delete_login_profile(user_name) log.info('Deleted login profile for IAM user %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Login profile already deleted for IAM user %s.', user_name) return True log.error('Failed to delete login profile for IAM user %s.', user_name) return False def get_all_mfa_devices(user_name, region=None, key=None, keyid=None, profile=None): ''' Get all MFA devices associated with an IAM user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_mfa_devices user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: result = conn.get_all_mfa_devices(user_name) devices = result['list_mfa_devices_response']['list_mfa_devices_result']['mfa_devices'] return devices except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Could not find IAM user %s.', user_name) return [] log.error('Failed to get all MFA devices for IAM user %s.', user_name) return False def deactivate_mfa_device(user_name, serial, region=None, key=None, keyid=None, profile=None): ''' Deactivates the specified MFA device and removes it from association with the user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.deactivate_mfa_device user_name serial_num ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.deactivate_mfa_device(user_name, serial) log.info('Deactivated MFA device %s for IAM user %s.', serial, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('MFA device %s not associated with IAM user %s.', serial, user_name) return True log.error('Failed to deactivate MFA device %s for IAM user %s.', serial, user_name) return False def delete_virtual_mfa_device(serial, region=None, key=None, keyid=None, profile=None): ''' Deletes the specified virtual MFA device. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_virtual_mfa_device serial_num ''' conn = __utils__['boto3.get_connection_func']('iam')() try: conn.delete_virtual_mfa_device(SerialNumber=serial) log.info('Deleted virtual MFA device %s.', serial) return True except botocore.exceptions.ClientError as e: log.debug(e) if 'NoSuchEntity' in six.text_type(e): log.info('Virtual MFA device %s not found.', serial) return True log.error('Failed to delete virtual MFA device %s.', serial) return False def update_account_password_policy(allow_users_to_change_password=None, hard_expiry=None, max_password_age=None, minimum_password_length=None, password_reuse_prevention=None, require_lowercase_characters=None, require_numbers=None, require_symbols=None, require_uppercase_characters=None, region=None, key=None, keyid=None, profile=None): ''' Update the password policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_account_password_policy True ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.update_account_password_policy(allow_users_to_change_password, hard_expiry, max_password_age, minimum_password_length, password_reuse_prevention, require_lowercase_characters, require_numbers, require_symbols, require_uppercase_characters) log.info('The password policy has been updated.') return True except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy' log.error(msg) return False def get_account_policy(region=None, key=None, keyid=None, profile=None): ''' Get account policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_account_password_policy() return info.get_account_password_policy_response.get_account_password_policy_result.password_policy except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy.' log.error(msg) return False def create_role(name, policy_document=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Create an instance role. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if role_exists(name, region, key, keyid, profile): return True if not policy_document: policy_document = None try: conn.create_role(name, assume_role_policy_document=policy_document, path=path) log.info('Created IAM role %s.', name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to create IAM role %s.', name) return False def delete_role(name, region=None, key=None, keyid=None, profile=None): ''' Delete an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(name, region, key, keyid, profile): return True try: conn.delete_role(name) log.info('Deleted %s IAM role.', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s IAM role.', name) return False def profile_associated(role_name, profile_name, region, key, keyid, profile): ''' Check to see if an instance profile is associated with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.profile_associated myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # The IAM module of boto doesn't return objects. Instead you need to grab # values through its properties. Sigh. try: profiles = conn.list_instance_profiles_for_role(role_name) except boto.exception.BotoServerError as e: log.debug(e) return False profiles = profiles.list_instance_profiles_for_role_response profiles = profiles.list_instance_profiles_for_role_result profiles = profiles.instance_profiles for profile in profiles: if profile.instance_profile_name == profile_name: return True return False def associate_profile_to_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Associate an instance profile with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.associate_profile_to_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if associated: return True else: try: conn.add_role_to_instance_profile(profile_name, role_name) log.info('Added %s instance profile to IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add %s instance profile to IAM role %s', profile_name, role_name) return False def disassociate_profile_from_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Disassociate an instance profile from an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.disassociate_profile_from_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if not associated: return True else: try: conn.remove_role_from_instance_profile(profile_name, role_name) log.info('Removed %s instance profile from IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove %s instance profile from IAM role %s.', profile_name, role_name) return False def list_role_policies(role_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_role_policies myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_role_policies(role_name) _list = response.list_role_policies_response.list_role_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def get_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.get_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: _policy = conn.get_role_policy(role_name, policy_name) # I _hate_ you for not giving me an object boto. _policy = _policy.get_role_policy_response.policy_document # Policy is url encoded _policy = _unquote(_policy) _policy = salt.utils.json.loads(_policy, object_pairs_hook=odict.OrderedDict) return _policy except boto.exception.BotoServerError: return {} def create_role_policy(role_name, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Create or modify a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role_policy myirole mypolicy '{"MyPolicy": "Statement": [{"Action": ["sqs:*"], "Effect": "Allow", "Resource": ["arn:aws:sqs:*:*:*"], "Sid": "MyPolicySqs1"}]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) mode = 'create' if _policy: if _policy == policy: return True mode = 'modify' if isinstance(policy, six.string_types): policy = salt.utils.json.loads(policy, object_pairs_hook=odict.OrderedDict) try: _policy = salt.utils.json.dumps(policy) conn.put_role_policy(role_name, policy_name, _policy) if mode == 'create': msg = 'Successfully added policy %s to IAM role %s.' else: msg = 'Successfully modified policy %s for IAM role %s.' log.info(msg, policy_name, role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to %s policy %s for IAM role %s.', mode, policy_name, role_name) return False def delete_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) if not _policy: return True try: conn.delete_role_policy(role_name, policy_name) log.info('Successfully deleted policy %s for IAM role %s.', policy_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM role %s.', policy_name, role_name) return False def update_assume_role_policy(role_name, policy_document, region=None, key=None, keyid=None, profile=None): ''' Update an assume role policy for a role. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_assume_role_policy myrole '{"Statement":"..."}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(policy_document, six.string_types): policy_document = salt.utils.json.loads(policy_document, object_pairs_hook=odict.OrderedDict) try: _policy_document = salt.utils.json.dumps(policy_document) conn.update_assume_role_policy(role_name, _policy_document) log.info('Successfully updated assume role policy for IAM role %s.', role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to update assume role policy for IAM role %s.', role_name) return False def build_policy(region=None, key=None, keyid=None, profile=None): ''' Build a default assume role policy. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.build_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if hasattr(conn, 'build_policy'): policy = salt.utils.json.loads(conn.build_policy()) elif hasattr(conn, '_build_policy'): policy = salt.utils.json.loads(conn._build_policy()) else: return {} # The format we get from build_policy isn't going to be what we get back # from AWS for the exact same policy. AWS converts single item list values # into strings, so let's do the same here. for key, policy_val in policy.items(): for statement in policy_val: if (isinstance(statement['Action'], list) and len(statement['Action']) == 1): statement['Action'] = statement['Action'][0] if (isinstance(statement['Principal']['Service'], list) and len(statement['Principal']['Service']) == 1): statement['Principal']['Service'] = statement['Principal']['Service'][0] # build_policy doesn't add a version field, which AWS is going to set to a # default value, when we get it back, so let's set it. policy['Version'] = '2008-10-17' return policy def get_account_id(region=None, key=None, keyid=None, profile=None): ''' Get a the AWS account id associated with the used credentials. CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_id ''' cache_key = 'boto_iam.account_id' if cache_key not in __context__: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_user() # The get_user call returns an user ARN: # arn:aws:iam::027050522557:user/salt-test arn = ret['get_user_response']['get_user_result']['user']['arn'] account_id = arn.split(':')[4] except boto.exception.BotoServerError: # If call failed, then let's try to get the ARN from the metadata timeout = boto.config.getfloat( 'Boto', 'metadata_service_timeout', 1.0 ) attempts = boto.config.getint( 'Boto', 'metadata_service_num_attempts', 1 ) identity = boto.utils.get_instance_identity( timeout=timeout, num_retries=attempts ) try: account_id = identity['document']['accountId'] except KeyError: log.error('Failed to get account id from instance_identity in' ' boto_iam.get_account_id.') __context__[cache_key] = account_id return __context__[cache_key] def get_all_roles(path_prefix=None, region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM role details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_roles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _roles = conn.list_roles(path_prefix=path_prefix) roles = _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) while marker: _roles = conn.list_roles(path_prefix=path_prefix, marker=marker) roles = roles + _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) return roles def get_all_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM user details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_users ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _users = conn.get_all_users(path_prefix=path_prefix) users = _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) while marker: _users = conn.get_all_users(path_prefix=path_prefix, marker=marker) users = users + _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) return users def get_all_user_policies(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all user policies. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_user_policies myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_all_user_policies(user_name, marker, max_items) if not info: return False _list = info.list_user_policies_response.list_user_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policies for user %s.', user_name) return False def get_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user_policy myuser mypolicyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user_policy(user_name, policy_name) log.debug('Info for IAM user %s policy %s: %s.', user_name, policy_name, info) if not info: return False info = info.get_user_policy_response.get_user_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policy %s for IAM user %s.', policy_name, user_name) return False def put_user_policy(user_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_user_policy myuser policyname policyrules ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_user_policy(user_name, policy_name, policy_json) if created: log.info('Created policy %s for IAM user %s.', policy_name, user_name) return True log.error('Could not create policy %s for IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy %s for IAM user %s.', policy_name, user_name) return False def delete_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user_policy myuser mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_user_policy( user_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_user_policy(user_name, policy_name) log.info('Successfully deleted policy %s for IAM user %s.', policy_name, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM user %s.', policy_name, user_name) return False def upload_server_cert(cert_name, cert_body, private_key, cert_chain=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Upload a certificate to Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.upload_server_cert mycert_name crt priv_key :param cert_name: The name for the server certificate. Do not include the path in this value. :param cert_body: The contents of the public key certificate in PEM-encoded format. :param private_key: The contents of the private key in PEM-encoded format. :param cert_chain: The contents of the certificate chain. This is typically a concatenation of the PEM-encoded public key certificates of the chain. :param path: The path for the server certificate. :param region: The name of the region to connect to. :param key: The key to be used in order to connect :param keyid: The keyid to be used in order to connect :param profile: The profile that contains a dict of region, key, keyid :return: True / False ''' exists = get_server_certificate(cert_name, region, key, keyid, profile) if exists: return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.upload_server_cert(cert_name, cert_body, private_key, cert_chain) log.info('Created certificate %s.', cert_name) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to failed to create certificate %s.', cert_name) return False def list_server_certificates(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Lists the server certificates stored in IAM that have the specified path prefix. .. versionadded:: ??? :param path_prefix: The path prefix for filtering the results. For example: /company/servercerts would get all server certificates for which the path starts with /company/servercerts . This parameter is optional. If it is not included, it defaults to a slash (/), listing all server certificates. This parameter allows (per its regex pattern) a string of characters consisting of either a forward slash (/) by itself or a string that must begin and end with forward slashes. In addition, it can contain any ASCII character from the ! (u0021) through the DEL character (u007F), including most punctuation characters, digits, and upper and lowercased letters. CLI Example: .. code-block:: bash salt myminion boto_iam.list_server_certificates path_prefix=/somepath/ ''' retries = 10 sleep = 6 conn = __utils__['boto3.get_connection']('iam', region=region, key=key, keyid=keyid, profile=profile) Items = [] while retries: try: log.debug('Garnering list of IAM Server Certificates') IsTruncated = True while IsTruncated: kwargs = {'PathPrefix': path_prefix} ret = conn.list_server_certificates(**kwargs) Items += ret.get('ServerCertificateMetadataList', []) IsTruncated = ret.get('IsTruncated') kwargs.update({'Marker': ret.get('Marker')}) return Items except botocore.exceptions.ParamValidationError as err: raise SaltInvocationError(str(err)) except botocore.exceptions.ClientError as err: if retries and jmespath.search('Error.Code', err.response) == 'Throttling': retries -= 1 log.debug('Throttled by AWS API, retrying in %s seconds...', sleep) time.sleep(sleep) continue log.error('Failed to list IAM Server Certificates: %s', err.message) return None def get_server_certificate(cert_name, region=None, key=None, keyid=None, profile=None): ''' Returns certificate information from Amazon .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_server_certificate mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_server_certificate(cert_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get certificate %s information.', cert_name) return False def delete_server_cert(cert_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a certificate from Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_server_cert mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_server_cert(cert_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete certificate %s.', cert_name) return False def export_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM user details. Produces results that can be used to create an sls file. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.export_users --out=txt | sed "s/local: //" > iam_users.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() users = get_all_users(path_prefix, region, key, keyid, profile) for user in users: name = user.user_name _policies = conn.get_all_user_policies(name, max_items=100) _policies = _policies.list_user_policies_response.list_user_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_user_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_user_policy_response.get_user_policy_result.policy_document )) policies[policy_name] = _policy user_sls = [] user_sls.append({"name": name}) user_sls.append({"policies": policies}) user_sls.append({"path": user.path}) results["manage user " + name] = {"boto_iam.user_present": user_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def export_roles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM role details. Produces results that can be used to create an sls file. CLI Example: salt-call boto_iam.export_roles --out=txt | sed "s/local: //" > iam_roles.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() roles = get_all_roles(path_prefix, region, key, keyid, profile) for role in roles: name = role.role_name _policies = conn.list_role_policies(name, max_items=100) _policies = _policies.list_role_policies_response.list_role_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_role_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_role_policy_response.get_role_policy_result.policy_document )) policies[policy_name] = _policy role_sls = [] role_sls.append({"name": name}) role_sls.append({"policies": policies}) role_sls.append({'policy_document': salt.utils.json.loads(_unquote(role.assume_role_policy_document))}) role_sls.append({"path": role.path}) results["manage role " + name] = {"boto_iam_role.present": role_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def _get_policy_arn(name, region=None, key=None, keyid=None, profile=None): if name.startswith('arn:aws:iam:'): return name account_id = get_account_id( region=region, key=key, keyid=keyid, profile=profile ) return 'arn:aws:iam::{0}:policy/{1}'.format(account_id, name) def policy_exists(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return True except boto.exception.BotoServerError: return False def get_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return ret.get('get_policy_response', {}).get('get_policy_result', {}) except boto.exception.BotoServerError: return None def create_policy(policy_name, policy_document, path=None, description=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in 'path', 'description': if locals()[arg] is not None: params[arg] = locals()[arg] if policy_exists(policy_name, region, key, keyid, profile): return True try: conn.create_policy(policy_name, policy_document, **params) log.info('Created IAM policy %s.', policy_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s.', policy_name) return False return True def delete_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_exists(policy_arn, region, key, keyid, profile): return True try: conn.delete_policy(policy_arn) log.info('Deleted %s policy.', policy_name) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete %s policy: %s.', policy_name, aws.get('message')) return False return True def list_policies(region=None, key=None, keyid=None, profile=None): ''' List policies. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policies ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: policies = [] for ret in __utils__['boto.paged_call'](conn.list_policies): policies.append(ret.get('list_policies_response', {}).get('list_policies_result', {}).get('policies')) return policies except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to list policy versions.' log.error(msg) return [] def policy_version_exists(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.get_policy_version(policy_arn, version_id) return True except boto.exception.BotoServerError: return False def get_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy_version(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile), version_id) retval = ret.get('get_policy_version_response', {}).get('get_policy_version_result', {}).get('policy_version', {}) retval['document'] = _unquote(retval.get('document')) return {'policy_version': retval} except boto.exception.BotoServerError: return None def create_policy_version(policy_name, policy_document, set_as_default=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy version. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy_version mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in ('set_as_default',): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.create_policy_version(policy_arn, policy_document, **params) vid = ret.get('create_policy_version_response', {}).get('create_policy_version_result', {}).get('policy_version', {}).get('version_id') log.info('Created IAM policy %s version %s.', policy_name, vid) return {'created': True, 'version_id': vid} except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s version %s.', policy_name, vid) return {'created': False, 'error': __utils__['boto.get_error'](e)} def list_policy_versions(policy_name, region=None, key=None, keyid=None, profile=None): ''' List versions of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policy_versions mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.list_policy_versions(policy_arn) return ret.get('list_policy_versions_response', {}).get('list_policy_versions_result', {}).get('versions') except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list versions for IAM policy %s.', policy_name) return [] def set_default_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Set the default version of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.set_default_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.set_default_policy_version(policy_arn, version_id) log.info('Set %s policy to version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to set %s policy to version %s: %s', policy_name, version_id, aws.get('message')) return False return True def attach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_user_policy(policy_arn, user_name) log.info('Attached policy %s to IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach %s policy to IAM user %s.', policy_name, user_name) return False return True def detach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_user_policy(policy_arn, user_name) log.info('Detached %s policy from IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach %s policy from IAM user %s.', policy_name, user_name) return False return True def attach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_group_policy(policy_arn, group_name) log.info('Attached policy %s to IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM group %s.', policy_name, group_name) return False return True def detach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_group_policy(policy_arn, group_name) log.info('Detached policy %s from IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM group %s.', policy_name, group_name) return False return True def attach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_role_policy(policy_arn, role_name) log.info('Attached policy %s to IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM role %s.', policy_name, role_name) return False return True def detach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_role_policy(policy_arn, role_name) log.info('Detached policy %s from IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM role %s.', policy_name, role_name) return False return True def list_entities_for_policy(policy_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities that a policy is attached to. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 params = {} for arg in ('path_prefix', 'entity_filter'): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) while retries: try: allret = { 'policy_groups': [], 'policy_users': [], 'policy_roles': [], } for ret in __utils__['boto.paged_call'](conn.list_entities_for_policy, policy_arn=policy_arn, **params): for k, v in six.iteritems(allret): v.extend(ret.get('list_entities_for_policy_response', {}).get('list_entities_for_policy_result', {}).get(k)) return allret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('Failed to list entities for IAM policy %s: %s', policy_name, e.message) return {} return {} def list_attached_user_policies(user_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given user. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'UserName': user_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedUserPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_user_policies_response', {}).get('list_attached_user_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM user %s.', user_name) return [] def list_attached_group_policies(group_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given group. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'GroupName': group_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedGroupPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_group_policies_response', {}).get('list_attached_group_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM group %s.', group_name) return [] def list_attached_role_policies(role_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'RoleName': role_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedRolePolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_role_policies_response', {}).get('list_attached_role_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM role %s.', role_name) return [] def create_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Create SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.create_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_saml_provider(saml_metadata_document, name) log.info('Successfully created %s SAML provider.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to create SAML provider %s.', name) return False def get_saml_provider_arn(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider_arn my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_saml_providers() for saml_provider in response.list_saml_providers_response.list_saml_providers_result.saml_provider_list: if saml_provider['arn'].endswith(':saml-provider/' + name): return saml_provider['arn'] return False except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to get ARN of SAML provider %s.', name) return False def delete_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Delete SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.delete_saml_provider my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return True conn.delete_saml_provider(saml_provider_arn) log.info('Successfully deleted SAML provider %s.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete SAML provider %s.', name) return False def list_saml_providers(region=None, key=None, keyid=None, profile=None): ''' List SAML providers. CLI Example: .. code-block:: bash salt myminion boto_iam.list_saml_providers ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: providers = [] info = conn.list_saml_providers() for arn in info['list_saml_providers_response']['list_saml_providers_result']['saml_provider_list']: providers.append(arn['arn'].rsplit('/', 1)[1]) return providers except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get list of SAML providers.') return False def get_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider document. CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider arn ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: provider = conn.get_saml_provider(name) return provider['get_saml_provider_response']['get_saml_provider_result']['saml_metadata_document'] except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get SAML provider document %s.', name) return False def update_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Update SAML provider. CLI Example: .. code-block:: bash salt myminion boto_iam.update_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return False if conn.update_saml_provider(name, saml_metadata_document): return True return False except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to update SAML provider %s.', name) return False
saltstack/salt
salt/modules/boto_iam.py
list_policy_versions
python
def list_policy_versions(policy_name, region=None, key=None, keyid=None, profile=None): ''' List versions of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policy_versions mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.list_policy_versions(policy_arn) return ret.get('list_policy_versions_response', {}).get('list_policy_versions_result', {}).get('versions') except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list versions for IAM policy %s.', policy_name) return []
List versions of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policy_versions mypolicy
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iam.py#L1933-L1953
[ "def _get_policy_arn(name, region=None, key=None, keyid=None, profile=None):\n if name.startswith('arn:aws:iam:'):\n return name\n\n account_id = get_account_id(\n region=region, key=key, keyid=keyid, profile=profile\n )\n return 'arn:aws:iam::{0}:policy/{1}'.format(account_id, name)\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon IAM .. versionadded:: 2014.7.0 :configuration: This module accepts explicit iam 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 iam.keyid: GKTADJGHEIQSXMKKRBJ08H iam.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs iam.region: 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: boto ''' # keep lint from choking on _get_conn and _cache_id #pylint: disable=E0602 # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import salt libs from salt.ext import six import salt.utils.compat import salt.utils.json import salt.utils.odict as odict import salt.utils.versions from salt.exceptions import SaltInvocationError # Import third party libs # pylint: disable=unused-import from salt.ext.six.moves.urllib.parse import unquote as _unquote # pylint: disable=no-name-in-module try: import boto import boto.iam import boto3 import botocore logging.getLogger('boto').setLevel(logging.CRITICAL) logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=unused-import log = logging.getLogger(__name__) def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'iam', pack=__salt__) def instance_profile_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an instance profile exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: # Boto weirdly returns an exception here if an instance profile doesn't # exist. conn.get_instance_profile(name) return True except boto.exception.BotoServerError: return False def create_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Create an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.create_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if instance_profile_exists(name, region, key, keyid, profile): return True try: # This call returns an instance profile if successful and an exception # if not. It's annoying. conn.create_instance_profile(name) log.info('Created %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create %s instance profile.', name) return False return True def delete_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Delete an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not instance_profile_exists(name, region, key, keyid, profile): return True try: conn.delete_instance_profile(name) log.info('Deleted %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s instance profile.', name) return False return True def role_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an IAM role exists. CLI Example: .. code-block:: bash salt myminion boto_iam.role_exists myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_role(name) return True except boto.exception.BotoServerError: return False def describe_role(name, region=None, key=None, keyid=None, profile=None): ''' Get information for a role. CLI Example: .. code-block:: bash salt myminion boto_iam.describe_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_role(name) if not info: return False role = info.get_role_response.get_role_result.role role['assume_role_policy_document'] = salt.utils.json.loads(_unquote( role.assume_role_policy_document )) # If Sid wasn't defined by the user, boto will still return a Sid in # each policy. To properly check idempotently, let's remove the Sid # from the return if it's not actually set. for policy_key, policy in role['assume_role_policy_document'].items(): if policy_key == 'Statement': for val in policy: if 'Sid' in val and not val['Sid']: del val['Sid'] return role except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get %s information.', name) return False def create_user(user_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_user myuser ''' if not path: path = '/' if get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_user(user_name, path) log.info('Created IAM user : %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM user %s.', user_name) return False def get_all_access_keys(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all access keys from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_access_keys myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.get_all_access_keys(user_name, marker, max_items) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get access keys for IAM user %s.', user_name) return six.text_type(e) def create_access_key(user_name, region=None, key=None, keyid=None, profile=None): ''' Create access key id for a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.create_access_key(user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create access key.') return six.text_type(e) def delete_access_key(access_key_id, user_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete access key id from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_access_key(access_key_id, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete access key id %s.', access_key_id) return six.text_type(e) def delete_user(user_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user myuser ''' if not get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.delete_user(user_name) log.info('Deleted IAM user : %s .', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM user %s', user_name) return six.text_type(e) def get_user(user_name=None, region=None, key=None, keyid=None, profile=None): ''' Get user information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user(user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM user %s info.', user_name) return False def create_group(group_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_group group ''' if not path: path = '/' if get_group(group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_group(group_name, path) log.info('Created IAM group : %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM group %s.', group_name) return False def get_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group(group_name, max_items=1) if not info: return False return info['get_group_response']['get_group_result']['group'] except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_group_members(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: marker = None truncated = True users = [] while truncated: info = conn.get_group(group_name, marker=marker, max_items=1000) if not info: return False truncated = bool(info['get_group_response']['get_group_result']['is_truncated']) if truncated and 'marker' in info['get_group_response']['get_group_result']: marker = info['get_group_response']['get_group_result']['marker'] else: marker = None truncated = False users += info['get_group_response']['get_group_result']['users'] return users except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get members for IAM group %s.', group_name) return False def add_user_to_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Add user to group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.add_user_to_group myuser mygroup ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('Username : %s does not exist.', user_name) return False if user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.add_user_to_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add IAM user %s to group %s.', user_name, group_name) return False def user_exists_in_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Check if user exists in group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.user_exists_in_group myuser mygroup ''' # TODO this should probably use boto.iam.get_groups_for_user users = get_group_members( group_name=group_name, region=region, key=key, keyid=keyid, profile=profile ) if users: for _user in users: if user_name == _user['user_name']: log.debug('IAM user %s is already in IAM group %s.', user_name, group_name) return True return False def remove_user_from_group(group_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Remove user from group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.remove_user_from_group mygroup myuser ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist.', user_name) return False if not user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.remove_user_from_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove IAM user %s from group %s', user_name, group_name) return False def put_group_policy(group_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_group_policy mygroup policyname policyrules ''' group = get_group(group_name, region=region, key=key, keyid=keyid, profile=profile) if not group: log.error('Group %s does not exist', group_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_group_policy(group_name, policy_name, policy_json) if created: log.info('Created policy for IAM group %s.', group_name) return True log.error('Could not create policy for IAM group %s', group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy for IAM group %s', group_name) return False def delete_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group_policy mygroup mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_group_policy( group_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_group_policy(group_name, policy_name) log.info('Successfully deleted policy %s for IAM group %s.', policy_name, group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM group %s.', policy_name, group_name) return False def get_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group_policy mygroup policyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group_policy(group_name, policy_name) log.debug('info for group policy is : %s', info) if not info: return False info = info.get_group_policy_response.get_group_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_all_groups(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM group details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_groups ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _groups = conn.get_all_groups(path_prefix=path_prefix) groups = _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) while marker: _groups = conn.get_all_groups(path_prefix=path_prefix, marker=marker) groups = groups + _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) return groups def get_all_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.get_all_instance_profiles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) marker = False profiles = [] while marker is not None: marker = marker if marker else None p = conn.list_instance_profiles(path_prefix=path_prefix, marker=marker) res = p.list_instance_profiles_response.list_instance_profiles_result profiles += res.instance_profiles marker = getattr(res, 'marker', None) return profiles def list_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' List all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.list_instance_profiles ''' p = get_all_instance_profiles(path_prefix, region, key, keyid, profile) return [i['instance_profile_name'] for i in p] def get_all_group_policies(group_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a group. CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_group_policies mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False try: response = conn.get_all_group_policies(group_name) _list = response.list_group_policies_response.list_group_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def delete_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _group = get_group( group_name, region, key, keyid, profile ) if not _group: return True try: conn.delete_group(group_name) log.info('Successfully deleted IAM group %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM group %s.', group_name) return False def create_login_profile(user_name, password, region=None, key=None, keyid=None, profile=None): ''' Creates a login profile for the specified user, give the user the ability to access AWS services and the AWS Management Console. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_login_profile user_name password ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.create_login_profile(user_name, password) log.info('Created profile for IAM user %s.', user_name) return info except boto.exception.BotoServerError as e: log.debug(e) if 'Conflict' in e: log.info('Profile already exists for IAM user %s.', user_name) return 'Conflict' log.error('Failed to update profile for IAM user %s.', user_name) return False def delete_login_profile(user_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a login profile for the specified user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_login_profile user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.delete_login_profile(user_name) log.info('Deleted login profile for IAM user %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Login profile already deleted for IAM user %s.', user_name) return True log.error('Failed to delete login profile for IAM user %s.', user_name) return False def get_all_mfa_devices(user_name, region=None, key=None, keyid=None, profile=None): ''' Get all MFA devices associated with an IAM user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_mfa_devices user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: result = conn.get_all_mfa_devices(user_name) devices = result['list_mfa_devices_response']['list_mfa_devices_result']['mfa_devices'] return devices except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Could not find IAM user %s.', user_name) return [] log.error('Failed to get all MFA devices for IAM user %s.', user_name) return False def deactivate_mfa_device(user_name, serial, region=None, key=None, keyid=None, profile=None): ''' Deactivates the specified MFA device and removes it from association with the user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.deactivate_mfa_device user_name serial_num ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.deactivate_mfa_device(user_name, serial) log.info('Deactivated MFA device %s for IAM user %s.', serial, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('MFA device %s not associated with IAM user %s.', serial, user_name) return True log.error('Failed to deactivate MFA device %s for IAM user %s.', serial, user_name) return False def delete_virtual_mfa_device(serial, region=None, key=None, keyid=None, profile=None): ''' Deletes the specified virtual MFA device. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_virtual_mfa_device serial_num ''' conn = __utils__['boto3.get_connection_func']('iam')() try: conn.delete_virtual_mfa_device(SerialNumber=serial) log.info('Deleted virtual MFA device %s.', serial) return True except botocore.exceptions.ClientError as e: log.debug(e) if 'NoSuchEntity' in six.text_type(e): log.info('Virtual MFA device %s not found.', serial) return True log.error('Failed to delete virtual MFA device %s.', serial) return False def update_account_password_policy(allow_users_to_change_password=None, hard_expiry=None, max_password_age=None, minimum_password_length=None, password_reuse_prevention=None, require_lowercase_characters=None, require_numbers=None, require_symbols=None, require_uppercase_characters=None, region=None, key=None, keyid=None, profile=None): ''' Update the password policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_account_password_policy True ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.update_account_password_policy(allow_users_to_change_password, hard_expiry, max_password_age, minimum_password_length, password_reuse_prevention, require_lowercase_characters, require_numbers, require_symbols, require_uppercase_characters) log.info('The password policy has been updated.') return True except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy' log.error(msg) return False def get_account_policy(region=None, key=None, keyid=None, profile=None): ''' Get account policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_account_password_policy() return info.get_account_password_policy_response.get_account_password_policy_result.password_policy except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy.' log.error(msg) return False def create_role(name, policy_document=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Create an instance role. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if role_exists(name, region, key, keyid, profile): return True if not policy_document: policy_document = None try: conn.create_role(name, assume_role_policy_document=policy_document, path=path) log.info('Created IAM role %s.', name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to create IAM role %s.', name) return False def delete_role(name, region=None, key=None, keyid=None, profile=None): ''' Delete an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(name, region, key, keyid, profile): return True try: conn.delete_role(name) log.info('Deleted %s IAM role.', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s IAM role.', name) return False def profile_associated(role_name, profile_name, region, key, keyid, profile): ''' Check to see if an instance profile is associated with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.profile_associated myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # The IAM module of boto doesn't return objects. Instead you need to grab # values through its properties. Sigh. try: profiles = conn.list_instance_profiles_for_role(role_name) except boto.exception.BotoServerError as e: log.debug(e) return False profiles = profiles.list_instance_profiles_for_role_response profiles = profiles.list_instance_profiles_for_role_result profiles = profiles.instance_profiles for profile in profiles: if profile.instance_profile_name == profile_name: return True return False def associate_profile_to_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Associate an instance profile with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.associate_profile_to_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if associated: return True else: try: conn.add_role_to_instance_profile(profile_name, role_name) log.info('Added %s instance profile to IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add %s instance profile to IAM role %s', profile_name, role_name) return False def disassociate_profile_from_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Disassociate an instance profile from an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.disassociate_profile_from_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if not associated: return True else: try: conn.remove_role_from_instance_profile(profile_name, role_name) log.info('Removed %s instance profile from IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove %s instance profile from IAM role %s.', profile_name, role_name) return False def list_role_policies(role_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_role_policies myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_role_policies(role_name) _list = response.list_role_policies_response.list_role_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def get_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.get_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: _policy = conn.get_role_policy(role_name, policy_name) # I _hate_ you for not giving me an object boto. _policy = _policy.get_role_policy_response.policy_document # Policy is url encoded _policy = _unquote(_policy) _policy = salt.utils.json.loads(_policy, object_pairs_hook=odict.OrderedDict) return _policy except boto.exception.BotoServerError: return {} def create_role_policy(role_name, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Create or modify a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role_policy myirole mypolicy '{"MyPolicy": "Statement": [{"Action": ["sqs:*"], "Effect": "Allow", "Resource": ["arn:aws:sqs:*:*:*"], "Sid": "MyPolicySqs1"}]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) mode = 'create' if _policy: if _policy == policy: return True mode = 'modify' if isinstance(policy, six.string_types): policy = salt.utils.json.loads(policy, object_pairs_hook=odict.OrderedDict) try: _policy = salt.utils.json.dumps(policy) conn.put_role_policy(role_name, policy_name, _policy) if mode == 'create': msg = 'Successfully added policy %s to IAM role %s.' else: msg = 'Successfully modified policy %s for IAM role %s.' log.info(msg, policy_name, role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to %s policy %s for IAM role %s.', mode, policy_name, role_name) return False def delete_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) if not _policy: return True try: conn.delete_role_policy(role_name, policy_name) log.info('Successfully deleted policy %s for IAM role %s.', policy_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM role %s.', policy_name, role_name) return False def update_assume_role_policy(role_name, policy_document, region=None, key=None, keyid=None, profile=None): ''' Update an assume role policy for a role. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_assume_role_policy myrole '{"Statement":"..."}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(policy_document, six.string_types): policy_document = salt.utils.json.loads(policy_document, object_pairs_hook=odict.OrderedDict) try: _policy_document = salt.utils.json.dumps(policy_document) conn.update_assume_role_policy(role_name, _policy_document) log.info('Successfully updated assume role policy for IAM role %s.', role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to update assume role policy for IAM role %s.', role_name) return False def build_policy(region=None, key=None, keyid=None, profile=None): ''' Build a default assume role policy. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.build_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if hasattr(conn, 'build_policy'): policy = salt.utils.json.loads(conn.build_policy()) elif hasattr(conn, '_build_policy'): policy = salt.utils.json.loads(conn._build_policy()) else: return {} # The format we get from build_policy isn't going to be what we get back # from AWS for the exact same policy. AWS converts single item list values # into strings, so let's do the same here. for key, policy_val in policy.items(): for statement in policy_val: if (isinstance(statement['Action'], list) and len(statement['Action']) == 1): statement['Action'] = statement['Action'][0] if (isinstance(statement['Principal']['Service'], list) and len(statement['Principal']['Service']) == 1): statement['Principal']['Service'] = statement['Principal']['Service'][0] # build_policy doesn't add a version field, which AWS is going to set to a # default value, when we get it back, so let's set it. policy['Version'] = '2008-10-17' return policy def get_account_id(region=None, key=None, keyid=None, profile=None): ''' Get a the AWS account id associated with the used credentials. CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_id ''' cache_key = 'boto_iam.account_id' if cache_key not in __context__: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_user() # The get_user call returns an user ARN: # arn:aws:iam::027050522557:user/salt-test arn = ret['get_user_response']['get_user_result']['user']['arn'] account_id = arn.split(':')[4] except boto.exception.BotoServerError: # If call failed, then let's try to get the ARN from the metadata timeout = boto.config.getfloat( 'Boto', 'metadata_service_timeout', 1.0 ) attempts = boto.config.getint( 'Boto', 'metadata_service_num_attempts', 1 ) identity = boto.utils.get_instance_identity( timeout=timeout, num_retries=attempts ) try: account_id = identity['document']['accountId'] except KeyError: log.error('Failed to get account id from instance_identity in' ' boto_iam.get_account_id.') __context__[cache_key] = account_id return __context__[cache_key] def get_all_roles(path_prefix=None, region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM role details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_roles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _roles = conn.list_roles(path_prefix=path_prefix) roles = _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) while marker: _roles = conn.list_roles(path_prefix=path_prefix, marker=marker) roles = roles + _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) return roles def get_all_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM user details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_users ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _users = conn.get_all_users(path_prefix=path_prefix) users = _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) while marker: _users = conn.get_all_users(path_prefix=path_prefix, marker=marker) users = users + _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) return users def get_all_user_policies(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all user policies. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_user_policies myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_all_user_policies(user_name, marker, max_items) if not info: return False _list = info.list_user_policies_response.list_user_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policies for user %s.', user_name) return False def get_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user_policy myuser mypolicyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user_policy(user_name, policy_name) log.debug('Info for IAM user %s policy %s: %s.', user_name, policy_name, info) if not info: return False info = info.get_user_policy_response.get_user_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policy %s for IAM user %s.', policy_name, user_name) return False def put_user_policy(user_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_user_policy myuser policyname policyrules ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_user_policy(user_name, policy_name, policy_json) if created: log.info('Created policy %s for IAM user %s.', policy_name, user_name) return True log.error('Could not create policy %s for IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy %s for IAM user %s.', policy_name, user_name) return False def delete_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user_policy myuser mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_user_policy( user_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_user_policy(user_name, policy_name) log.info('Successfully deleted policy %s for IAM user %s.', policy_name, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM user %s.', policy_name, user_name) return False def upload_server_cert(cert_name, cert_body, private_key, cert_chain=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Upload a certificate to Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.upload_server_cert mycert_name crt priv_key :param cert_name: The name for the server certificate. Do not include the path in this value. :param cert_body: The contents of the public key certificate in PEM-encoded format. :param private_key: The contents of the private key in PEM-encoded format. :param cert_chain: The contents of the certificate chain. This is typically a concatenation of the PEM-encoded public key certificates of the chain. :param path: The path for the server certificate. :param region: The name of the region to connect to. :param key: The key to be used in order to connect :param keyid: The keyid to be used in order to connect :param profile: The profile that contains a dict of region, key, keyid :return: True / False ''' exists = get_server_certificate(cert_name, region, key, keyid, profile) if exists: return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.upload_server_cert(cert_name, cert_body, private_key, cert_chain) log.info('Created certificate %s.', cert_name) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to failed to create certificate %s.', cert_name) return False def list_server_certificates(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Lists the server certificates stored in IAM that have the specified path prefix. .. versionadded:: ??? :param path_prefix: The path prefix for filtering the results. For example: /company/servercerts would get all server certificates for which the path starts with /company/servercerts . This parameter is optional. If it is not included, it defaults to a slash (/), listing all server certificates. This parameter allows (per its regex pattern) a string of characters consisting of either a forward slash (/) by itself or a string that must begin and end with forward slashes. In addition, it can contain any ASCII character from the ! (u0021) through the DEL character (u007F), including most punctuation characters, digits, and upper and lowercased letters. CLI Example: .. code-block:: bash salt myminion boto_iam.list_server_certificates path_prefix=/somepath/ ''' retries = 10 sleep = 6 conn = __utils__['boto3.get_connection']('iam', region=region, key=key, keyid=keyid, profile=profile) Items = [] while retries: try: log.debug('Garnering list of IAM Server Certificates') IsTruncated = True while IsTruncated: kwargs = {'PathPrefix': path_prefix} ret = conn.list_server_certificates(**kwargs) Items += ret.get('ServerCertificateMetadataList', []) IsTruncated = ret.get('IsTruncated') kwargs.update({'Marker': ret.get('Marker')}) return Items except botocore.exceptions.ParamValidationError as err: raise SaltInvocationError(str(err)) except botocore.exceptions.ClientError as err: if retries and jmespath.search('Error.Code', err.response) == 'Throttling': retries -= 1 log.debug('Throttled by AWS API, retrying in %s seconds...', sleep) time.sleep(sleep) continue log.error('Failed to list IAM Server Certificates: %s', err.message) return None def get_server_certificate(cert_name, region=None, key=None, keyid=None, profile=None): ''' Returns certificate information from Amazon .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_server_certificate mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_server_certificate(cert_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get certificate %s information.', cert_name) return False def delete_server_cert(cert_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a certificate from Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_server_cert mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_server_cert(cert_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete certificate %s.', cert_name) return False def export_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM user details. Produces results that can be used to create an sls file. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.export_users --out=txt | sed "s/local: //" > iam_users.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() users = get_all_users(path_prefix, region, key, keyid, profile) for user in users: name = user.user_name _policies = conn.get_all_user_policies(name, max_items=100) _policies = _policies.list_user_policies_response.list_user_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_user_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_user_policy_response.get_user_policy_result.policy_document )) policies[policy_name] = _policy user_sls = [] user_sls.append({"name": name}) user_sls.append({"policies": policies}) user_sls.append({"path": user.path}) results["manage user " + name] = {"boto_iam.user_present": user_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def export_roles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM role details. Produces results that can be used to create an sls file. CLI Example: salt-call boto_iam.export_roles --out=txt | sed "s/local: //" > iam_roles.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() roles = get_all_roles(path_prefix, region, key, keyid, profile) for role in roles: name = role.role_name _policies = conn.list_role_policies(name, max_items=100) _policies = _policies.list_role_policies_response.list_role_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_role_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_role_policy_response.get_role_policy_result.policy_document )) policies[policy_name] = _policy role_sls = [] role_sls.append({"name": name}) role_sls.append({"policies": policies}) role_sls.append({'policy_document': salt.utils.json.loads(_unquote(role.assume_role_policy_document))}) role_sls.append({"path": role.path}) results["manage role " + name] = {"boto_iam_role.present": role_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def _get_policy_arn(name, region=None, key=None, keyid=None, profile=None): if name.startswith('arn:aws:iam:'): return name account_id = get_account_id( region=region, key=key, keyid=keyid, profile=profile ) return 'arn:aws:iam::{0}:policy/{1}'.format(account_id, name) def policy_exists(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return True except boto.exception.BotoServerError: return False def get_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return ret.get('get_policy_response', {}).get('get_policy_result', {}) except boto.exception.BotoServerError: return None def create_policy(policy_name, policy_document, path=None, description=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in 'path', 'description': if locals()[arg] is not None: params[arg] = locals()[arg] if policy_exists(policy_name, region, key, keyid, profile): return True try: conn.create_policy(policy_name, policy_document, **params) log.info('Created IAM policy %s.', policy_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s.', policy_name) return False return True def delete_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_exists(policy_arn, region, key, keyid, profile): return True try: conn.delete_policy(policy_arn) log.info('Deleted %s policy.', policy_name) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete %s policy: %s.', policy_name, aws.get('message')) return False return True def list_policies(region=None, key=None, keyid=None, profile=None): ''' List policies. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policies ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: policies = [] for ret in __utils__['boto.paged_call'](conn.list_policies): policies.append(ret.get('list_policies_response', {}).get('list_policies_result', {}).get('policies')) return policies except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to list policy versions.' log.error(msg) return [] def policy_version_exists(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.get_policy_version(policy_arn, version_id) return True except boto.exception.BotoServerError: return False def get_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy_version(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile), version_id) retval = ret.get('get_policy_version_response', {}).get('get_policy_version_result', {}).get('policy_version', {}) retval['document'] = _unquote(retval.get('document')) return {'policy_version': retval} except boto.exception.BotoServerError: return None def create_policy_version(policy_name, policy_document, set_as_default=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy version. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy_version mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in ('set_as_default',): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.create_policy_version(policy_arn, policy_document, **params) vid = ret.get('create_policy_version_response', {}).get('create_policy_version_result', {}).get('policy_version', {}).get('version_id') log.info('Created IAM policy %s version %s.', policy_name, vid) return {'created': True, 'version_id': vid} except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s version %s.', policy_name, vid) return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Delete a policy version. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_version_exists(policy_arn, version_id, region, key, keyid, profile): return True try: conn.delete_policy_version(policy_arn, version_id) log.info('Deleted IAM policy %s version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete IAM policy %s version %s: %s', policy_name, version_id, aws.get('message')) return False return True def set_default_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Set the default version of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.set_default_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.set_default_policy_version(policy_arn, version_id) log.info('Set %s policy to version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to set %s policy to version %s: %s', policy_name, version_id, aws.get('message')) return False return True def attach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_user_policy(policy_arn, user_name) log.info('Attached policy %s to IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach %s policy to IAM user %s.', policy_name, user_name) return False return True def detach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_user_policy(policy_arn, user_name) log.info('Detached %s policy from IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach %s policy from IAM user %s.', policy_name, user_name) return False return True def attach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_group_policy(policy_arn, group_name) log.info('Attached policy %s to IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM group %s.', policy_name, group_name) return False return True def detach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_group_policy(policy_arn, group_name) log.info('Detached policy %s from IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM group %s.', policy_name, group_name) return False return True def attach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_role_policy(policy_arn, role_name) log.info('Attached policy %s to IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM role %s.', policy_name, role_name) return False return True def detach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_role_policy(policy_arn, role_name) log.info('Detached policy %s from IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM role %s.', policy_name, role_name) return False return True def list_entities_for_policy(policy_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities that a policy is attached to. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 params = {} for arg in ('path_prefix', 'entity_filter'): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) while retries: try: allret = { 'policy_groups': [], 'policy_users': [], 'policy_roles': [], } for ret in __utils__['boto.paged_call'](conn.list_entities_for_policy, policy_arn=policy_arn, **params): for k, v in six.iteritems(allret): v.extend(ret.get('list_entities_for_policy_response', {}).get('list_entities_for_policy_result', {}).get(k)) return allret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('Failed to list entities for IAM policy %s: %s', policy_name, e.message) return {} return {} def list_attached_user_policies(user_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given user. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'UserName': user_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedUserPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_user_policies_response', {}).get('list_attached_user_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM user %s.', user_name) return [] def list_attached_group_policies(group_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given group. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'GroupName': group_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedGroupPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_group_policies_response', {}).get('list_attached_group_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM group %s.', group_name) return [] def list_attached_role_policies(role_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'RoleName': role_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedRolePolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_role_policies_response', {}).get('list_attached_role_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM role %s.', role_name) return [] def create_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Create SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.create_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_saml_provider(saml_metadata_document, name) log.info('Successfully created %s SAML provider.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to create SAML provider %s.', name) return False def get_saml_provider_arn(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider_arn my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_saml_providers() for saml_provider in response.list_saml_providers_response.list_saml_providers_result.saml_provider_list: if saml_provider['arn'].endswith(':saml-provider/' + name): return saml_provider['arn'] return False except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to get ARN of SAML provider %s.', name) return False def delete_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Delete SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.delete_saml_provider my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return True conn.delete_saml_provider(saml_provider_arn) log.info('Successfully deleted SAML provider %s.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete SAML provider %s.', name) return False def list_saml_providers(region=None, key=None, keyid=None, profile=None): ''' List SAML providers. CLI Example: .. code-block:: bash salt myminion boto_iam.list_saml_providers ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: providers = [] info = conn.list_saml_providers() for arn in info['list_saml_providers_response']['list_saml_providers_result']['saml_provider_list']: providers.append(arn['arn'].rsplit('/', 1)[1]) return providers except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get list of SAML providers.') return False def get_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider document. CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider arn ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: provider = conn.get_saml_provider(name) return provider['get_saml_provider_response']['get_saml_provider_result']['saml_metadata_document'] except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get SAML provider document %s.', name) return False def update_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Update SAML provider. CLI Example: .. code-block:: bash salt myminion boto_iam.update_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return False if conn.update_saml_provider(name, saml_metadata_document): return True return False except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to update SAML provider %s.', name) return False
saltstack/salt
salt/modules/boto_iam.py
detach_user_policy
python
def detach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_user_policy(policy_arn, user_name) log.info('Detached %s policy from IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach %s policy from IAM user %s.', policy_name, user_name) return False return True
Detach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_user_policy mypolicy myuser
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iam.py#L2006-L2027
[ "def _get_policy_arn(name, region=None, key=None, keyid=None, profile=None):\n if name.startswith('arn:aws:iam:'):\n return name\n\n account_id = get_account_id(\n region=region, key=key, keyid=keyid, profile=profile\n )\n return 'arn:aws:iam::{0}:policy/{1}'.format(account_id, name)\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon IAM .. versionadded:: 2014.7.0 :configuration: This module accepts explicit iam 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 iam.keyid: GKTADJGHEIQSXMKKRBJ08H iam.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs iam.region: 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: boto ''' # keep lint from choking on _get_conn and _cache_id #pylint: disable=E0602 # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import salt libs from salt.ext import six import salt.utils.compat import salt.utils.json import salt.utils.odict as odict import salt.utils.versions from salt.exceptions import SaltInvocationError # Import third party libs # pylint: disable=unused-import from salt.ext.six.moves.urllib.parse import unquote as _unquote # pylint: disable=no-name-in-module try: import boto import boto.iam import boto3 import botocore logging.getLogger('boto').setLevel(logging.CRITICAL) logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=unused-import log = logging.getLogger(__name__) def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'iam', pack=__salt__) def instance_profile_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an instance profile exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: # Boto weirdly returns an exception here if an instance profile doesn't # exist. conn.get_instance_profile(name) return True except boto.exception.BotoServerError: return False def create_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Create an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.create_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if instance_profile_exists(name, region, key, keyid, profile): return True try: # This call returns an instance profile if successful and an exception # if not. It's annoying. conn.create_instance_profile(name) log.info('Created %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create %s instance profile.', name) return False return True def delete_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Delete an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not instance_profile_exists(name, region, key, keyid, profile): return True try: conn.delete_instance_profile(name) log.info('Deleted %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s instance profile.', name) return False return True def role_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an IAM role exists. CLI Example: .. code-block:: bash salt myminion boto_iam.role_exists myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_role(name) return True except boto.exception.BotoServerError: return False def describe_role(name, region=None, key=None, keyid=None, profile=None): ''' Get information for a role. CLI Example: .. code-block:: bash salt myminion boto_iam.describe_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_role(name) if not info: return False role = info.get_role_response.get_role_result.role role['assume_role_policy_document'] = salt.utils.json.loads(_unquote( role.assume_role_policy_document )) # If Sid wasn't defined by the user, boto will still return a Sid in # each policy. To properly check idempotently, let's remove the Sid # from the return if it's not actually set. for policy_key, policy in role['assume_role_policy_document'].items(): if policy_key == 'Statement': for val in policy: if 'Sid' in val and not val['Sid']: del val['Sid'] return role except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get %s information.', name) return False def create_user(user_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_user myuser ''' if not path: path = '/' if get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_user(user_name, path) log.info('Created IAM user : %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM user %s.', user_name) return False def get_all_access_keys(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all access keys from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_access_keys myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.get_all_access_keys(user_name, marker, max_items) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get access keys for IAM user %s.', user_name) return six.text_type(e) def create_access_key(user_name, region=None, key=None, keyid=None, profile=None): ''' Create access key id for a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.create_access_key(user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create access key.') return six.text_type(e) def delete_access_key(access_key_id, user_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete access key id from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_access_key(access_key_id, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete access key id %s.', access_key_id) return six.text_type(e) def delete_user(user_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user myuser ''' if not get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.delete_user(user_name) log.info('Deleted IAM user : %s .', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM user %s', user_name) return six.text_type(e) def get_user(user_name=None, region=None, key=None, keyid=None, profile=None): ''' Get user information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user(user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM user %s info.', user_name) return False def create_group(group_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_group group ''' if not path: path = '/' if get_group(group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_group(group_name, path) log.info('Created IAM group : %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM group %s.', group_name) return False def get_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group(group_name, max_items=1) if not info: return False return info['get_group_response']['get_group_result']['group'] except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_group_members(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: marker = None truncated = True users = [] while truncated: info = conn.get_group(group_name, marker=marker, max_items=1000) if not info: return False truncated = bool(info['get_group_response']['get_group_result']['is_truncated']) if truncated and 'marker' in info['get_group_response']['get_group_result']: marker = info['get_group_response']['get_group_result']['marker'] else: marker = None truncated = False users += info['get_group_response']['get_group_result']['users'] return users except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get members for IAM group %s.', group_name) return False def add_user_to_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Add user to group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.add_user_to_group myuser mygroup ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('Username : %s does not exist.', user_name) return False if user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.add_user_to_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add IAM user %s to group %s.', user_name, group_name) return False def user_exists_in_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Check if user exists in group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.user_exists_in_group myuser mygroup ''' # TODO this should probably use boto.iam.get_groups_for_user users = get_group_members( group_name=group_name, region=region, key=key, keyid=keyid, profile=profile ) if users: for _user in users: if user_name == _user['user_name']: log.debug('IAM user %s is already in IAM group %s.', user_name, group_name) return True return False def remove_user_from_group(group_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Remove user from group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.remove_user_from_group mygroup myuser ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist.', user_name) return False if not user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.remove_user_from_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove IAM user %s from group %s', user_name, group_name) return False def put_group_policy(group_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_group_policy mygroup policyname policyrules ''' group = get_group(group_name, region=region, key=key, keyid=keyid, profile=profile) if not group: log.error('Group %s does not exist', group_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_group_policy(group_name, policy_name, policy_json) if created: log.info('Created policy for IAM group %s.', group_name) return True log.error('Could not create policy for IAM group %s', group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy for IAM group %s', group_name) return False def delete_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group_policy mygroup mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_group_policy( group_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_group_policy(group_name, policy_name) log.info('Successfully deleted policy %s for IAM group %s.', policy_name, group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM group %s.', policy_name, group_name) return False def get_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group_policy mygroup policyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group_policy(group_name, policy_name) log.debug('info for group policy is : %s', info) if not info: return False info = info.get_group_policy_response.get_group_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_all_groups(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM group details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_groups ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _groups = conn.get_all_groups(path_prefix=path_prefix) groups = _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) while marker: _groups = conn.get_all_groups(path_prefix=path_prefix, marker=marker) groups = groups + _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) return groups def get_all_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.get_all_instance_profiles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) marker = False profiles = [] while marker is not None: marker = marker if marker else None p = conn.list_instance_profiles(path_prefix=path_prefix, marker=marker) res = p.list_instance_profiles_response.list_instance_profiles_result profiles += res.instance_profiles marker = getattr(res, 'marker', None) return profiles def list_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' List all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.list_instance_profiles ''' p = get_all_instance_profiles(path_prefix, region, key, keyid, profile) return [i['instance_profile_name'] for i in p] def get_all_group_policies(group_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a group. CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_group_policies mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False try: response = conn.get_all_group_policies(group_name) _list = response.list_group_policies_response.list_group_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def delete_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _group = get_group( group_name, region, key, keyid, profile ) if not _group: return True try: conn.delete_group(group_name) log.info('Successfully deleted IAM group %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM group %s.', group_name) return False def create_login_profile(user_name, password, region=None, key=None, keyid=None, profile=None): ''' Creates a login profile for the specified user, give the user the ability to access AWS services and the AWS Management Console. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_login_profile user_name password ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.create_login_profile(user_name, password) log.info('Created profile for IAM user %s.', user_name) return info except boto.exception.BotoServerError as e: log.debug(e) if 'Conflict' in e: log.info('Profile already exists for IAM user %s.', user_name) return 'Conflict' log.error('Failed to update profile for IAM user %s.', user_name) return False def delete_login_profile(user_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a login profile for the specified user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_login_profile user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.delete_login_profile(user_name) log.info('Deleted login profile for IAM user %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Login profile already deleted for IAM user %s.', user_name) return True log.error('Failed to delete login profile for IAM user %s.', user_name) return False def get_all_mfa_devices(user_name, region=None, key=None, keyid=None, profile=None): ''' Get all MFA devices associated with an IAM user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_mfa_devices user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: result = conn.get_all_mfa_devices(user_name) devices = result['list_mfa_devices_response']['list_mfa_devices_result']['mfa_devices'] return devices except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Could not find IAM user %s.', user_name) return [] log.error('Failed to get all MFA devices for IAM user %s.', user_name) return False def deactivate_mfa_device(user_name, serial, region=None, key=None, keyid=None, profile=None): ''' Deactivates the specified MFA device and removes it from association with the user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.deactivate_mfa_device user_name serial_num ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.deactivate_mfa_device(user_name, serial) log.info('Deactivated MFA device %s for IAM user %s.', serial, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('MFA device %s not associated with IAM user %s.', serial, user_name) return True log.error('Failed to deactivate MFA device %s for IAM user %s.', serial, user_name) return False def delete_virtual_mfa_device(serial, region=None, key=None, keyid=None, profile=None): ''' Deletes the specified virtual MFA device. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_virtual_mfa_device serial_num ''' conn = __utils__['boto3.get_connection_func']('iam')() try: conn.delete_virtual_mfa_device(SerialNumber=serial) log.info('Deleted virtual MFA device %s.', serial) return True except botocore.exceptions.ClientError as e: log.debug(e) if 'NoSuchEntity' in six.text_type(e): log.info('Virtual MFA device %s not found.', serial) return True log.error('Failed to delete virtual MFA device %s.', serial) return False def update_account_password_policy(allow_users_to_change_password=None, hard_expiry=None, max_password_age=None, minimum_password_length=None, password_reuse_prevention=None, require_lowercase_characters=None, require_numbers=None, require_symbols=None, require_uppercase_characters=None, region=None, key=None, keyid=None, profile=None): ''' Update the password policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_account_password_policy True ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.update_account_password_policy(allow_users_to_change_password, hard_expiry, max_password_age, minimum_password_length, password_reuse_prevention, require_lowercase_characters, require_numbers, require_symbols, require_uppercase_characters) log.info('The password policy has been updated.') return True except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy' log.error(msg) return False def get_account_policy(region=None, key=None, keyid=None, profile=None): ''' Get account policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_account_password_policy() return info.get_account_password_policy_response.get_account_password_policy_result.password_policy except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy.' log.error(msg) return False def create_role(name, policy_document=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Create an instance role. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if role_exists(name, region, key, keyid, profile): return True if not policy_document: policy_document = None try: conn.create_role(name, assume_role_policy_document=policy_document, path=path) log.info('Created IAM role %s.', name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to create IAM role %s.', name) return False def delete_role(name, region=None, key=None, keyid=None, profile=None): ''' Delete an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(name, region, key, keyid, profile): return True try: conn.delete_role(name) log.info('Deleted %s IAM role.', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s IAM role.', name) return False def profile_associated(role_name, profile_name, region, key, keyid, profile): ''' Check to see if an instance profile is associated with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.profile_associated myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # The IAM module of boto doesn't return objects. Instead you need to grab # values through its properties. Sigh. try: profiles = conn.list_instance_profiles_for_role(role_name) except boto.exception.BotoServerError as e: log.debug(e) return False profiles = profiles.list_instance_profiles_for_role_response profiles = profiles.list_instance_profiles_for_role_result profiles = profiles.instance_profiles for profile in profiles: if profile.instance_profile_name == profile_name: return True return False def associate_profile_to_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Associate an instance profile with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.associate_profile_to_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if associated: return True else: try: conn.add_role_to_instance_profile(profile_name, role_name) log.info('Added %s instance profile to IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add %s instance profile to IAM role %s', profile_name, role_name) return False def disassociate_profile_from_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Disassociate an instance profile from an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.disassociate_profile_from_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if not associated: return True else: try: conn.remove_role_from_instance_profile(profile_name, role_name) log.info('Removed %s instance profile from IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove %s instance profile from IAM role %s.', profile_name, role_name) return False def list_role_policies(role_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_role_policies myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_role_policies(role_name) _list = response.list_role_policies_response.list_role_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def get_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.get_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: _policy = conn.get_role_policy(role_name, policy_name) # I _hate_ you for not giving me an object boto. _policy = _policy.get_role_policy_response.policy_document # Policy is url encoded _policy = _unquote(_policy) _policy = salt.utils.json.loads(_policy, object_pairs_hook=odict.OrderedDict) return _policy except boto.exception.BotoServerError: return {} def create_role_policy(role_name, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Create or modify a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role_policy myirole mypolicy '{"MyPolicy": "Statement": [{"Action": ["sqs:*"], "Effect": "Allow", "Resource": ["arn:aws:sqs:*:*:*"], "Sid": "MyPolicySqs1"}]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) mode = 'create' if _policy: if _policy == policy: return True mode = 'modify' if isinstance(policy, six.string_types): policy = salt.utils.json.loads(policy, object_pairs_hook=odict.OrderedDict) try: _policy = salt.utils.json.dumps(policy) conn.put_role_policy(role_name, policy_name, _policy) if mode == 'create': msg = 'Successfully added policy %s to IAM role %s.' else: msg = 'Successfully modified policy %s for IAM role %s.' log.info(msg, policy_name, role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to %s policy %s for IAM role %s.', mode, policy_name, role_name) return False def delete_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) if not _policy: return True try: conn.delete_role_policy(role_name, policy_name) log.info('Successfully deleted policy %s for IAM role %s.', policy_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM role %s.', policy_name, role_name) return False def update_assume_role_policy(role_name, policy_document, region=None, key=None, keyid=None, profile=None): ''' Update an assume role policy for a role. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_assume_role_policy myrole '{"Statement":"..."}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(policy_document, six.string_types): policy_document = salt.utils.json.loads(policy_document, object_pairs_hook=odict.OrderedDict) try: _policy_document = salt.utils.json.dumps(policy_document) conn.update_assume_role_policy(role_name, _policy_document) log.info('Successfully updated assume role policy for IAM role %s.', role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to update assume role policy for IAM role %s.', role_name) return False def build_policy(region=None, key=None, keyid=None, profile=None): ''' Build a default assume role policy. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.build_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if hasattr(conn, 'build_policy'): policy = salt.utils.json.loads(conn.build_policy()) elif hasattr(conn, '_build_policy'): policy = salt.utils.json.loads(conn._build_policy()) else: return {} # The format we get from build_policy isn't going to be what we get back # from AWS for the exact same policy. AWS converts single item list values # into strings, so let's do the same here. for key, policy_val in policy.items(): for statement in policy_val: if (isinstance(statement['Action'], list) and len(statement['Action']) == 1): statement['Action'] = statement['Action'][0] if (isinstance(statement['Principal']['Service'], list) and len(statement['Principal']['Service']) == 1): statement['Principal']['Service'] = statement['Principal']['Service'][0] # build_policy doesn't add a version field, which AWS is going to set to a # default value, when we get it back, so let's set it. policy['Version'] = '2008-10-17' return policy def get_account_id(region=None, key=None, keyid=None, profile=None): ''' Get a the AWS account id associated with the used credentials. CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_id ''' cache_key = 'boto_iam.account_id' if cache_key not in __context__: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_user() # The get_user call returns an user ARN: # arn:aws:iam::027050522557:user/salt-test arn = ret['get_user_response']['get_user_result']['user']['arn'] account_id = arn.split(':')[4] except boto.exception.BotoServerError: # If call failed, then let's try to get the ARN from the metadata timeout = boto.config.getfloat( 'Boto', 'metadata_service_timeout', 1.0 ) attempts = boto.config.getint( 'Boto', 'metadata_service_num_attempts', 1 ) identity = boto.utils.get_instance_identity( timeout=timeout, num_retries=attempts ) try: account_id = identity['document']['accountId'] except KeyError: log.error('Failed to get account id from instance_identity in' ' boto_iam.get_account_id.') __context__[cache_key] = account_id return __context__[cache_key] def get_all_roles(path_prefix=None, region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM role details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_roles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _roles = conn.list_roles(path_prefix=path_prefix) roles = _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) while marker: _roles = conn.list_roles(path_prefix=path_prefix, marker=marker) roles = roles + _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) return roles def get_all_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM user details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_users ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _users = conn.get_all_users(path_prefix=path_prefix) users = _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) while marker: _users = conn.get_all_users(path_prefix=path_prefix, marker=marker) users = users + _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) return users def get_all_user_policies(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all user policies. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_user_policies myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_all_user_policies(user_name, marker, max_items) if not info: return False _list = info.list_user_policies_response.list_user_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policies for user %s.', user_name) return False def get_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user_policy myuser mypolicyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user_policy(user_name, policy_name) log.debug('Info for IAM user %s policy %s: %s.', user_name, policy_name, info) if not info: return False info = info.get_user_policy_response.get_user_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policy %s for IAM user %s.', policy_name, user_name) return False def put_user_policy(user_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_user_policy myuser policyname policyrules ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_user_policy(user_name, policy_name, policy_json) if created: log.info('Created policy %s for IAM user %s.', policy_name, user_name) return True log.error('Could not create policy %s for IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy %s for IAM user %s.', policy_name, user_name) return False def delete_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user_policy myuser mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_user_policy( user_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_user_policy(user_name, policy_name) log.info('Successfully deleted policy %s for IAM user %s.', policy_name, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM user %s.', policy_name, user_name) return False def upload_server_cert(cert_name, cert_body, private_key, cert_chain=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Upload a certificate to Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.upload_server_cert mycert_name crt priv_key :param cert_name: The name for the server certificate. Do not include the path in this value. :param cert_body: The contents of the public key certificate in PEM-encoded format. :param private_key: The contents of the private key in PEM-encoded format. :param cert_chain: The contents of the certificate chain. This is typically a concatenation of the PEM-encoded public key certificates of the chain. :param path: The path for the server certificate. :param region: The name of the region to connect to. :param key: The key to be used in order to connect :param keyid: The keyid to be used in order to connect :param profile: The profile that contains a dict of region, key, keyid :return: True / False ''' exists = get_server_certificate(cert_name, region, key, keyid, profile) if exists: return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.upload_server_cert(cert_name, cert_body, private_key, cert_chain) log.info('Created certificate %s.', cert_name) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to failed to create certificate %s.', cert_name) return False def list_server_certificates(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Lists the server certificates stored in IAM that have the specified path prefix. .. versionadded:: ??? :param path_prefix: The path prefix for filtering the results. For example: /company/servercerts would get all server certificates for which the path starts with /company/servercerts . This parameter is optional. If it is not included, it defaults to a slash (/), listing all server certificates. This parameter allows (per its regex pattern) a string of characters consisting of either a forward slash (/) by itself or a string that must begin and end with forward slashes. In addition, it can contain any ASCII character from the ! (u0021) through the DEL character (u007F), including most punctuation characters, digits, and upper and lowercased letters. CLI Example: .. code-block:: bash salt myminion boto_iam.list_server_certificates path_prefix=/somepath/ ''' retries = 10 sleep = 6 conn = __utils__['boto3.get_connection']('iam', region=region, key=key, keyid=keyid, profile=profile) Items = [] while retries: try: log.debug('Garnering list of IAM Server Certificates') IsTruncated = True while IsTruncated: kwargs = {'PathPrefix': path_prefix} ret = conn.list_server_certificates(**kwargs) Items += ret.get('ServerCertificateMetadataList', []) IsTruncated = ret.get('IsTruncated') kwargs.update({'Marker': ret.get('Marker')}) return Items except botocore.exceptions.ParamValidationError as err: raise SaltInvocationError(str(err)) except botocore.exceptions.ClientError as err: if retries and jmespath.search('Error.Code', err.response) == 'Throttling': retries -= 1 log.debug('Throttled by AWS API, retrying in %s seconds...', sleep) time.sleep(sleep) continue log.error('Failed to list IAM Server Certificates: %s', err.message) return None def get_server_certificate(cert_name, region=None, key=None, keyid=None, profile=None): ''' Returns certificate information from Amazon .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_server_certificate mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_server_certificate(cert_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get certificate %s information.', cert_name) return False def delete_server_cert(cert_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a certificate from Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_server_cert mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_server_cert(cert_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete certificate %s.', cert_name) return False def export_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM user details. Produces results that can be used to create an sls file. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.export_users --out=txt | sed "s/local: //" > iam_users.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() users = get_all_users(path_prefix, region, key, keyid, profile) for user in users: name = user.user_name _policies = conn.get_all_user_policies(name, max_items=100) _policies = _policies.list_user_policies_response.list_user_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_user_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_user_policy_response.get_user_policy_result.policy_document )) policies[policy_name] = _policy user_sls = [] user_sls.append({"name": name}) user_sls.append({"policies": policies}) user_sls.append({"path": user.path}) results["manage user " + name] = {"boto_iam.user_present": user_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def export_roles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM role details. Produces results that can be used to create an sls file. CLI Example: salt-call boto_iam.export_roles --out=txt | sed "s/local: //" > iam_roles.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() roles = get_all_roles(path_prefix, region, key, keyid, profile) for role in roles: name = role.role_name _policies = conn.list_role_policies(name, max_items=100) _policies = _policies.list_role_policies_response.list_role_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_role_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_role_policy_response.get_role_policy_result.policy_document )) policies[policy_name] = _policy role_sls = [] role_sls.append({"name": name}) role_sls.append({"policies": policies}) role_sls.append({'policy_document': salt.utils.json.loads(_unquote(role.assume_role_policy_document))}) role_sls.append({"path": role.path}) results["manage role " + name] = {"boto_iam_role.present": role_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def _get_policy_arn(name, region=None, key=None, keyid=None, profile=None): if name.startswith('arn:aws:iam:'): return name account_id = get_account_id( region=region, key=key, keyid=keyid, profile=profile ) return 'arn:aws:iam::{0}:policy/{1}'.format(account_id, name) def policy_exists(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return True except boto.exception.BotoServerError: return False def get_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return ret.get('get_policy_response', {}).get('get_policy_result', {}) except boto.exception.BotoServerError: return None def create_policy(policy_name, policy_document, path=None, description=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in 'path', 'description': if locals()[arg] is not None: params[arg] = locals()[arg] if policy_exists(policy_name, region, key, keyid, profile): return True try: conn.create_policy(policy_name, policy_document, **params) log.info('Created IAM policy %s.', policy_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s.', policy_name) return False return True def delete_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_exists(policy_arn, region, key, keyid, profile): return True try: conn.delete_policy(policy_arn) log.info('Deleted %s policy.', policy_name) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete %s policy: %s.', policy_name, aws.get('message')) return False return True def list_policies(region=None, key=None, keyid=None, profile=None): ''' List policies. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policies ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: policies = [] for ret in __utils__['boto.paged_call'](conn.list_policies): policies.append(ret.get('list_policies_response', {}).get('list_policies_result', {}).get('policies')) return policies except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to list policy versions.' log.error(msg) return [] def policy_version_exists(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.get_policy_version(policy_arn, version_id) return True except boto.exception.BotoServerError: return False def get_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy_version(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile), version_id) retval = ret.get('get_policy_version_response', {}).get('get_policy_version_result', {}).get('policy_version', {}) retval['document'] = _unquote(retval.get('document')) return {'policy_version': retval} except boto.exception.BotoServerError: return None def create_policy_version(policy_name, policy_document, set_as_default=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy version. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy_version mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in ('set_as_default',): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.create_policy_version(policy_arn, policy_document, **params) vid = ret.get('create_policy_version_response', {}).get('create_policy_version_result', {}).get('policy_version', {}).get('version_id') log.info('Created IAM policy %s version %s.', policy_name, vid) return {'created': True, 'version_id': vid} except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s version %s.', policy_name, vid) return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Delete a policy version. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_version_exists(policy_arn, version_id, region, key, keyid, profile): return True try: conn.delete_policy_version(policy_arn, version_id) log.info('Deleted IAM policy %s version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete IAM policy %s version %s: %s', policy_name, version_id, aws.get('message')) return False return True def list_policy_versions(policy_name, region=None, key=None, keyid=None, profile=None): ''' List versions of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policy_versions mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.list_policy_versions(policy_arn) return ret.get('list_policy_versions_response', {}).get('list_policy_versions_result', {}).get('versions') except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list versions for IAM policy %s.', policy_name) return [] def set_default_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Set the default version of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.set_default_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.set_default_policy_version(policy_arn, version_id) log.info('Set %s policy to version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to set %s policy to version %s: %s', policy_name, version_id, aws.get('message')) return False return True def attach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_user_policy(policy_arn, user_name) log.info('Attached policy %s to IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach %s policy to IAM user %s.', policy_name, user_name) return False return True def attach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_group_policy(policy_arn, group_name) log.info('Attached policy %s to IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM group %s.', policy_name, group_name) return False return True def detach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_group_policy(policy_arn, group_name) log.info('Detached policy %s from IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM group %s.', policy_name, group_name) return False return True def attach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_role_policy(policy_arn, role_name) log.info('Attached policy %s to IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM role %s.', policy_name, role_name) return False return True def detach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_role_policy(policy_arn, role_name) log.info('Detached policy %s from IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM role %s.', policy_name, role_name) return False return True def list_entities_for_policy(policy_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities that a policy is attached to. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 params = {} for arg in ('path_prefix', 'entity_filter'): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) while retries: try: allret = { 'policy_groups': [], 'policy_users': [], 'policy_roles': [], } for ret in __utils__['boto.paged_call'](conn.list_entities_for_policy, policy_arn=policy_arn, **params): for k, v in six.iteritems(allret): v.extend(ret.get('list_entities_for_policy_response', {}).get('list_entities_for_policy_result', {}).get(k)) return allret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('Failed to list entities for IAM policy %s: %s', policy_name, e.message) return {} return {} def list_attached_user_policies(user_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given user. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'UserName': user_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedUserPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_user_policies_response', {}).get('list_attached_user_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM user %s.', user_name) return [] def list_attached_group_policies(group_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given group. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'GroupName': group_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedGroupPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_group_policies_response', {}).get('list_attached_group_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM group %s.', group_name) return [] def list_attached_role_policies(role_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'RoleName': role_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedRolePolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_role_policies_response', {}).get('list_attached_role_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM role %s.', role_name) return [] def create_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Create SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.create_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_saml_provider(saml_metadata_document, name) log.info('Successfully created %s SAML provider.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to create SAML provider %s.', name) return False def get_saml_provider_arn(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider_arn my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_saml_providers() for saml_provider in response.list_saml_providers_response.list_saml_providers_result.saml_provider_list: if saml_provider['arn'].endswith(':saml-provider/' + name): return saml_provider['arn'] return False except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to get ARN of SAML provider %s.', name) return False def delete_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Delete SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.delete_saml_provider my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return True conn.delete_saml_provider(saml_provider_arn) log.info('Successfully deleted SAML provider %s.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete SAML provider %s.', name) return False def list_saml_providers(region=None, key=None, keyid=None, profile=None): ''' List SAML providers. CLI Example: .. code-block:: bash salt myminion boto_iam.list_saml_providers ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: providers = [] info = conn.list_saml_providers() for arn in info['list_saml_providers_response']['list_saml_providers_result']['saml_provider_list']: providers.append(arn['arn'].rsplit('/', 1)[1]) return providers except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get list of SAML providers.') return False def get_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider document. CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider arn ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: provider = conn.get_saml_provider(name) return provider['get_saml_provider_response']['get_saml_provider_result']['saml_metadata_document'] except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get SAML provider document %s.', name) return False def update_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Update SAML provider. CLI Example: .. code-block:: bash salt myminion boto_iam.update_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return False if conn.update_saml_provider(name, saml_metadata_document): return True return False except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to update SAML provider %s.', name) return False
saltstack/salt
salt/modules/boto_iam.py
list_entities_for_policy
python
def list_entities_for_policy(policy_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities that a policy is attached to. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 params = {} for arg in ('path_prefix', 'entity_filter'): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) while retries: try: allret = { 'policy_groups': [], 'policy_users': [], 'policy_roles': [], } for ret in __utils__['boto.paged_call'](conn.list_entities_for_policy, policy_arn=policy_arn, **params): for k, v in six.iteritems(allret): v.extend(ret.get('list_entities_for_policy_response', {}).get('list_entities_for_policy_result', {}).get(k)) return allret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('Failed to list entities for IAM policy %s: %s', policy_name, e.message) return {} return {}
List entities that a policy is attached to. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iam.py#L2126-L2165
[ "def iteritems(d, **kw):\n return d.iteritems(**kw)\n", "def _get_policy_arn(name, region=None, key=None, keyid=None, profile=None):\n if name.startswith('arn:aws:iam:'):\n return name\n\n account_id = get_account_id(\n region=region, key=key, keyid=keyid, profile=profile\n )\n return 'arn:aws:iam::{0}:policy/{1}'.format(account_id, name)\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon IAM .. versionadded:: 2014.7.0 :configuration: This module accepts explicit iam 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 iam.keyid: GKTADJGHEIQSXMKKRBJ08H iam.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs iam.region: 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: boto ''' # keep lint from choking on _get_conn and _cache_id #pylint: disable=E0602 # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import salt libs from salt.ext import six import salt.utils.compat import salt.utils.json import salt.utils.odict as odict import salt.utils.versions from salt.exceptions import SaltInvocationError # Import third party libs # pylint: disable=unused-import from salt.ext.six.moves.urllib.parse import unquote as _unquote # pylint: disable=no-name-in-module try: import boto import boto.iam import boto3 import botocore logging.getLogger('boto').setLevel(logging.CRITICAL) logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=unused-import log = logging.getLogger(__name__) def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'iam', pack=__salt__) def instance_profile_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an instance profile exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: # Boto weirdly returns an exception here if an instance profile doesn't # exist. conn.get_instance_profile(name) return True except boto.exception.BotoServerError: return False def create_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Create an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.create_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if instance_profile_exists(name, region, key, keyid, profile): return True try: # This call returns an instance profile if successful and an exception # if not. It's annoying. conn.create_instance_profile(name) log.info('Created %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create %s instance profile.', name) return False return True def delete_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Delete an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not instance_profile_exists(name, region, key, keyid, profile): return True try: conn.delete_instance_profile(name) log.info('Deleted %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s instance profile.', name) return False return True def role_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an IAM role exists. CLI Example: .. code-block:: bash salt myminion boto_iam.role_exists myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_role(name) return True except boto.exception.BotoServerError: return False def describe_role(name, region=None, key=None, keyid=None, profile=None): ''' Get information for a role. CLI Example: .. code-block:: bash salt myminion boto_iam.describe_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_role(name) if not info: return False role = info.get_role_response.get_role_result.role role['assume_role_policy_document'] = salt.utils.json.loads(_unquote( role.assume_role_policy_document )) # If Sid wasn't defined by the user, boto will still return a Sid in # each policy. To properly check idempotently, let's remove the Sid # from the return if it's not actually set. for policy_key, policy in role['assume_role_policy_document'].items(): if policy_key == 'Statement': for val in policy: if 'Sid' in val and not val['Sid']: del val['Sid'] return role except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get %s information.', name) return False def create_user(user_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_user myuser ''' if not path: path = '/' if get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_user(user_name, path) log.info('Created IAM user : %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM user %s.', user_name) return False def get_all_access_keys(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all access keys from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_access_keys myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.get_all_access_keys(user_name, marker, max_items) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get access keys for IAM user %s.', user_name) return six.text_type(e) def create_access_key(user_name, region=None, key=None, keyid=None, profile=None): ''' Create access key id for a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.create_access_key(user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create access key.') return six.text_type(e) def delete_access_key(access_key_id, user_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete access key id from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_access_key(access_key_id, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete access key id %s.', access_key_id) return six.text_type(e) def delete_user(user_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user myuser ''' if not get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.delete_user(user_name) log.info('Deleted IAM user : %s .', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM user %s', user_name) return six.text_type(e) def get_user(user_name=None, region=None, key=None, keyid=None, profile=None): ''' Get user information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user(user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM user %s info.', user_name) return False def create_group(group_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_group group ''' if not path: path = '/' if get_group(group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_group(group_name, path) log.info('Created IAM group : %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM group %s.', group_name) return False def get_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group(group_name, max_items=1) if not info: return False return info['get_group_response']['get_group_result']['group'] except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_group_members(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: marker = None truncated = True users = [] while truncated: info = conn.get_group(group_name, marker=marker, max_items=1000) if not info: return False truncated = bool(info['get_group_response']['get_group_result']['is_truncated']) if truncated and 'marker' in info['get_group_response']['get_group_result']: marker = info['get_group_response']['get_group_result']['marker'] else: marker = None truncated = False users += info['get_group_response']['get_group_result']['users'] return users except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get members for IAM group %s.', group_name) return False def add_user_to_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Add user to group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.add_user_to_group myuser mygroup ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('Username : %s does not exist.', user_name) return False if user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.add_user_to_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add IAM user %s to group %s.', user_name, group_name) return False def user_exists_in_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Check if user exists in group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.user_exists_in_group myuser mygroup ''' # TODO this should probably use boto.iam.get_groups_for_user users = get_group_members( group_name=group_name, region=region, key=key, keyid=keyid, profile=profile ) if users: for _user in users: if user_name == _user['user_name']: log.debug('IAM user %s is already in IAM group %s.', user_name, group_name) return True return False def remove_user_from_group(group_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Remove user from group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.remove_user_from_group mygroup myuser ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist.', user_name) return False if not user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.remove_user_from_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove IAM user %s from group %s', user_name, group_name) return False def put_group_policy(group_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_group_policy mygroup policyname policyrules ''' group = get_group(group_name, region=region, key=key, keyid=keyid, profile=profile) if not group: log.error('Group %s does not exist', group_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_group_policy(group_name, policy_name, policy_json) if created: log.info('Created policy for IAM group %s.', group_name) return True log.error('Could not create policy for IAM group %s', group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy for IAM group %s', group_name) return False def delete_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group_policy mygroup mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_group_policy( group_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_group_policy(group_name, policy_name) log.info('Successfully deleted policy %s for IAM group %s.', policy_name, group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM group %s.', policy_name, group_name) return False def get_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group_policy mygroup policyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group_policy(group_name, policy_name) log.debug('info for group policy is : %s', info) if not info: return False info = info.get_group_policy_response.get_group_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_all_groups(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM group details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_groups ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _groups = conn.get_all_groups(path_prefix=path_prefix) groups = _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) while marker: _groups = conn.get_all_groups(path_prefix=path_prefix, marker=marker) groups = groups + _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) return groups def get_all_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.get_all_instance_profiles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) marker = False profiles = [] while marker is not None: marker = marker if marker else None p = conn.list_instance_profiles(path_prefix=path_prefix, marker=marker) res = p.list_instance_profiles_response.list_instance_profiles_result profiles += res.instance_profiles marker = getattr(res, 'marker', None) return profiles def list_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' List all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.list_instance_profiles ''' p = get_all_instance_profiles(path_prefix, region, key, keyid, profile) return [i['instance_profile_name'] for i in p] def get_all_group_policies(group_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a group. CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_group_policies mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False try: response = conn.get_all_group_policies(group_name) _list = response.list_group_policies_response.list_group_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def delete_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _group = get_group( group_name, region, key, keyid, profile ) if not _group: return True try: conn.delete_group(group_name) log.info('Successfully deleted IAM group %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM group %s.', group_name) return False def create_login_profile(user_name, password, region=None, key=None, keyid=None, profile=None): ''' Creates a login profile for the specified user, give the user the ability to access AWS services and the AWS Management Console. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_login_profile user_name password ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.create_login_profile(user_name, password) log.info('Created profile for IAM user %s.', user_name) return info except boto.exception.BotoServerError as e: log.debug(e) if 'Conflict' in e: log.info('Profile already exists for IAM user %s.', user_name) return 'Conflict' log.error('Failed to update profile for IAM user %s.', user_name) return False def delete_login_profile(user_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a login profile for the specified user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_login_profile user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.delete_login_profile(user_name) log.info('Deleted login profile for IAM user %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Login profile already deleted for IAM user %s.', user_name) return True log.error('Failed to delete login profile for IAM user %s.', user_name) return False def get_all_mfa_devices(user_name, region=None, key=None, keyid=None, profile=None): ''' Get all MFA devices associated with an IAM user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_mfa_devices user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: result = conn.get_all_mfa_devices(user_name) devices = result['list_mfa_devices_response']['list_mfa_devices_result']['mfa_devices'] return devices except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Could not find IAM user %s.', user_name) return [] log.error('Failed to get all MFA devices for IAM user %s.', user_name) return False def deactivate_mfa_device(user_name, serial, region=None, key=None, keyid=None, profile=None): ''' Deactivates the specified MFA device and removes it from association with the user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.deactivate_mfa_device user_name serial_num ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.deactivate_mfa_device(user_name, serial) log.info('Deactivated MFA device %s for IAM user %s.', serial, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('MFA device %s not associated with IAM user %s.', serial, user_name) return True log.error('Failed to deactivate MFA device %s for IAM user %s.', serial, user_name) return False def delete_virtual_mfa_device(serial, region=None, key=None, keyid=None, profile=None): ''' Deletes the specified virtual MFA device. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_virtual_mfa_device serial_num ''' conn = __utils__['boto3.get_connection_func']('iam')() try: conn.delete_virtual_mfa_device(SerialNumber=serial) log.info('Deleted virtual MFA device %s.', serial) return True except botocore.exceptions.ClientError as e: log.debug(e) if 'NoSuchEntity' in six.text_type(e): log.info('Virtual MFA device %s not found.', serial) return True log.error('Failed to delete virtual MFA device %s.', serial) return False def update_account_password_policy(allow_users_to_change_password=None, hard_expiry=None, max_password_age=None, minimum_password_length=None, password_reuse_prevention=None, require_lowercase_characters=None, require_numbers=None, require_symbols=None, require_uppercase_characters=None, region=None, key=None, keyid=None, profile=None): ''' Update the password policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_account_password_policy True ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.update_account_password_policy(allow_users_to_change_password, hard_expiry, max_password_age, minimum_password_length, password_reuse_prevention, require_lowercase_characters, require_numbers, require_symbols, require_uppercase_characters) log.info('The password policy has been updated.') return True except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy' log.error(msg) return False def get_account_policy(region=None, key=None, keyid=None, profile=None): ''' Get account policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_account_password_policy() return info.get_account_password_policy_response.get_account_password_policy_result.password_policy except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy.' log.error(msg) return False def create_role(name, policy_document=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Create an instance role. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if role_exists(name, region, key, keyid, profile): return True if not policy_document: policy_document = None try: conn.create_role(name, assume_role_policy_document=policy_document, path=path) log.info('Created IAM role %s.', name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to create IAM role %s.', name) return False def delete_role(name, region=None, key=None, keyid=None, profile=None): ''' Delete an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(name, region, key, keyid, profile): return True try: conn.delete_role(name) log.info('Deleted %s IAM role.', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s IAM role.', name) return False def profile_associated(role_name, profile_name, region, key, keyid, profile): ''' Check to see if an instance profile is associated with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.profile_associated myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # The IAM module of boto doesn't return objects. Instead you need to grab # values through its properties. Sigh. try: profiles = conn.list_instance_profiles_for_role(role_name) except boto.exception.BotoServerError as e: log.debug(e) return False profiles = profiles.list_instance_profiles_for_role_response profiles = profiles.list_instance_profiles_for_role_result profiles = profiles.instance_profiles for profile in profiles: if profile.instance_profile_name == profile_name: return True return False def associate_profile_to_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Associate an instance profile with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.associate_profile_to_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if associated: return True else: try: conn.add_role_to_instance_profile(profile_name, role_name) log.info('Added %s instance profile to IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add %s instance profile to IAM role %s', profile_name, role_name) return False def disassociate_profile_from_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Disassociate an instance profile from an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.disassociate_profile_from_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if not associated: return True else: try: conn.remove_role_from_instance_profile(profile_name, role_name) log.info('Removed %s instance profile from IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove %s instance profile from IAM role %s.', profile_name, role_name) return False def list_role_policies(role_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_role_policies myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_role_policies(role_name) _list = response.list_role_policies_response.list_role_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def get_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.get_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: _policy = conn.get_role_policy(role_name, policy_name) # I _hate_ you for not giving me an object boto. _policy = _policy.get_role_policy_response.policy_document # Policy is url encoded _policy = _unquote(_policy) _policy = salt.utils.json.loads(_policy, object_pairs_hook=odict.OrderedDict) return _policy except boto.exception.BotoServerError: return {} def create_role_policy(role_name, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Create or modify a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role_policy myirole mypolicy '{"MyPolicy": "Statement": [{"Action": ["sqs:*"], "Effect": "Allow", "Resource": ["arn:aws:sqs:*:*:*"], "Sid": "MyPolicySqs1"}]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) mode = 'create' if _policy: if _policy == policy: return True mode = 'modify' if isinstance(policy, six.string_types): policy = salt.utils.json.loads(policy, object_pairs_hook=odict.OrderedDict) try: _policy = salt.utils.json.dumps(policy) conn.put_role_policy(role_name, policy_name, _policy) if mode == 'create': msg = 'Successfully added policy %s to IAM role %s.' else: msg = 'Successfully modified policy %s for IAM role %s.' log.info(msg, policy_name, role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to %s policy %s for IAM role %s.', mode, policy_name, role_name) return False def delete_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) if not _policy: return True try: conn.delete_role_policy(role_name, policy_name) log.info('Successfully deleted policy %s for IAM role %s.', policy_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM role %s.', policy_name, role_name) return False def update_assume_role_policy(role_name, policy_document, region=None, key=None, keyid=None, profile=None): ''' Update an assume role policy for a role. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_assume_role_policy myrole '{"Statement":"..."}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(policy_document, six.string_types): policy_document = salt.utils.json.loads(policy_document, object_pairs_hook=odict.OrderedDict) try: _policy_document = salt.utils.json.dumps(policy_document) conn.update_assume_role_policy(role_name, _policy_document) log.info('Successfully updated assume role policy for IAM role %s.', role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to update assume role policy for IAM role %s.', role_name) return False def build_policy(region=None, key=None, keyid=None, profile=None): ''' Build a default assume role policy. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.build_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if hasattr(conn, 'build_policy'): policy = salt.utils.json.loads(conn.build_policy()) elif hasattr(conn, '_build_policy'): policy = salt.utils.json.loads(conn._build_policy()) else: return {} # The format we get from build_policy isn't going to be what we get back # from AWS for the exact same policy. AWS converts single item list values # into strings, so let's do the same here. for key, policy_val in policy.items(): for statement in policy_val: if (isinstance(statement['Action'], list) and len(statement['Action']) == 1): statement['Action'] = statement['Action'][0] if (isinstance(statement['Principal']['Service'], list) and len(statement['Principal']['Service']) == 1): statement['Principal']['Service'] = statement['Principal']['Service'][0] # build_policy doesn't add a version field, which AWS is going to set to a # default value, when we get it back, so let's set it. policy['Version'] = '2008-10-17' return policy def get_account_id(region=None, key=None, keyid=None, profile=None): ''' Get a the AWS account id associated with the used credentials. CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_id ''' cache_key = 'boto_iam.account_id' if cache_key not in __context__: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_user() # The get_user call returns an user ARN: # arn:aws:iam::027050522557:user/salt-test arn = ret['get_user_response']['get_user_result']['user']['arn'] account_id = arn.split(':')[4] except boto.exception.BotoServerError: # If call failed, then let's try to get the ARN from the metadata timeout = boto.config.getfloat( 'Boto', 'metadata_service_timeout', 1.0 ) attempts = boto.config.getint( 'Boto', 'metadata_service_num_attempts', 1 ) identity = boto.utils.get_instance_identity( timeout=timeout, num_retries=attempts ) try: account_id = identity['document']['accountId'] except KeyError: log.error('Failed to get account id from instance_identity in' ' boto_iam.get_account_id.') __context__[cache_key] = account_id return __context__[cache_key] def get_all_roles(path_prefix=None, region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM role details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_roles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _roles = conn.list_roles(path_prefix=path_prefix) roles = _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) while marker: _roles = conn.list_roles(path_prefix=path_prefix, marker=marker) roles = roles + _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) return roles def get_all_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM user details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_users ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _users = conn.get_all_users(path_prefix=path_prefix) users = _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) while marker: _users = conn.get_all_users(path_prefix=path_prefix, marker=marker) users = users + _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) return users def get_all_user_policies(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all user policies. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_user_policies myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_all_user_policies(user_name, marker, max_items) if not info: return False _list = info.list_user_policies_response.list_user_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policies for user %s.', user_name) return False def get_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user_policy myuser mypolicyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user_policy(user_name, policy_name) log.debug('Info for IAM user %s policy %s: %s.', user_name, policy_name, info) if not info: return False info = info.get_user_policy_response.get_user_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policy %s for IAM user %s.', policy_name, user_name) return False def put_user_policy(user_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_user_policy myuser policyname policyrules ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_user_policy(user_name, policy_name, policy_json) if created: log.info('Created policy %s for IAM user %s.', policy_name, user_name) return True log.error('Could not create policy %s for IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy %s for IAM user %s.', policy_name, user_name) return False def delete_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user_policy myuser mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_user_policy( user_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_user_policy(user_name, policy_name) log.info('Successfully deleted policy %s for IAM user %s.', policy_name, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM user %s.', policy_name, user_name) return False def upload_server_cert(cert_name, cert_body, private_key, cert_chain=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Upload a certificate to Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.upload_server_cert mycert_name crt priv_key :param cert_name: The name for the server certificate. Do not include the path in this value. :param cert_body: The contents of the public key certificate in PEM-encoded format. :param private_key: The contents of the private key in PEM-encoded format. :param cert_chain: The contents of the certificate chain. This is typically a concatenation of the PEM-encoded public key certificates of the chain. :param path: The path for the server certificate. :param region: The name of the region to connect to. :param key: The key to be used in order to connect :param keyid: The keyid to be used in order to connect :param profile: The profile that contains a dict of region, key, keyid :return: True / False ''' exists = get_server_certificate(cert_name, region, key, keyid, profile) if exists: return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.upload_server_cert(cert_name, cert_body, private_key, cert_chain) log.info('Created certificate %s.', cert_name) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to failed to create certificate %s.', cert_name) return False def list_server_certificates(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Lists the server certificates stored in IAM that have the specified path prefix. .. versionadded:: ??? :param path_prefix: The path prefix for filtering the results. For example: /company/servercerts would get all server certificates for which the path starts with /company/servercerts . This parameter is optional. If it is not included, it defaults to a slash (/), listing all server certificates. This parameter allows (per its regex pattern) a string of characters consisting of either a forward slash (/) by itself or a string that must begin and end with forward slashes. In addition, it can contain any ASCII character from the ! (u0021) through the DEL character (u007F), including most punctuation characters, digits, and upper and lowercased letters. CLI Example: .. code-block:: bash salt myminion boto_iam.list_server_certificates path_prefix=/somepath/ ''' retries = 10 sleep = 6 conn = __utils__['boto3.get_connection']('iam', region=region, key=key, keyid=keyid, profile=profile) Items = [] while retries: try: log.debug('Garnering list of IAM Server Certificates') IsTruncated = True while IsTruncated: kwargs = {'PathPrefix': path_prefix} ret = conn.list_server_certificates(**kwargs) Items += ret.get('ServerCertificateMetadataList', []) IsTruncated = ret.get('IsTruncated') kwargs.update({'Marker': ret.get('Marker')}) return Items except botocore.exceptions.ParamValidationError as err: raise SaltInvocationError(str(err)) except botocore.exceptions.ClientError as err: if retries and jmespath.search('Error.Code', err.response) == 'Throttling': retries -= 1 log.debug('Throttled by AWS API, retrying in %s seconds...', sleep) time.sleep(sleep) continue log.error('Failed to list IAM Server Certificates: %s', err.message) return None def get_server_certificate(cert_name, region=None, key=None, keyid=None, profile=None): ''' Returns certificate information from Amazon .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_server_certificate mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_server_certificate(cert_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get certificate %s information.', cert_name) return False def delete_server_cert(cert_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a certificate from Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_server_cert mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_server_cert(cert_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete certificate %s.', cert_name) return False def export_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM user details. Produces results that can be used to create an sls file. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.export_users --out=txt | sed "s/local: //" > iam_users.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() users = get_all_users(path_prefix, region, key, keyid, profile) for user in users: name = user.user_name _policies = conn.get_all_user_policies(name, max_items=100) _policies = _policies.list_user_policies_response.list_user_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_user_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_user_policy_response.get_user_policy_result.policy_document )) policies[policy_name] = _policy user_sls = [] user_sls.append({"name": name}) user_sls.append({"policies": policies}) user_sls.append({"path": user.path}) results["manage user " + name] = {"boto_iam.user_present": user_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def export_roles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM role details. Produces results that can be used to create an sls file. CLI Example: salt-call boto_iam.export_roles --out=txt | sed "s/local: //" > iam_roles.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() roles = get_all_roles(path_prefix, region, key, keyid, profile) for role in roles: name = role.role_name _policies = conn.list_role_policies(name, max_items=100) _policies = _policies.list_role_policies_response.list_role_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_role_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_role_policy_response.get_role_policy_result.policy_document )) policies[policy_name] = _policy role_sls = [] role_sls.append({"name": name}) role_sls.append({"policies": policies}) role_sls.append({'policy_document': salt.utils.json.loads(_unquote(role.assume_role_policy_document))}) role_sls.append({"path": role.path}) results["manage role " + name] = {"boto_iam_role.present": role_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def _get_policy_arn(name, region=None, key=None, keyid=None, profile=None): if name.startswith('arn:aws:iam:'): return name account_id = get_account_id( region=region, key=key, keyid=keyid, profile=profile ) return 'arn:aws:iam::{0}:policy/{1}'.format(account_id, name) def policy_exists(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return True except boto.exception.BotoServerError: return False def get_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return ret.get('get_policy_response', {}).get('get_policy_result', {}) except boto.exception.BotoServerError: return None def create_policy(policy_name, policy_document, path=None, description=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in 'path', 'description': if locals()[arg] is not None: params[arg] = locals()[arg] if policy_exists(policy_name, region, key, keyid, profile): return True try: conn.create_policy(policy_name, policy_document, **params) log.info('Created IAM policy %s.', policy_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s.', policy_name) return False return True def delete_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_exists(policy_arn, region, key, keyid, profile): return True try: conn.delete_policy(policy_arn) log.info('Deleted %s policy.', policy_name) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete %s policy: %s.', policy_name, aws.get('message')) return False return True def list_policies(region=None, key=None, keyid=None, profile=None): ''' List policies. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policies ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: policies = [] for ret in __utils__['boto.paged_call'](conn.list_policies): policies.append(ret.get('list_policies_response', {}).get('list_policies_result', {}).get('policies')) return policies except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to list policy versions.' log.error(msg) return [] def policy_version_exists(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.get_policy_version(policy_arn, version_id) return True except boto.exception.BotoServerError: return False def get_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy_version(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile), version_id) retval = ret.get('get_policy_version_response', {}).get('get_policy_version_result', {}).get('policy_version', {}) retval['document'] = _unquote(retval.get('document')) return {'policy_version': retval} except boto.exception.BotoServerError: return None def create_policy_version(policy_name, policy_document, set_as_default=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy version. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy_version mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in ('set_as_default',): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.create_policy_version(policy_arn, policy_document, **params) vid = ret.get('create_policy_version_response', {}).get('create_policy_version_result', {}).get('policy_version', {}).get('version_id') log.info('Created IAM policy %s version %s.', policy_name, vid) return {'created': True, 'version_id': vid} except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s version %s.', policy_name, vid) return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Delete a policy version. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_version_exists(policy_arn, version_id, region, key, keyid, profile): return True try: conn.delete_policy_version(policy_arn, version_id) log.info('Deleted IAM policy %s version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete IAM policy %s version %s: %s', policy_name, version_id, aws.get('message')) return False return True def list_policy_versions(policy_name, region=None, key=None, keyid=None, profile=None): ''' List versions of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policy_versions mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.list_policy_versions(policy_arn) return ret.get('list_policy_versions_response', {}).get('list_policy_versions_result', {}).get('versions') except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list versions for IAM policy %s.', policy_name) return [] def set_default_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Set the default version of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.set_default_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.set_default_policy_version(policy_arn, version_id) log.info('Set %s policy to version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to set %s policy to version %s: %s', policy_name, version_id, aws.get('message')) return False return True def attach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_user_policy(policy_arn, user_name) log.info('Attached policy %s to IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach %s policy to IAM user %s.', policy_name, user_name) return False return True def detach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_user_policy(policy_arn, user_name) log.info('Detached %s policy from IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach %s policy from IAM user %s.', policy_name, user_name) return False return True def attach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_group_policy(policy_arn, group_name) log.info('Attached policy %s to IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM group %s.', policy_name, group_name) return False return True def detach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_group_policy(policy_arn, group_name) log.info('Detached policy %s from IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM group %s.', policy_name, group_name) return False return True def attach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_role_policy(policy_arn, role_name) log.info('Attached policy %s to IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM role %s.', policy_name, role_name) return False return True def detach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_role_policy(policy_arn, role_name) log.info('Detached policy %s from IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM role %s.', policy_name, role_name) return False return True def list_attached_user_policies(user_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given user. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'UserName': user_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedUserPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_user_policies_response', {}).get('list_attached_user_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM user %s.', user_name) return [] def list_attached_group_policies(group_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given group. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'GroupName': group_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedGroupPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_group_policies_response', {}).get('list_attached_group_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM group %s.', group_name) return [] def list_attached_role_policies(role_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'RoleName': role_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedRolePolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_role_policies_response', {}).get('list_attached_role_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM role %s.', role_name) return [] def create_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Create SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.create_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_saml_provider(saml_metadata_document, name) log.info('Successfully created %s SAML provider.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to create SAML provider %s.', name) return False def get_saml_provider_arn(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider_arn my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_saml_providers() for saml_provider in response.list_saml_providers_response.list_saml_providers_result.saml_provider_list: if saml_provider['arn'].endswith(':saml-provider/' + name): return saml_provider['arn'] return False except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to get ARN of SAML provider %s.', name) return False def delete_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Delete SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.delete_saml_provider my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return True conn.delete_saml_provider(saml_provider_arn) log.info('Successfully deleted SAML provider %s.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete SAML provider %s.', name) return False def list_saml_providers(region=None, key=None, keyid=None, profile=None): ''' List SAML providers. CLI Example: .. code-block:: bash salt myminion boto_iam.list_saml_providers ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: providers = [] info = conn.list_saml_providers() for arn in info['list_saml_providers_response']['list_saml_providers_result']['saml_provider_list']: providers.append(arn['arn'].rsplit('/', 1)[1]) return providers except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get list of SAML providers.') return False def get_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider document. CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider arn ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: provider = conn.get_saml_provider(name) return provider['get_saml_provider_response']['get_saml_provider_result']['saml_metadata_document'] except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get SAML provider document %s.', name) return False def update_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Update SAML provider. CLI Example: .. code-block:: bash salt myminion boto_iam.update_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return False if conn.update_saml_provider(name, saml_metadata_document): return True return False except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to update SAML provider %s.', name) return False
saltstack/salt
salt/modules/boto_iam.py
list_attached_role_policies
python
def list_attached_role_policies(role_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'RoleName': role_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedRolePolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_role_policies_response', {}).get('list_attached_role_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM role %s.', role_name) return []
List entities attached to the given role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iam.py#L2230-L2258
null
# -*- coding: utf-8 -*- ''' Connection module for Amazon IAM .. versionadded:: 2014.7.0 :configuration: This module accepts explicit iam 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 iam.keyid: GKTADJGHEIQSXMKKRBJ08H iam.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs iam.region: 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: boto ''' # keep lint from choking on _get_conn and _cache_id #pylint: disable=E0602 # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import salt libs from salt.ext import six import salt.utils.compat import salt.utils.json import salt.utils.odict as odict import salt.utils.versions from salt.exceptions import SaltInvocationError # Import third party libs # pylint: disable=unused-import from salt.ext.six.moves.urllib.parse import unquote as _unquote # pylint: disable=no-name-in-module try: import boto import boto.iam import boto3 import botocore logging.getLogger('boto').setLevel(logging.CRITICAL) logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=unused-import log = logging.getLogger(__name__) def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'iam', pack=__salt__) def instance_profile_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an instance profile exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: # Boto weirdly returns an exception here if an instance profile doesn't # exist. conn.get_instance_profile(name) return True except boto.exception.BotoServerError: return False def create_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Create an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.create_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if instance_profile_exists(name, region, key, keyid, profile): return True try: # This call returns an instance profile if successful and an exception # if not. It's annoying. conn.create_instance_profile(name) log.info('Created %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create %s instance profile.', name) return False return True def delete_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Delete an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not instance_profile_exists(name, region, key, keyid, profile): return True try: conn.delete_instance_profile(name) log.info('Deleted %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s instance profile.', name) return False return True def role_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an IAM role exists. CLI Example: .. code-block:: bash salt myminion boto_iam.role_exists myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_role(name) return True except boto.exception.BotoServerError: return False def describe_role(name, region=None, key=None, keyid=None, profile=None): ''' Get information for a role. CLI Example: .. code-block:: bash salt myminion boto_iam.describe_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_role(name) if not info: return False role = info.get_role_response.get_role_result.role role['assume_role_policy_document'] = salt.utils.json.loads(_unquote( role.assume_role_policy_document )) # If Sid wasn't defined by the user, boto will still return a Sid in # each policy. To properly check idempotently, let's remove the Sid # from the return if it's not actually set. for policy_key, policy in role['assume_role_policy_document'].items(): if policy_key == 'Statement': for val in policy: if 'Sid' in val and not val['Sid']: del val['Sid'] return role except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get %s information.', name) return False def create_user(user_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_user myuser ''' if not path: path = '/' if get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_user(user_name, path) log.info('Created IAM user : %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM user %s.', user_name) return False def get_all_access_keys(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all access keys from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_access_keys myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.get_all_access_keys(user_name, marker, max_items) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get access keys for IAM user %s.', user_name) return six.text_type(e) def create_access_key(user_name, region=None, key=None, keyid=None, profile=None): ''' Create access key id for a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.create_access_key(user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create access key.') return six.text_type(e) def delete_access_key(access_key_id, user_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete access key id from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_access_key(access_key_id, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete access key id %s.', access_key_id) return six.text_type(e) def delete_user(user_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user myuser ''' if not get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.delete_user(user_name) log.info('Deleted IAM user : %s .', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM user %s', user_name) return six.text_type(e) def get_user(user_name=None, region=None, key=None, keyid=None, profile=None): ''' Get user information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user(user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM user %s info.', user_name) return False def create_group(group_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_group group ''' if not path: path = '/' if get_group(group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_group(group_name, path) log.info('Created IAM group : %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM group %s.', group_name) return False def get_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group(group_name, max_items=1) if not info: return False return info['get_group_response']['get_group_result']['group'] except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_group_members(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: marker = None truncated = True users = [] while truncated: info = conn.get_group(group_name, marker=marker, max_items=1000) if not info: return False truncated = bool(info['get_group_response']['get_group_result']['is_truncated']) if truncated and 'marker' in info['get_group_response']['get_group_result']: marker = info['get_group_response']['get_group_result']['marker'] else: marker = None truncated = False users += info['get_group_response']['get_group_result']['users'] return users except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get members for IAM group %s.', group_name) return False def add_user_to_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Add user to group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.add_user_to_group myuser mygroup ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('Username : %s does not exist.', user_name) return False if user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.add_user_to_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add IAM user %s to group %s.', user_name, group_name) return False def user_exists_in_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Check if user exists in group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.user_exists_in_group myuser mygroup ''' # TODO this should probably use boto.iam.get_groups_for_user users = get_group_members( group_name=group_name, region=region, key=key, keyid=keyid, profile=profile ) if users: for _user in users: if user_name == _user['user_name']: log.debug('IAM user %s is already in IAM group %s.', user_name, group_name) return True return False def remove_user_from_group(group_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Remove user from group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.remove_user_from_group mygroup myuser ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist.', user_name) return False if not user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.remove_user_from_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove IAM user %s from group %s', user_name, group_name) return False def put_group_policy(group_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_group_policy mygroup policyname policyrules ''' group = get_group(group_name, region=region, key=key, keyid=keyid, profile=profile) if not group: log.error('Group %s does not exist', group_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_group_policy(group_name, policy_name, policy_json) if created: log.info('Created policy for IAM group %s.', group_name) return True log.error('Could not create policy for IAM group %s', group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy for IAM group %s', group_name) return False def delete_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group_policy mygroup mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_group_policy( group_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_group_policy(group_name, policy_name) log.info('Successfully deleted policy %s for IAM group %s.', policy_name, group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM group %s.', policy_name, group_name) return False def get_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group_policy mygroup policyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group_policy(group_name, policy_name) log.debug('info for group policy is : %s', info) if not info: return False info = info.get_group_policy_response.get_group_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_all_groups(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM group details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_groups ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _groups = conn.get_all_groups(path_prefix=path_prefix) groups = _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) while marker: _groups = conn.get_all_groups(path_prefix=path_prefix, marker=marker) groups = groups + _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) return groups def get_all_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.get_all_instance_profiles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) marker = False profiles = [] while marker is not None: marker = marker if marker else None p = conn.list_instance_profiles(path_prefix=path_prefix, marker=marker) res = p.list_instance_profiles_response.list_instance_profiles_result profiles += res.instance_profiles marker = getattr(res, 'marker', None) return profiles def list_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' List all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.list_instance_profiles ''' p = get_all_instance_profiles(path_prefix, region, key, keyid, profile) return [i['instance_profile_name'] for i in p] def get_all_group_policies(group_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a group. CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_group_policies mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False try: response = conn.get_all_group_policies(group_name) _list = response.list_group_policies_response.list_group_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def delete_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _group = get_group( group_name, region, key, keyid, profile ) if not _group: return True try: conn.delete_group(group_name) log.info('Successfully deleted IAM group %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM group %s.', group_name) return False def create_login_profile(user_name, password, region=None, key=None, keyid=None, profile=None): ''' Creates a login profile for the specified user, give the user the ability to access AWS services and the AWS Management Console. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_login_profile user_name password ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.create_login_profile(user_name, password) log.info('Created profile for IAM user %s.', user_name) return info except boto.exception.BotoServerError as e: log.debug(e) if 'Conflict' in e: log.info('Profile already exists for IAM user %s.', user_name) return 'Conflict' log.error('Failed to update profile for IAM user %s.', user_name) return False def delete_login_profile(user_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a login profile for the specified user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_login_profile user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.delete_login_profile(user_name) log.info('Deleted login profile for IAM user %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Login profile already deleted for IAM user %s.', user_name) return True log.error('Failed to delete login profile for IAM user %s.', user_name) return False def get_all_mfa_devices(user_name, region=None, key=None, keyid=None, profile=None): ''' Get all MFA devices associated with an IAM user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_mfa_devices user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: result = conn.get_all_mfa_devices(user_name) devices = result['list_mfa_devices_response']['list_mfa_devices_result']['mfa_devices'] return devices except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Could not find IAM user %s.', user_name) return [] log.error('Failed to get all MFA devices for IAM user %s.', user_name) return False def deactivate_mfa_device(user_name, serial, region=None, key=None, keyid=None, profile=None): ''' Deactivates the specified MFA device and removes it from association with the user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.deactivate_mfa_device user_name serial_num ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.deactivate_mfa_device(user_name, serial) log.info('Deactivated MFA device %s for IAM user %s.', serial, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('MFA device %s not associated with IAM user %s.', serial, user_name) return True log.error('Failed to deactivate MFA device %s for IAM user %s.', serial, user_name) return False def delete_virtual_mfa_device(serial, region=None, key=None, keyid=None, profile=None): ''' Deletes the specified virtual MFA device. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_virtual_mfa_device serial_num ''' conn = __utils__['boto3.get_connection_func']('iam')() try: conn.delete_virtual_mfa_device(SerialNumber=serial) log.info('Deleted virtual MFA device %s.', serial) return True except botocore.exceptions.ClientError as e: log.debug(e) if 'NoSuchEntity' in six.text_type(e): log.info('Virtual MFA device %s not found.', serial) return True log.error('Failed to delete virtual MFA device %s.', serial) return False def update_account_password_policy(allow_users_to_change_password=None, hard_expiry=None, max_password_age=None, minimum_password_length=None, password_reuse_prevention=None, require_lowercase_characters=None, require_numbers=None, require_symbols=None, require_uppercase_characters=None, region=None, key=None, keyid=None, profile=None): ''' Update the password policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_account_password_policy True ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.update_account_password_policy(allow_users_to_change_password, hard_expiry, max_password_age, minimum_password_length, password_reuse_prevention, require_lowercase_characters, require_numbers, require_symbols, require_uppercase_characters) log.info('The password policy has been updated.') return True except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy' log.error(msg) return False def get_account_policy(region=None, key=None, keyid=None, profile=None): ''' Get account policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_account_password_policy() return info.get_account_password_policy_response.get_account_password_policy_result.password_policy except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy.' log.error(msg) return False def create_role(name, policy_document=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Create an instance role. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if role_exists(name, region, key, keyid, profile): return True if not policy_document: policy_document = None try: conn.create_role(name, assume_role_policy_document=policy_document, path=path) log.info('Created IAM role %s.', name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to create IAM role %s.', name) return False def delete_role(name, region=None, key=None, keyid=None, profile=None): ''' Delete an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(name, region, key, keyid, profile): return True try: conn.delete_role(name) log.info('Deleted %s IAM role.', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s IAM role.', name) return False def profile_associated(role_name, profile_name, region, key, keyid, profile): ''' Check to see if an instance profile is associated with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.profile_associated myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # The IAM module of boto doesn't return objects. Instead you need to grab # values through its properties. Sigh. try: profiles = conn.list_instance_profiles_for_role(role_name) except boto.exception.BotoServerError as e: log.debug(e) return False profiles = profiles.list_instance_profiles_for_role_response profiles = profiles.list_instance_profiles_for_role_result profiles = profiles.instance_profiles for profile in profiles: if profile.instance_profile_name == profile_name: return True return False def associate_profile_to_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Associate an instance profile with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.associate_profile_to_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if associated: return True else: try: conn.add_role_to_instance_profile(profile_name, role_name) log.info('Added %s instance profile to IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add %s instance profile to IAM role %s', profile_name, role_name) return False def disassociate_profile_from_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Disassociate an instance profile from an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.disassociate_profile_from_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if not associated: return True else: try: conn.remove_role_from_instance_profile(profile_name, role_name) log.info('Removed %s instance profile from IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove %s instance profile from IAM role %s.', profile_name, role_name) return False def list_role_policies(role_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_role_policies myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_role_policies(role_name) _list = response.list_role_policies_response.list_role_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def get_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.get_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: _policy = conn.get_role_policy(role_name, policy_name) # I _hate_ you for not giving me an object boto. _policy = _policy.get_role_policy_response.policy_document # Policy is url encoded _policy = _unquote(_policy) _policy = salt.utils.json.loads(_policy, object_pairs_hook=odict.OrderedDict) return _policy except boto.exception.BotoServerError: return {} def create_role_policy(role_name, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Create or modify a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role_policy myirole mypolicy '{"MyPolicy": "Statement": [{"Action": ["sqs:*"], "Effect": "Allow", "Resource": ["arn:aws:sqs:*:*:*"], "Sid": "MyPolicySqs1"}]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) mode = 'create' if _policy: if _policy == policy: return True mode = 'modify' if isinstance(policy, six.string_types): policy = salt.utils.json.loads(policy, object_pairs_hook=odict.OrderedDict) try: _policy = salt.utils.json.dumps(policy) conn.put_role_policy(role_name, policy_name, _policy) if mode == 'create': msg = 'Successfully added policy %s to IAM role %s.' else: msg = 'Successfully modified policy %s for IAM role %s.' log.info(msg, policy_name, role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to %s policy %s for IAM role %s.', mode, policy_name, role_name) return False def delete_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) if not _policy: return True try: conn.delete_role_policy(role_name, policy_name) log.info('Successfully deleted policy %s for IAM role %s.', policy_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM role %s.', policy_name, role_name) return False def update_assume_role_policy(role_name, policy_document, region=None, key=None, keyid=None, profile=None): ''' Update an assume role policy for a role. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_assume_role_policy myrole '{"Statement":"..."}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(policy_document, six.string_types): policy_document = salt.utils.json.loads(policy_document, object_pairs_hook=odict.OrderedDict) try: _policy_document = salt.utils.json.dumps(policy_document) conn.update_assume_role_policy(role_name, _policy_document) log.info('Successfully updated assume role policy for IAM role %s.', role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to update assume role policy for IAM role %s.', role_name) return False def build_policy(region=None, key=None, keyid=None, profile=None): ''' Build a default assume role policy. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.build_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if hasattr(conn, 'build_policy'): policy = salt.utils.json.loads(conn.build_policy()) elif hasattr(conn, '_build_policy'): policy = salt.utils.json.loads(conn._build_policy()) else: return {} # The format we get from build_policy isn't going to be what we get back # from AWS for the exact same policy. AWS converts single item list values # into strings, so let's do the same here. for key, policy_val in policy.items(): for statement in policy_val: if (isinstance(statement['Action'], list) and len(statement['Action']) == 1): statement['Action'] = statement['Action'][0] if (isinstance(statement['Principal']['Service'], list) and len(statement['Principal']['Service']) == 1): statement['Principal']['Service'] = statement['Principal']['Service'][0] # build_policy doesn't add a version field, which AWS is going to set to a # default value, when we get it back, so let's set it. policy['Version'] = '2008-10-17' return policy def get_account_id(region=None, key=None, keyid=None, profile=None): ''' Get a the AWS account id associated with the used credentials. CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_id ''' cache_key = 'boto_iam.account_id' if cache_key not in __context__: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_user() # The get_user call returns an user ARN: # arn:aws:iam::027050522557:user/salt-test arn = ret['get_user_response']['get_user_result']['user']['arn'] account_id = arn.split(':')[4] except boto.exception.BotoServerError: # If call failed, then let's try to get the ARN from the metadata timeout = boto.config.getfloat( 'Boto', 'metadata_service_timeout', 1.0 ) attempts = boto.config.getint( 'Boto', 'metadata_service_num_attempts', 1 ) identity = boto.utils.get_instance_identity( timeout=timeout, num_retries=attempts ) try: account_id = identity['document']['accountId'] except KeyError: log.error('Failed to get account id from instance_identity in' ' boto_iam.get_account_id.') __context__[cache_key] = account_id return __context__[cache_key] def get_all_roles(path_prefix=None, region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM role details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_roles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _roles = conn.list_roles(path_prefix=path_prefix) roles = _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) while marker: _roles = conn.list_roles(path_prefix=path_prefix, marker=marker) roles = roles + _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) return roles def get_all_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM user details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_users ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _users = conn.get_all_users(path_prefix=path_prefix) users = _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) while marker: _users = conn.get_all_users(path_prefix=path_prefix, marker=marker) users = users + _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) return users def get_all_user_policies(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all user policies. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_user_policies myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_all_user_policies(user_name, marker, max_items) if not info: return False _list = info.list_user_policies_response.list_user_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policies for user %s.', user_name) return False def get_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user_policy myuser mypolicyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user_policy(user_name, policy_name) log.debug('Info for IAM user %s policy %s: %s.', user_name, policy_name, info) if not info: return False info = info.get_user_policy_response.get_user_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policy %s for IAM user %s.', policy_name, user_name) return False def put_user_policy(user_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_user_policy myuser policyname policyrules ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_user_policy(user_name, policy_name, policy_json) if created: log.info('Created policy %s for IAM user %s.', policy_name, user_name) return True log.error('Could not create policy %s for IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy %s for IAM user %s.', policy_name, user_name) return False def delete_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user_policy myuser mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_user_policy( user_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_user_policy(user_name, policy_name) log.info('Successfully deleted policy %s for IAM user %s.', policy_name, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM user %s.', policy_name, user_name) return False def upload_server_cert(cert_name, cert_body, private_key, cert_chain=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Upload a certificate to Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.upload_server_cert mycert_name crt priv_key :param cert_name: The name for the server certificate. Do not include the path in this value. :param cert_body: The contents of the public key certificate in PEM-encoded format. :param private_key: The contents of the private key in PEM-encoded format. :param cert_chain: The contents of the certificate chain. This is typically a concatenation of the PEM-encoded public key certificates of the chain. :param path: The path for the server certificate. :param region: The name of the region to connect to. :param key: The key to be used in order to connect :param keyid: The keyid to be used in order to connect :param profile: The profile that contains a dict of region, key, keyid :return: True / False ''' exists = get_server_certificate(cert_name, region, key, keyid, profile) if exists: return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.upload_server_cert(cert_name, cert_body, private_key, cert_chain) log.info('Created certificate %s.', cert_name) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to failed to create certificate %s.', cert_name) return False def list_server_certificates(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Lists the server certificates stored in IAM that have the specified path prefix. .. versionadded:: ??? :param path_prefix: The path prefix for filtering the results. For example: /company/servercerts would get all server certificates for which the path starts with /company/servercerts . This parameter is optional. If it is not included, it defaults to a slash (/), listing all server certificates. This parameter allows (per its regex pattern) a string of characters consisting of either a forward slash (/) by itself or a string that must begin and end with forward slashes. In addition, it can contain any ASCII character from the ! (u0021) through the DEL character (u007F), including most punctuation characters, digits, and upper and lowercased letters. CLI Example: .. code-block:: bash salt myminion boto_iam.list_server_certificates path_prefix=/somepath/ ''' retries = 10 sleep = 6 conn = __utils__['boto3.get_connection']('iam', region=region, key=key, keyid=keyid, profile=profile) Items = [] while retries: try: log.debug('Garnering list of IAM Server Certificates') IsTruncated = True while IsTruncated: kwargs = {'PathPrefix': path_prefix} ret = conn.list_server_certificates(**kwargs) Items += ret.get('ServerCertificateMetadataList', []) IsTruncated = ret.get('IsTruncated') kwargs.update({'Marker': ret.get('Marker')}) return Items except botocore.exceptions.ParamValidationError as err: raise SaltInvocationError(str(err)) except botocore.exceptions.ClientError as err: if retries and jmespath.search('Error.Code', err.response) == 'Throttling': retries -= 1 log.debug('Throttled by AWS API, retrying in %s seconds...', sleep) time.sleep(sleep) continue log.error('Failed to list IAM Server Certificates: %s', err.message) return None def get_server_certificate(cert_name, region=None, key=None, keyid=None, profile=None): ''' Returns certificate information from Amazon .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_server_certificate mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_server_certificate(cert_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get certificate %s information.', cert_name) return False def delete_server_cert(cert_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a certificate from Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_server_cert mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_server_cert(cert_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete certificate %s.', cert_name) return False def export_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM user details. Produces results that can be used to create an sls file. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.export_users --out=txt | sed "s/local: //" > iam_users.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() users = get_all_users(path_prefix, region, key, keyid, profile) for user in users: name = user.user_name _policies = conn.get_all_user_policies(name, max_items=100) _policies = _policies.list_user_policies_response.list_user_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_user_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_user_policy_response.get_user_policy_result.policy_document )) policies[policy_name] = _policy user_sls = [] user_sls.append({"name": name}) user_sls.append({"policies": policies}) user_sls.append({"path": user.path}) results["manage user " + name] = {"boto_iam.user_present": user_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def export_roles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM role details. Produces results that can be used to create an sls file. CLI Example: salt-call boto_iam.export_roles --out=txt | sed "s/local: //" > iam_roles.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() roles = get_all_roles(path_prefix, region, key, keyid, profile) for role in roles: name = role.role_name _policies = conn.list_role_policies(name, max_items=100) _policies = _policies.list_role_policies_response.list_role_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_role_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_role_policy_response.get_role_policy_result.policy_document )) policies[policy_name] = _policy role_sls = [] role_sls.append({"name": name}) role_sls.append({"policies": policies}) role_sls.append({'policy_document': salt.utils.json.loads(_unquote(role.assume_role_policy_document))}) role_sls.append({"path": role.path}) results["manage role " + name] = {"boto_iam_role.present": role_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def _get_policy_arn(name, region=None, key=None, keyid=None, profile=None): if name.startswith('arn:aws:iam:'): return name account_id = get_account_id( region=region, key=key, keyid=keyid, profile=profile ) return 'arn:aws:iam::{0}:policy/{1}'.format(account_id, name) def policy_exists(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return True except boto.exception.BotoServerError: return False def get_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return ret.get('get_policy_response', {}).get('get_policy_result', {}) except boto.exception.BotoServerError: return None def create_policy(policy_name, policy_document, path=None, description=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in 'path', 'description': if locals()[arg] is not None: params[arg] = locals()[arg] if policy_exists(policy_name, region, key, keyid, profile): return True try: conn.create_policy(policy_name, policy_document, **params) log.info('Created IAM policy %s.', policy_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s.', policy_name) return False return True def delete_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_exists(policy_arn, region, key, keyid, profile): return True try: conn.delete_policy(policy_arn) log.info('Deleted %s policy.', policy_name) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete %s policy: %s.', policy_name, aws.get('message')) return False return True def list_policies(region=None, key=None, keyid=None, profile=None): ''' List policies. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policies ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: policies = [] for ret in __utils__['boto.paged_call'](conn.list_policies): policies.append(ret.get('list_policies_response', {}).get('list_policies_result', {}).get('policies')) return policies except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to list policy versions.' log.error(msg) return [] def policy_version_exists(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.get_policy_version(policy_arn, version_id) return True except boto.exception.BotoServerError: return False def get_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy_version(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile), version_id) retval = ret.get('get_policy_version_response', {}).get('get_policy_version_result', {}).get('policy_version', {}) retval['document'] = _unquote(retval.get('document')) return {'policy_version': retval} except boto.exception.BotoServerError: return None def create_policy_version(policy_name, policy_document, set_as_default=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy version. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy_version mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in ('set_as_default',): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.create_policy_version(policy_arn, policy_document, **params) vid = ret.get('create_policy_version_response', {}).get('create_policy_version_result', {}).get('policy_version', {}).get('version_id') log.info('Created IAM policy %s version %s.', policy_name, vid) return {'created': True, 'version_id': vid} except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s version %s.', policy_name, vid) return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Delete a policy version. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_version_exists(policy_arn, version_id, region, key, keyid, profile): return True try: conn.delete_policy_version(policy_arn, version_id) log.info('Deleted IAM policy %s version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete IAM policy %s version %s: %s', policy_name, version_id, aws.get('message')) return False return True def list_policy_versions(policy_name, region=None, key=None, keyid=None, profile=None): ''' List versions of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policy_versions mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.list_policy_versions(policy_arn) return ret.get('list_policy_versions_response', {}).get('list_policy_versions_result', {}).get('versions') except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list versions for IAM policy %s.', policy_name) return [] def set_default_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Set the default version of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.set_default_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.set_default_policy_version(policy_arn, version_id) log.info('Set %s policy to version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to set %s policy to version %s: %s', policy_name, version_id, aws.get('message')) return False return True def attach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_user_policy(policy_arn, user_name) log.info('Attached policy %s to IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach %s policy to IAM user %s.', policy_name, user_name) return False return True def detach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_user_policy(policy_arn, user_name) log.info('Detached %s policy from IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach %s policy from IAM user %s.', policy_name, user_name) return False return True def attach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_group_policy(policy_arn, group_name) log.info('Attached policy %s to IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM group %s.', policy_name, group_name) return False return True def detach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_group_policy(policy_arn, group_name) log.info('Detached policy %s from IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM group %s.', policy_name, group_name) return False return True def attach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_role_policy(policy_arn, role_name) log.info('Attached policy %s to IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM role %s.', policy_name, role_name) return False return True def detach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_role_policy(policy_arn, role_name) log.info('Detached policy %s from IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM role %s.', policy_name, role_name) return False return True def list_entities_for_policy(policy_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities that a policy is attached to. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 params = {} for arg in ('path_prefix', 'entity_filter'): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) while retries: try: allret = { 'policy_groups': [], 'policy_users': [], 'policy_roles': [], } for ret in __utils__['boto.paged_call'](conn.list_entities_for_policy, policy_arn=policy_arn, **params): for k, v in six.iteritems(allret): v.extend(ret.get('list_entities_for_policy_response', {}).get('list_entities_for_policy_result', {}).get(k)) return allret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('Failed to list entities for IAM policy %s: %s', policy_name, e.message) return {} return {} def list_attached_user_policies(user_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given user. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'UserName': user_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedUserPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_user_policies_response', {}).get('list_attached_user_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM user %s.', user_name) return [] def list_attached_group_policies(group_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given group. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'GroupName': group_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedGroupPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_group_policies_response', {}).get('list_attached_group_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM group %s.', group_name) return [] def create_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Create SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.create_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_saml_provider(saml_metadata_document, name) log.info('Successfully created %s SAML provider.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to create SAML provider %s.', name) return False def get_saml_provider_arn(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider_arn my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_saml_providers() for saml_provider in response.list_saml_providers_response.list_saml_providers_result.saml_provider_list: if saml_provider['arn'].endswith(':saml-provider/' + name): return saml_provider['arn'] return False except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to get ARN of SAML provider %s.', name) return False def delete_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Delete SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.delete_saml_provider my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return True conn.delete_saml_provider(saml_provider_arn) log.info('Successfully deleted SAML provider %s.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete SAML provider %s.', name) return False def list_saml_providers(region=None, key=None, keyid=None, profile=None): ''' List SAML providers. CLI Example: .. code-block:: bash salt myminion boto_iam.list_saml_providers ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: providers = [] info = conn.list_saml_providers() for arn in info['list_saml_providers_response']['list_saml_providers_result']['saml_provider_list']: providers.append(arn['arn'].rsplit('/', 1)[1]) return providers except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get list of SAML providers.') return False def get_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider document. CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider arn ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: provider = conn.get_saml_provider(name) return provider['get_saml_provider_response']['get_saml_provider_result']['saml_metadata_document'] except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get SAML provider document %s.', name) return False def update_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Update SAML provider. CLI Example: .. code-block:: bash salt myminion boto_iam.update_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return False if conn.update_saml_provider(name, saml_metadata_document): return True return False except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to update SAML provider %s.', name) return False
saltstack/salt
salt/modules/boto_iam.py
create_saml_provider
python
def create_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Create SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.create_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_saml_provider(saml_metadata_document, name) log.info('Successfully created %s SAML provider.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to create SAML provider %s.', name) return False
Create SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.create_saml_provider my_saml_provider_name saml_metadata_document
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iam.py#L2261-L2280
null
# -*- coding: utf-8 -*- ''' Connection module for Amazon IAM .. versionadded:: 2014.7.0 :configuration: This module accepts explicit iam 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 iam.keyid: GKTADJGHEIQSXMKKRBJ08H iam.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs iam.region: 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: boto ''' # keep lint from choking on _get_conn and _cache_id #pylint: disable=E0602 # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import salt libs from salt.ext import six import salt.utils.compat import salt.utils.json import salt.utils.odict as odict import salt.utils.versions from salt.exceptions import SaltInvocationError # Import third party libs # pylint: disable=unused-import from salt.ext.six.moves.urllib.parse import unquote as _unquote # pylint: disable=no-name-in-module try: import boto import boto.iam import boto3 import botocore logging.getLogger('boto').setLevel(logging.CRITICAL) logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=unused-import log = logging.getLogger(__name__) def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'iam', pack=__salt__) def instance_profile_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an instance profile exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: # Boto weirdly returns an exception here if an instance profile doesn't # exist. conn.get_instance_profile(name) return True except boto.exception.BotoServerError: return False def create_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Create an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.create_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if instance_profile_exists(name, region, key, keyid, profile): return True try: # This call returns an instance profile if successful and an exception # if not. It's annoying. conn.create_instance_profile(name) log.info('Created %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create %s instance profile.', name) return False return True def delete_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Delete an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not instance_profile_exists(name, region, key, keyid, profile): return True try: conn.delete_instance_profile(name) log.info('Deleted %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s instance profile.', name) return False return True def role_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an IAM role exists. CLI Example: .. code-block:: bash salt myminion boto_iam.role_exists myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_role(name) return True except boto.exception.BotoServerError: return False def describe_role(name, region=None, key=None, keyid=None, profile=None): ''' Get information for a role. CLI Example: .. code-block:: bash salt myminion boto_iam.describe_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_role(name) if not info: return False role = info.get_role_response.get_role_result.role role['assume_role_policy_document'] = salt.utils.json.loads(_unquote( role.assume_role_policy_document )) # If Sid wasn't defined by the user, boto will still return a Sid in # each policy. To properly check idempotently, let's remove the Sid # from the return if it's not actually set. for policy_key, policy in role['assume_role_policy_document'].items(): if policy_key == 'Statement': for val in policy: if 'Sid' in val and not val['Sid']: del val['Sid'] return role except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get %s information.', name) return False def create_user(user_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_user myuser ''' if not path: path = '/' if get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_user(user_name, path) log.info('Created IAM user : %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM user %s.', user_name) return False def get_all_access_keys(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all access keys from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_access_keys myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.get_all_access_keys(user_name, marker, max_items) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get access keys for IAM user %s.', user_name) return six.text_type(e) def create_access_key(user_name, region=None, key=None, keyid=None, profile=None): ''' Create access key id for a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.create_access_key(user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create access key.') return six.text_type(e) def delete_access_key(access_key_id, user_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete access key id from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_access_key(access_key_id, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete access key id %s.', access_key_id) return six.text_type(e) def delete_user(user_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user myuser ''' if not get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.delete_user(user_name) log.info('Deleted IAM user : %s .', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM user %s', user_name) return six.text_type(e) def get_user(user_name=None, region=None, key=None, keyid=None, profile=None): ''' Get user information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user(user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM user %s info.', user_name) return False def create_group(group_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_group group ''' if not path: path = '/' if get_group(group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_group(group_name, path) log.info('Created IAM group : %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM group %s.', group_name) return False def get_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group(group_name, max_items=1) if not info: return False return info['get_group_response']['get_group_result']['group'] except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_group_members(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: marker = None truncated = True users = [] while truncated: info = conn.get_group(group_name, marker=marker, max_items=1000) if not info: return False truncated = bool(info['get_group_response']['get_group_result']['is_truncated']) if truncated and 'marker' in info['get_group_response']['get_group_result']: marker = info['get_group_response']['get_group_result']['marker'] else: marker = None truncated = False users += info['get_group_response']['get_group_result']['users'] return users except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get members for IAM group %s.', group_name) return False def add_user_to_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Add user to group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.add_user_to_group myuser mygroup ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('Username : %s does not exist.', user_name) return False if user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.add_user_to_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add IAM user %s to group %s.', user_name, group_name) return False def user_exists_in_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Check if user exists in group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.user_exists_in_group myuser mygroup ''' # TODO this should probably use boto.iam.get_groups_for_user users = get_group_members( group_name=group_name, region=region, key=key, keyid=keyid, profile=profile ) if users: for _user in users: if user_name == _user['user_name']: log.debug('IAM user %s is already in IAM group %s.', user_name, group_name) return True return False def remove_user_from_group(group_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Remove user from group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.remove_user_from_group mygroup myuser ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist.', user_name) return False if not user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.remove_user_from_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove IAM user %s from group %s', user_name, group_name) return False def put_group_policy(group_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_group_policy mygroup policyname policyrules ''' group = get_group(group_name, region=region, key=key, keyid=keyid, profile=profile) if not group: log.error('Group %s does not exist', group_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_group_policy(group_name, policy_name, policy_json) if created: log.info('Created policy for IAM group %s.', group_name) return True log.error('Could not create policy for IAM group %s', group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy for IAM group %s', group_name) return False def delete_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group_policy mygroup mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_group_policy( group_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_group_policy(group_name, policy_name) log.info('Successfully deleted policy %s for IAM group %s.', policy_name, group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM group %s.', policy_name, group_name) return False def get_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group_policy mygroup policyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group_policy(group_name, policy_name) log.debug('info for group policy is : %s', info) if not info: return False info = info.get_group_policy_response.get_group_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_all_groups(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM group details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_groups ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _groups = conn.get_all_groups(path_prefix=path_prefix) groups = _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) while marker: _groups = conn.get_all_groups(path_prefix=path_prefix, marker=marker) groups = groups + _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) return groups def get_all_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.get_all_instance_profiles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) marker = False profiles = [] while marker is not None: marker = marker if marker else None p = conn.list_instance_profiles(path_prefix=path_prefix, marker=marker) res = p.list_instance_profiles_response.list_instance_profiles_result profiles += res.instance_profiles marker = getattr(res, 'marker', None) return profiles def list_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' List all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.list_instance_profiles ''' p = get_all_instance_profiles(path_prefix, region, key, keyid, profile) return [i['instance_profile_name'] for i in p] def get_all_group_policies(group_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a group. CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_group_policies mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False try: response = conn.get_all_group_policies(group_name) _list = response.list_group_policies_response.list_group_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def delete_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _group = get_group( group_name, region, key, keyid, profile ) if not _group: return True try: conn.delete_group(group_name) log.info('Successfully deleted IAM group %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM group %s.', group_name) return False def create_login_profile(user_name, password, region=None, key=None, keyid=None, profile=None): ''' Creates a login profile for the specified user, give the user the ability to access AWS services and the AWS Management Console. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_login_profile user_name password ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.create_login_profile(user_name, password) log.info('Created profile for IAM user %s.', user_name) return info except boto.exception.BotoServerError as e: log.debug(e) if 'Conflict' in e: log.info('Profile already exists for IAM user %s.', user_name) return 'Conflict' log.error('Failed to update profile for IAM user %s.', user_name) return False def delete_login_profile(user_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a login profile for the specified user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_login_profile user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.delete_login_profile(user_name) log.info('Deleted login profile for IAM user %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Login profile already deleted for IAM user %s.', user_name) return True log.error('Failed to delete login profile for IAM user %s.', user_name) return False def get_all_mfa_devices(user_name, region=None, key=None, keyid=None, profile=None): ''' Get all MFA devices associated with an IAM user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_mfa_devices user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: result = conn.get_all_mfa_devices(user_name) devices = result['list_mfa_devices_response']['list_mfa_devices_result']['mfa_devices'] return devices except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Could not find IAM user %s.', user_name) return [] log.error('Failed to get all MFA devices for IAM user %s.', user_name) return False def deactivate_mfa_device(user_name, serial, region=None, key=None, keyid=None, profile=None): ''' Deactivates the specified MFA device and removes it from association with the user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.deactivate_mfa_device user_name serial_num ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.deactivate_mfa_device(user_name, serial) log.info('Deactivated MFA device %s for IAM user %s.', serial, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('MFA device %s not associated with IAM user %s.', serial, user_name) return True log.error('Failed to deactivate MFA device %s for IAM user %s.', serial, user_name) return False def delete_virtual_mfa_device(serial, region=None, key=None, keyid=None, profile=None): ''' Deletes the specified virtual MFA device. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_virtual_mfa_device serial_num ''' conn = __utils__['boto3.get_connection_func']('iam')() try: conn.delete_virtual_mfa_device(SerialNumber=serial) log.info('Deleted virtual MFA device %s.', serial) return True except botocore.exceptions.ClientError as e: log.debug(e) if 'NoSuchEntity' in six.text_type(e): log.info('Virtual MFA device %s not found.', serial) return True log.error('Failed to delete virtual MFA device %s.', serial) return False def update_account_password_policy(allow_users_to_change_password=None, hard_expiry=None, max_password_age=None, minimum_password_length=None, password_reuse_prevention=None, require_lowercase_characters=None, require_numbers=None, require_symbols=None, require_uppercase_characters=None, region=None, key=None, keyid=None, profile=None): ''' Update the password policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_account_password_policy True ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.update_account_password_policy(allow_users_to_change_password, hard_expiry, max_password_age, minimum_password_length, password_reuse_prevention, require_lowercase_characters, require_numbers, require_symbols, require_uppercase_characters) log.info('The password policy has been updated.') return True except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy' log.error(msg) return False def get_account_policy(region=None, key=None, keyid=None, profile=None): ''' Get account policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_account_password_policy() return info.get_account_password_policy_response.get_account_password_policy_result.password_policy except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy.' log.error(msg) return False def create_role(name, policy_document=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Create an instance role. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if role_exists(name, region, key, keyid, profile): return True if not policy_document: policy_document = None try: conn.create_role(name, assume_role_policy_document=policy_document, path=path) log.info('Created IAM role %s.', name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to create IAM role %s.', name) return False def delete_role(name, region=None, key=None, keyid=None, profile=None): ''' Delete an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(name, region, key, keyid, profile): return True try: conn.delete_role(name) log.info('Deleted %s IAM role.', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s IAM role.', name) return False def profile_associated(role_name, profile_name, region, key, keyid, profile): ''' Check to see if an instance profile is associated with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.profile_associated myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # The IAM module of boto doesn't return objects. Instead you need to grab # values through its properties. Sigh. try: profiles = conn.list_instance_profiles_for_role(role_name) except boto.exception.BotoServerError as e: log.debug(e) return False profiles = profiles.list_instance_profiles_for_role_response profiles = profiles.list_instance_profiles_for_role_result profiles = profiles.instance_profiles for profile in profiles: if profile.instance_profile_name == profile_name: return True return False def associate_profile_to_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Associate an instance profile with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.associate_profile_to_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if associated: return True else: try: conn.add_role_to_instance_profile(profile_name, role_name) log.info('Added %s instance profile to IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add %s instance profile to IAM role %s', profile_name, role_name) return False def disassociate_profile_from_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Disassociate an instance profile from an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.disassociate_profile_from_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if not associated: return True else: try: conn.remove_role_from_instance_profile(profile_name, role_name) log.info('Removed %s instance profile from IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove %s instance profile from IAM role %s.', profile_name, role_name) return False def list_role_policies(role_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_role_policies myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_role_policies(role_name) _list = response.list_role_policies_response.list_role_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def get_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.get_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: _policy = conn.get_role_policy(role_name, policy_name) # I _hate_ you for not giving me an object boto. _policy = _policy.get_role_policy_response.policy_document # Policy is url encoded _policy = _unquote(_policy) _policy = salt.utils.json.loads(_policy, object_pairs_hook=odict.OrderedDict) return _policy except boto.exception.BotoServerError: return {} def create_role_policy(role_name, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Create or modify a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role_policy myirole mypolicy '{"MyPolicy": "Statement": [{"Action": ["sqs:*"], "Effect": "Allow", "Resource": ["arn:aws:sqs:*:*:*"], "Sid": "MyPolicySqs1"}]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) mode = 'create' if _policy: if _policy == policy: return True mode = 'modify' if isinstance(policy, six.string_types): policy = salt.utils.json.loads(policy, object_pairs_hook=odict.OrderedDict) try: _policy = salt.utils.json.dumps(policy) conn.put_role_policy(role_name, policy_name, _policy) if mode == 'create': msg = 'Successfully added policy %s to IAM role %s.' else: msg = 'Successfully modified policy %s for IAM role %s.' log.info(msg, policy_name, role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to %s policy %s for IAM role %s.', mode, policy_name, role_name) return False def delete_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) if not _policy: return True try: conn.delete_role_policy(role_name, policy_name) log.info('Successfully deleted policy %s for IAM role %s.', policy_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM role %s.', policy_name, role_name) return False def update_assume_role_policy(role_name, policy_document, region=None, key=None, keyid=None, profile=None): ''' Update an assume role policy for a role. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_assume_role_policy myrole '{"Statement":"..."}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(policy_document, six.string_types): policy_document = salt.utils.json.loads(policy_document, object_pairs_hook=odict.OrderedDict) try: _policy_document = salt.utils.json.dumps(policy_document) conn.update_assume_role_policy(role_name, _policy_document) log.info('Successfully updated assume role policy for IAM role %s.', role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to update assume role policy for IAM role %s.', role_name) return False def build_policy(region=None, key=None, keyid=None, profile=None): ''' Build a default assume role policy. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.build_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if hasattr(conn, 'build_policy'): policy = salt.utils.json.loads(conn.build_policy()) elif hasattr(conn, '_build_policy'): policy = salt.utils.json.loads(conn._build_policy()) else: return {} # The format we get from build_policy isn't going to be what we get back # from AWS for the exact same policy. AWS converts single item list values # into strings, so let's do the same here. for key, policy_val in policy.items(): for statement in policy_val: if (isinstance(statement['Action'], list) and len(statement['Action']) == 1): statement['Action'] = statement['Action'][0] if (isinstance(statement['Principal']['Service'], list) and len(statement['Principal']['Service']) == 1): statement['Principal']['Service'] = statement['Principal']['Service'][0] # build_policy doesn't add a version field, which AWS is going to set to a # default value, when we get it back, so let's set it. policy['Version'] = '2008-10-17' return policy def get_account_id(region=None, key=None, keyid=None, profile=None): ''' Get a the AWS account id associated with the used credentials. CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_id ''' cache_key = 'boto_iam.account_id' if cache_key not in __context__: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_user() # The get_user call returns an user ARN: # arn:aws:iam::027050522557:user/salt-test arn = ret['get_user_response']['get_user_result']['user']['arn'] account_id = arn.split(':')[4] except boto.exception.BotoServerError: # If call failed, then let's try to get the ARN from the metadata timeout = boto.config.getfloat( 'Boto', 'metadata_service_timeout', 1.0 ) attempts = boto.config.getint( 'Boto', 'metadata_service_num_attempts', 1 ) identity = boto.utils.get_instance_identity( timeout=timeout, num_retries=attempts ) try: account_id = identity['document']['accountId'] except KeyError: log.error('Failed to get account id from instance_identity in' ' boto_iam.get_account_id.') __context__[cache_key] = account_id return __context__[cache_key] def get_all_roles(path_prefix=None, region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM role details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_roles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _roles = conn.list_roles(path_prefix=path_prefix) roles = _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) while marker: _roles = conn.list_roles(path_prefix=path_prefix, marker=marker) roles = roles + _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) return roles def get_all_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM user details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_users ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _users = conn.get_all_users(path_prefix=path_prefix) users = _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) while marker: _users = conn.get_all_users(path_prefix=path_prefix, marker=marker) users = users + _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) return users def get_all_user_policies(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all user policies. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_user_policies myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_all_user_policies(user_name, marker, max_items) if not info: return False _list = info.list_user_policies_response.list_user_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policies for user %s.', user_name) return False def get_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user_policy myuser mypolicyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user_policy(user_name, policy_name) log.debug('Info for IAM user %s policy %s: %s.', user_name, policy_name, info) if not info: return False info = info.get_user_policy_response.get_user_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policy %s for IAM user %s.', policy_name, user_name) return False def put_user_policy(user_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_user_policy myuser policyname policyrules ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_user_policy(user_name, policy_name, policy_json) if created: log.info('Created policy %s for IAM user %s.', policy_name, user_name) return True log.error('Could not create policy %s for IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy %s for IAM user %s.', policy_name, user_name) return False def delete_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user_policy myuser mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_user_policy( user_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_user_policy(user_name, policy_name) log.info('Successfully deleted policy %s for IAM user %s.', policy_name, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM user %s.', policy_name, user_name) return False def upload_server_cert(cert_name, cert_body, private_key, cert_chain=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Upload a certificate to Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.upload_server_cert mycert_name crt priv_key :param cert_name: The name for the server certificate. Do not include the path in this value. :param cert_body: The contents of the public key certificate in PEM-encoded format. :param private_key: The contents of the private key in PEM-encoded format. :param cert_chain: The contents of the certificate chain. This is typically a concatenation of the PEM-encoded public key certificates of the chain. :param path: The path for the server certificate. :param region: The name of the region to connect to. :param key: The key to be used in order to connect :param keyid: The keyid to be used in order to connect :param profile: The profile that contains a dict of region, key, keyid :return: True / False ''' exists = get_server_certificate(cert_name, region, key, keyid, profile) if exists: return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.upload_server_cert(cert_name, cert_body, private_key, cert_chain) log.info('Created certificate %s.', cert_name) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to failed to create certificate %s.', cert_name) return False def list_server_certificates(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Lists the server certificates stored in IAM that have the specified path prefix. .. versionadded:: ??? :param path_prefix: The path prefix for filtering the results. For example: /company/servercerts would get all server certificates for which the path starts with /company/servercerts . This parameter is optional. If it is not included, it defaults to a slash (/), listing all server certificates. This parameter allows (per its regex pattern) a string of characters consisting of either a forward slash (/) by itself or a string that must begin and end with forward slashes. In addition, it can contain any ASCII character from the ! (u0021) through the DEL character (u007F), including most punctuation characters, digits, and upper and lowercased letters. CLI Example: .. code-block:: bash salt myminion boto_iam.list_server_certificates path_prefix=/somepath/ ''' retries = 10 sleep = 6 conn = __utils__['boto3.get_connection']('iam', region=region, key=key, keyid=keyid, profile=profile) Items = [] while retries: try: log.debug('Garnering list of IAM Server Certificates') IsTruncated = True while IsTruncated: kwargs = {'PathPrefix': path_prefix} ret = conn.list_server_certificates(**kwargs) Items += ret.get('ServerCertificateMetadataList', []) IsTruncated = ret.get('IsTruncated') kwargs.update({'Marker': ret.get('Marker')}) return Items except botocore.exceptions.ParamValidationError as err: raise SaltInvocationError(str(err)) except botocore.exceptions.ClientError as err: if retries and jmespath.search('Error.Code', err.response) == 'Throttling': retries -= 1 log.debug('Throttled by AWS API, retrying in %s seconds...', sleep) time.sleep(sleep) continue log.error('Failed to list IAM Server Certificates: %s', err.message) return None def get_server_certificate(cert_name, region=None, key=None, keyid=None, profile=None): ''' Returns certificate information from Amazon .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_server_certificate mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_server_certificate(cert_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get certificate %s information.', cert_name) return False def delete_server_cert(cert_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a certificate from Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_server_cert mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_server_cert(cert_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete certificate %s.', cert_name) return False def export_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM user details. Produces results that can be used to create an sls file. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.export_users --out=txt | sed "s/local: //" > iam_users.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() users = get_all_users(path_prefix, region, key, keyid, profile) for user in users: name = user.user_name _policies = conn.get_all_user_policies(name, max_items=100) _policies = _policies.list_user_policies_response.list_user_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_user_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_user_policy_response.get_user_policy_result.policy_document )) policies[policy_name] = _policy user_sls = [] user_sls.append({"name": name}) user_sls.append({"policies": policies}) user_sls.append({"path": user.path}) results["manage user " + name] = {"boto_iam.user_present": user_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def export_roles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM role details. Produces results that can be used to create an sls file. CLI Example: salt-call boto_iam.export_roles --out=txt | sed "s/local: //" > iam_roles.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() roles = get_all_roles(path_prefix, region, key, keyid, profile) for role in roles: name = role.role_name _policies = conn.list_role_policies(name, max_items=100) _policies = _policies.list_role_policies_response.list_role_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_role_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_role_policy_response.get_role_policy_result.policy_document )) policies[policy_name] = _policy role_sls = [] role_sls.append({"name": name}) role_sls.append({"policies": policies}) role_sls.append({'policy_document': salt.utils.json.loads(_unquote(role.assume_role_policy_document))}) role_sls.append({"path": role.path}) results["manage role " + name] = {"boto_iam_role.present": role_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def _get_policy_arn(name, region=None, key=None, keyid=None, profile=None): if name.startswith('arn:aws:iam:'): return name account_id = get_account_id( region=region, key=key, keyid=keyid, profile=profile ) return 'arn:aws:iam::{0}:policy/{1}'.format(account_id, name) def policy_exists(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return True except boto.exception.BotoServerError: return False def get_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return ret.get('get_policy_response', {}).get('get_policy_result', {}) except boto.exception.BotoServerError: return None def create_policy(policy_name, policy_document, path=None, description=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in 'path', 'description': if locals()[arg] is not None: params[arg] = locals()[arg] if policy_exists(policy_name, region, key, keyid, profile): return True try: conn.create_policy(policy_name, policy_document, **params) log.info('Created IAM policy %s.', policy_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s.', policy_name) return False return True def delete_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_exists(policy_arn, region, key, keyid, profile): return True try: conn.delete_policy(policy_arn) log.info('Deleted %s policy.', policy_name) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete %s policy: %s.', policy_name, aws.get('message')) return False return True def list_policies(region=None, key=None, keyid=None, profile=None): ''' List policies. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policies ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: policies = [] for ret in __utils__['boto.paged_call'](conn.list_policies): policies.append(ret.get('list_policies_response', {}).get('list_policies_result', {}).get('policies')) return policies except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to list policy versions.' log.error(msg) return [] def policy_version_exists(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.get_policy_version(policy_arn, version_id) return True except boto.exception.BotoServerError: return False def get_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy_version(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile), version_id) retval = ret.get('get_policy_version_response', {}).get('get_policy_version_result', {}).get('policy_version', {}) retval['document'] = _unquote(retval.get('document')) return {'policy_version': retval} except boto.exception.BotoServerError: return None def create_policy_version(policy_name, policy_document, set_as_default=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy version. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy_version mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in ('set_as_default',): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.create_policy_version(policy_arn, policy_document, **params) vid = ret.get('create_policy_version_response', {}).get('create_policy_version_result', {}).get('policy_version', {}).get('version_id') log.info('Created IAM policy %s version %s.', policy_name, vid) return {'created': True, 'version_id': vid} except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s version %s.', policy_name, vid) return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Delete a policy version. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_version_exists(policy_arn, version_id, region, key, keyid, profile): return True try: conn.delete_policy_version(policy_arn, version_id) log.info('Deleted IAM policy %s version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete IAM policy %s version %s: %s', policy_name, version_id, aws.get('message')) return False return True def list_policy_versions(policy_name, region=None, key=None, keyid=None, profile=None): ''' List versions of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policy_versions mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.list_policy_versions(policy_arn) return ret.get('list_policy_versions_response', {}).get('list_policy_versions_result', {}).get('versions') except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list versions for IAM policy %s.', policy_name) return [] def set_default_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Set the default version of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.set_default_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.set_default_policy_version(policy_arn, version_id) log.info('Set %s policy to version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to set %s policy to version %s: %s', policy_name, version_id, aws.get('message')) return False return True def attach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_user_policy(policy_arn, user_name) log.info('Attached policy %s to IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach %s policy to IAM user %s.', policy_name, user_name) return False return True def detach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_user_policy(policy_arn, user_name) log.info('Detached %s policy from IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach %s policy from IAM user %s.', policy_name, user_name) return False return True def attach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_group_policy(policy_arn, group_name) log.info('Attached policy %s to IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM group %s.', policy_name, group_name) return False return True def detach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_group_policy(policy_arn, group_name) log.info('Detached policy %s from IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM group %s.', policy_name, group_name) return False return True def attach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_role_policy(policy_arn, role_name) log.info('Attached policy %s to IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM role %s.', policy_name, role_name) return False return True def detach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_role_policy(policy_arn, role_name) log.info('Detached policy %s from IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM role %s.', policy_name, role_name) return False return True def list_entities_for_policy(policy_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities that a policy is attached to. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 params = {} for arg in ('path_prefix', 'entity_filter'): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) while retries: try: allret = { 'policy_groups': [], 'policy_users': [], 'policy_roles': [], } for ret in __utils__['boto.paged_call'](conn.list_entities_for_policy, policy_arn=policy_arn, **params): for k, v in six.iteritems(allret): v.extend(ret.get('list_entities_for_policy_response', {}).get('list_entities_for_policy_result', {}).get(k)) return allret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('Failed to list entities for IAM policy %s: %s', policy_name, e.message) return {} return {} def list_attached_user_policies(user_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given user. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'UserName': user_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedUserPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_user_policies_response', {}).get('list_attached_user_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM user %s.', user_name) return [] def list_attached_group_policies(group_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given group. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'GroupName': group_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedGroupPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_group_policies_response', {}).get('list_attached_group_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM group %s.', group_name) return [] def list_attached_role_policies(role_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'RoleName': role_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedRolePolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_role_policies_response', {}).get('list_attached_role_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM role %s.', role_name) return [] def get_saml_provider_arn(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider_arn my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_saml_providers() for saml_provider in response.list_saml_providers_response.list_saml_providers_result.saml_provider_list: if saml_provider['arn'].endswith(':saml-provider/' + name): return saml_provider['arn'] return False except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to get ARN of SAML provider %s.', name) return False def delete_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Delete SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.delete_saml_provider my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return True conn.delete_saml_provider(saml_provider_arn) log.info('Successfully deleted SAML provider %s.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete SAML provider %s.', name) return False def list_saml_providers(region=None, key=None, keyid=None, profile=None): ''' List SAML providers. CLI Example: .. code-block:: bash salt myminion boto_iam.list_saml_providers ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: providers = [] info = conn.list_saml_providers() for arn in info['list_saml_providers_response']['list_saml_providers_result']['saml_provider_list']: providers.append(arn['arn'].rsplit('/', 1)[1]) return providers except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get list of SAML providers.') return False def get_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider document. CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider arn ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: provider = conn.get_saml_provider(name) return provider['get_saml_provider_response']['get_saml_provider_result']['saml_metadata_document'] except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get SAML provider document %s.', name) return False def update_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Update SAML provider. CLI Example: .. code-block:: bash salt myminion boto_iam.update_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return False if conn.update_saml_provider(name, saml_metadata_document): return True return False except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to update SAML provider %s.', name) return False
saltstack/salt
salt/modules/boto_iam.py
get_saml_provider_arn
python
def get_saml_provider_arn(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider_arn my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_saml_providers() for saml_provider in response.list_saml_providers_response.list_saml_providers_result.saml_provider_list: if saml_provider['arn'].endswith(':saml-provider/' + name): return saml_provider['arn'] return False except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to get ARN of SAML provider %s.', name) return False
Get SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider_arn my_saml_provider_name
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iam.py#L2283-L2304
null
# -*- coding: utf-8 -*- ''' Connection module for Amazon IAM .. versionadded:: 2014.7.0 :configuration: This module accepts explicit iam 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 iam.keyid: GKTADJGHEIQSXMKKRBJ08H iam.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs iam.region: 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: boto ''' # keep lint from choking on _get_conn and _cache_id #pylint: disable=E0602 # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import salt libs from salt.ext import six import salt.utils.compat import salt.utils.json import salt.utils.odict as odict import salt.utils.versions from salt.exceptions import SaltInvocationError # Import third party libs # pylint: disable=unused-import from salt.ext.six.moves.urllib.parse import unquote as _unquote # pylint: disable=no-name-in-module try: import boto import boto.iam import boto3 import botocore logging.getLogger('boto').setLevel(logging.CRITICAL) logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=unused-import log = logging.getLogger(__name__) def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'iam', pack=__salt__) def instance_profile_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an instance profile exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: # Boto weirdly returns an exception here if an instance profile doesn't # exist. conn.get_instance_profile(name) return True except boto.exception.BotoServerError: return False def create_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Create an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.create_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if instance_profile_exists(name, region, key, keyid, profile): return True try: # This call returns an instance profile if successful and an exception # if not. It's annoying. conn.create_instance_profile(name) log.info('Created %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create %s instance profile.', name) return False return True def delete_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Delete an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not instance_profile_exists(name, region, key, keyid, profile): return True try: conn.delete_instance_profile(name) log.info('Deleted %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s instance profile.', name) return False return True def role_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an IAM role exists. CLI Example: .. code-block:: bash salt myminion boto_iam.role_exists myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_role(name) return True except boto.exception.BotoServerError: return False def describe_role(name, region=None, key=None, keyid=None, profile=None): ''' Get information for a role. CLI Example: .. code-block:: bash salt myminion boto_iam.describe_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_role(name) if not info: return False role = info.get_role_response.get_role_result.role role['assume_role_policy_document'] = salt.utils.json.loads(_unquote( role.assume_role_policy_document )) # If Sid wasn't defined by the user, boto will still return a Sid in # each policy. To properly check idempotently, let's remove the Sid # from the return if it's not actually set. for policy_key, policy in role['assume_role_policy_document'].items(): if policy_key == 'Statement': for val in policy: if 'Sid' in val and not val['Sid']: del val['Sid'] return role except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get %s information.', name) return False def create_user(user_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_user myuser ''' if not path: path = '/' if get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_user(user_name, path) log.info('Created IAM user : %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM user %s.', user_name) return False def get_all_access_keys(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all access keys from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_access_keys myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.get_all_access_keys(user_name, marker, max_items) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get access keys for IAM user %s.', user_name) return six.text_type(e) def create_access_key(user_name, region=None, key=None, keyid=None, profile=None): ''' Create access key id for a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.create_access_key(user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create access key.') return six.text_type(e) def delete_access_key(access_key_id, user_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete access key id from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_access_key(access_key_id, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete access key id %s.', access_key_id) return six.text_type(e) def delete_user(user_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user myuser ''' if not get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.delete_user(user_name) log.info('Deleted IAM user : %s .', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM user %s', user_name) return six.text_type(e) def get_user(user_name=None, region=None, key=None, keyid=None, profile=None): ''' Get user information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user(user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM user %s info.', user_name) return False def create_group(group_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_group group ''' if not path: path = '/' if get_group(group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_group(group_name, path) log.info('Created IAM group : %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM group %s.', group_name) return False def get_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group(group_name, max_items=1) if not info: return False return info['get_group_response']['get_group_result']['group'] except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_group_members(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: marker = None truncated = True users = [] while truncated: info = conn.get_group(group_name, marker=marker, max_items=1000) if not info: return False truncated = bool(info['get_group_response']['get_group_result']['is_truncated']) if truncated and 'marker' in info['get_group_response']['get_group_result']: marker = info['get_group_response']['get_group_result']['marker'] else: marker = None truncated = False users += info['get_group_response']['get_group_result']['users'] return users except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get members for IAM group %s.', group_name) return False def add_user_to_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Add user to group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.add_user_to_group myuser mygroup ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('Username : %s does not exist.', user_name) return False if user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.add_user_to_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add IAM user %s to group %s.', user_name, group_name) return False def user_exists_in_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Check if user exists in group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.user_exists_in_group myuser mygroup ''' # TODO this should probably use boto.iam.get_groups_for_user users = get_group_members( group_name=group_name, region=region, key=key, keyid=keyid, profile=profile ) if users: for _user in users: if user_name == _user['user_name']: log.debug('IAM user %s is already in IAM group %s.', user_name, group_name) return True return False def remove_user_from_group(group_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Remove user from group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.remove_user_from_group mygroup myuser ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist.', user_name) return False if not user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.remove_user_from_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove IAM user %s from group %s', user_name, group_name) return False def put_group_policy(group_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_group_policy mygroup policyname policyrules ''' group = get_group(group_name, region=region, key=key, keyid=keyid, profile=profile) if not group: log.error('Group %s does not exist', group_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_group_policy(group_name, policy_name, policy_json) if created: log.info('Created policy for IAM group %s.', group_name) return True log.error('Could not create policy for IAM group %s', group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy for IAM group %s', group_name) return False def delete_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group_policy mygroup mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_group_policy( group_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_group_policy(group_name, policy_name) log.info('Successfully deleted policy %s for IAM group %s.', policy_name, group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM group %s.', policy_name, group_name) return False def get_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group_policy mygroup policyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group_policy(group_name, policy_name) log.debug('info for group policy is : %s', info) if not info: return False info = info.get_group_policy_response.get_group_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_all_groups(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM group details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_groups ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _groups = conn.get_all_groups(path_prefix=path_prefix) groups = _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) while marker: _groups = conn.get_all_groups(path_prefix=path_prefix, marker=marker) groups = groups + _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) return groups def get_all_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.get_all_instance_profiles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) marker = False profiles = [] while marker is not None: marker = marker if marker else None p = conn.list_instance_profiles(path_prefix=path_prefix, marker=marker) res = p.list_instance_profiles_response.list_instance_profiles_result profiles += res.instance_profiles marker = getattr(res, 'marker', None) return profiles def list_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' List all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.list_instance_profiles ''' p = get_all_instance_profiles(path_prefix, region, key, keyid, profile) return [i['instance_profile_name'] for i in p] def get_all_group_policies(group_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a group. CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_group_policies mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False try: response = conn.get_all_group_policies(group_name) _list = response.list_group_policies_response.list_group_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def delete_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _group = get_group( group_name, region, key, keyid, profile ) if not _group: return True try: conn.delete_group(group_name) log.info('Successfully deleted IAM group %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM group %s.', group_name) return False def create_login_profile(user_name, password, region=None, key=None, keyid=None, profile=None): ''' Creates a login profile for the specified user, give the user the ability to access AWS services and the AWS Management Console. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_login_profile user_name password ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.create_login_profile(user_name, password) log.info('Created profile for IAM user %s.', user_name) return info except boto.exception.BotoServerError as e: log.debug(e) if 'Conflict' in e: log.info('Profile already exists for IAM user %s.', user_name) return 'Conflict' log.error('Failed to update profile for IAM user %s.', user_name) return False def delete_login_profile(user_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a login profile for the specified user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_login_profile user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.delete_login_profile(user_name) log.info('Deleted login profile for IAM user %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Login profile already deleted for IAM user %s.', user_name) return True log.error('Failed to delete login profile for IAM user %s.', user_name) return False def get_all_mfa_devices(user_name, region=None, key=None, keyid=None, profile=None): ''' Get all MFA devices associated with an IAM user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_mfa_devices user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: result = conn.get_all_mfa_devices(user_name) devices = result['list_mfa_devices_response']['list_mfa_devices_result']['mfa_devices'] return devices except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Could not find IAM user %s.', user_name) return [] log.error('Failed to get all MFA devices for IAM user %s.', user_name) return False def deactivate_mfa_device(user_name, serial, region=None, key=None, keyid=None, profile=None): ''' Deactivates the specified MFA device and removes it from association with the user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.deactivate_mfa_device user_name serial_num ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.deactivate_mfa_device(user_name, serial) log.info('Deactivated MFA device %s for IAM user %s.', serial, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('MFA device %s not associated with IAM user %s.', serial, user_name) return True log.error('Failed to deactivate MFA device %s for IAM user %s.', serial, user_name) return False def delete_virtual_mfa_device(serial, region=None, key=None, keyid=None, profile=None): ''' Deletes the specified virtual MFA device. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_virtual_mfa_device serial_num ''' conn = __utils__['boto3.get_connection_func']('iam')() try: conn.delete_virtual_mfa_device(SerialNumber=serial) log.info('Deleted virtual MFA device %s.', serial) return True except botocore.exceptions.ClientError as e: log.debug(e) if 'NoSuchEntity' in six.text_type(e): log.info('Virtual MFA device %s not found.', serial) return True log.error('Failed to delete virtual MFA device %s.', serial) return False def update_account_password_policy(allow_users_to_change_password=None, hard_expiry=None, max_password_age=None, minimum_password_length=None, password_reuse_prevention=None, require_lowercase_characters=None, require_numbers=None, require_symbols=None, require_uppercase_characters=None, region=None, key=None, keyid=None, profile=None): ''' Update the password policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_account_password_policy True ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.update_account_password_policy(allow_users_to_change_password, hard_expiry, max_password_age, minimum_password_length, password_reuse_prevention, require_lowercase_characters, require_numbers, require_symbols, require_uppercase_characters) log.info('The password policy has been updated.') return True except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy' log.error(msg) return False def get_account_policy(region=None, key=None, keyid=None, profile=None): ''' Get account policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_account_password_policy() return info.get_account_password_policy_response.get_account_password_policy_result.password_policy except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy.' log.error(msg) return False def create_role(name, policy_document=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Create an instance role. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if role_exists(name, region, key, keyid, profile): return True if not policy_document: policy_document = None try: conn.create_role(name, assume_role_policy_document=policy_document, path=path) log.info('Created IAM role %s.', name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to create IAM role %s.', name) return False def delete_role(name, region=None, key=None, keyid=None, profile=None): ''' Delete an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(name, region, key, keyid, profile): return True try: conn.delete_role(name) log.info('Deleted %s IAM role.', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s IAM role.', name) return False def profile_associated(role_name, profile_name, region, key, keyid, profile): ''' Check to see if an instance profile is associated with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.profile_associated myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # The IAM module of boto doesn't return objects. Instead you need to grab # values through its properties. Sigh. try: profiles = conn.list_instance_profiles_for_role(role_name) except boto.exception.BotoServerError as e: log.debug(e) return False profiles = profiles.list_instance_profiles_for_role_response profiles = profiles.list_instance_profiles_for_role_result profiles = profiles.instance_profiles for profile in profiles: if profile.instance_profile_name == profile_name: return True return False def associate_profile_to_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Associate an instance profile with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.associate_profile_to_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if associated: return True else: try: conn.add_role_to_instance_profile(profile_name, role_name) log.info('Added %s instance profile to IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add %s instance profile to IAM role %s', profile_name, role_name) return False def disassociate_profile_from_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Disassociate an instance profile from an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.disassociate_profile_from_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if not associated: return True else: try: conn.remove_role_from_instance_profile(profile_name, role_name) log.info('Removed %s instance profile from IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove %s instance profile from IAM role %s.', profile_name, role_name) return False def list_role_policies(role_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_role_policies myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_role_policies(role_name) _list = response.list_role_policies_response.list_role_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def get_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.get_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: _policy = conn.get_role_policy(role_name, policy_name) # I _hate_ you for not giving me an object boto. _policy = _policy.get_role_policy_response.policy_document # Policy is url encoded _policy = _unquote(_policy) _policy = salt.utils.json.loads(_policy, object_pairs_hook=odict.OrderedDict) return _policy except boto.exception.BotoServerError: return {} def create_role_policy(role_name, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Create or modify a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role_policy myirole mypolicy '{"MyPolicy": "Statement": [{"Action": ["sqs:*"], "Effect": "Allow", "Resource": ["arn:aws:sqs:*:*:*"], "Sid": "MyPolicySqs1"}]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) mode = 'create' if _policy: if _policy == policy: return True mode = 'modify' if isinstance(policy, six.string_types): policy = salt.utils.json.loads(policy, object_pairs_hook=odict.OrderedDict) try: _policy = salt.utils.json.dumps(policy) conn.put_role_policy(role_name, policy_name, _policy) if mode == 'create': msg = 'Successfully added policy %s to IAM role %s.' else: msg = 'Successfully modified policy %s for IAM role %s.' log.info(msg, policy_name, role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to %s policy %s for IAM role %s.', mode, policy_name, role_name) return False def delete_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) if not _policy: return True try: conn.delete_role_policy(role_name, policy_name) log.info('Successfully deleted policy %s for IAM role %s.', policy_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM role %s.', policy_name, role_name) return False def update_assume_role_policy(role_name, policy_document, region=None, key=None, keyid=None, profile=None): ''' Update an assume role policy for a role. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_assume_role_policy myrole '{"Statement":"..."}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(policy_document, six.string_types): policy_document = salt.utils.json.loads(policy_document, object_pairs_hook=odict.OrderedDict) try: _policy_document = salt.utils.json.dumps(policy_document) conn.update_assume_role_policy(role_name, _policy_document) log.info('Successfully updated assume role policy for IAM role %s.', role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to update assume role policy for IAM role %s.', role_name) return False def build_policy(region=None, key=None, keyid=None, profile=None): ''' Build a default assume role policy. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.build_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if hasattr(conn, 'build_policy'): policy = salt.utils.json.loads(conn.build_policy()) elif hasattr(conn, '_build_policy'): policy = salt.utils.json.loads(conn._build_policy()) else: return {} # The format we get from build_policy isn't going to be what we get back # from AWS for the exact same policy. AWS converts single item list values # into strings, so let's do the same here. for key, policy_val in policy.items(): for statement in policy_val: if (isinstance(statement['Action'], list) and len(statement['Action']) == 1): statement['Action'] = statement['Action'][0] if (isinstance(statement['Principal']['Service'], list) and len(statement['Principal']['Service']) == 1): statement['Principal']['Service'] = statement['Principal']['Service'][0] # build_policy doesn't add a version field, which AWS is going to set to a # default value, when we get it back, so let's set it. policy['Version'] = '2008-10-17' return policy def get_account_id(region=None, key=None, keyid=None, profile=None): ''' Get a the AWS account id associated with the used credentials. CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_id ''' cache_key = 'boto_iam.account_id' if cache_key not in __context__: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_user() # The get_user call returns an user ARN: # arn:aws:iam::027050522557:user/salt-test arn = ret['get_user_response']['get_user_result']['user']['arn'] account_id = arn.split(':')[4] except boto.exception.BotoServerError: # If call failed, then let's try to get the ARN from the metadata timeout = boto.config.getfloat( 'Boto', 'metadata_service_timeout', 1.0 ) attempts = boto.config.getint( 'Boto', 'metadata_service_num_attempts', 1 ) identity = boto.utils.get_instance_identity( timeout=timeout, num_retries=attempts ) try: account_id = identity['document']['accountId'] except KeyError: log.error('Failed to get account id from instance_identity in' ' boto_iam.get_account_id.') __context__[cache_key] = account_id return __context__[cache_key] def get_all_roles(path_prefix=None, region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM role details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_roles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _roles = conn.list_roles(path_prefix=path_prefix) roles = _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) while marker: _roles = conn.list_roles(path_prefix=path_prefix, marker=marker) roles = roles + _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) return roles def get_all_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM user details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_users ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _users = conn.get_all_users(path_prefix=path_prefix) users = _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) while marker: _users = conn.get_all_users(path_prefix=path_prefix, marker=marker) users = users + _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) return users def get_all_user_policies(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all user policies. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_user_policies myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_all_user_policies(user_name, marker, max_items) if not info: return False _list = info.list_user_policies_response.list_user_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policies for user %s.', user_name) return False def get_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user_policy myuser mypolicyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user_policy(user_name, policy_name) log.debug('Info for IAM user %s policy %s: %s.', user_name, policy_name, info) if not info: return False info = info.get_user_policy_response.get_user_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policy %s for IAM user %s.', policy_name, user_name) return False def put_user_policy(user_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_user_policy myuser policyname policyrules ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_user_policy(user_name, policy_name, policy_json) if created: log.info('Created policy %s for IAM user %s.', policy_name, user_name) return True log.error('Could not create policy %s for IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy %s for IAM user %s.', policy_name, user_name) return False def delete_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user_policy myuser mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_user_policy( user_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_user_policy(user_name, policy_name) log.info('Successfully deleted policy %s for IAM user %s.', policy_name, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM user %s.', policy_name, user_name) return False def upload_server_cert(cert_name, cert_body, private_key, cert_chain=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Upload a certificate to Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.upload_server_cert mycert_name crt priv_key :param cert_name: The name for the server certificate. Do not include the path in this value. :param cert_body: The contents of the public key certificate in PEM-encoded format. :param private_key: The contents of the private key in PEM-encoded format. :param cert_chain: The contents of the certificate chain. This is typically a concatenation of the PEM-encoded public key certificates of the chain. :param path: The path for the server certificate. :param region: The name of the region to connect to. :param key: The key to be used in order to connect :param keyid: The keyid to be used in order to connect :param profile: The profile that contains a dict of region, key, keyid :return: True / False ''' exists = get_server_certificate(cert_name, region, key, keyid, profile) if exists: return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.upload_server_cert(cert_name, cert_body, private_key, cert_chain) log.info('Created certificate %s.', cert_name) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to failed to create certificate %s.', cert_name) return False def list_server_certificates(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Lists the server certificates stored in IAM that have the specified path prefix. .. versionadded:: ??? :param path_prefix: The path prefix for filtering the results. For example: /company/servercerts would get all server certificates for which the path starts with /company/servercerts . This parameter is optional. If it is not included, it defaults to a slash (/), listing all server certificates. This parameter allows (per its regex pattern) a string of characters consisting of either a forward slash (/) by itself or a string that must begin and end with forward slashes. In addition, it can contain any ASCII character from the ! (u0021) through the DEL character (u007F), including most punctuation characters, digits, and upper and lowercased letters. CLI Example: .. code-block:: bash salt myminion boto_iam.list_server_certificates path_prefix=/somepath/ ''' retries = 10 sleep = 6 conn = __utils__['boto3.get_connection']('iam', region=region, key=key, keyid=keyid, profile=profile) Items = [] while retries: try: log.debug('Garnering list of IAM Server Certificates') IsTruncated = True while IsTruncated: kwargs = {'PathPrefix': path_prefix} ret = conn.list_server_certificates(**kwargs) Items += ret.get('ServerCertificateMetadataList', []) IsTruncated = ret.get('IsTruncated') kwargs.update({'Marker': ret.get('Marker')}) return Items except botocore.exceptions.ParamValidationError as err: raise SaltInvocationError(str(err)) except botocore.exceptions.ClientError as err: if retries and jmespath.search('Error.Code', err.response) == 'Throttling': retries -= 1 log.debug('Throttled by AWS API, retrying in %s seconds...', sleep) time.sleep(sleep) continue log.error('Failed to list IAM Server Certificates: %s', err.message) return None def get_server_certificate(cert_name, region=None, key=None, keyid=None, profile=None): ''' Returns certificate information from Amazon .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_server_certificate mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_server_certificate(cert_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get certificate %s information.', cert_name) return False def delete_server_cert(cert_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a certificate from Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_server_cert mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_server_cert(cert_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete certificate %s.', cert_name) return False def export_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM user details. Produces results that can be used to create an sls file. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.export_users --out=txt | sed "s/local: //" > iam_users.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() users = get_all_users(path_prefix, region, key, keyid, profile) for user in users: name = user.user_name _policies = conn.get_all_user_policies(name, max_items=100) _policies = _policies.list_user_policies_response.list_user_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_user_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_user_policy_response.get_user_policy_result.policy_document )) policies[policy_name] = _policy user_sls = [] user_sls.append({"name": name}) user_sls.append({"policies": policies}) user_sls.append({"path": user.path}) results["manage user " + name] = {"boto_iam.user_present": user_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def export_roles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM role details. Produces results that can be used to create an sls file. CLI Example: salt-call boto_iam.export_roles --out=txt | sed "s/local: //" > iam_roles.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() roles = get_all_roles(path_prefix, region, key, keyid, profile) for role in roles: name = role.role_name _policies = conn.list_role_policies(name, max_items=100) _policies = _policies.list_role_policies_response.list_role_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_role_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_role_policy_response.get_role_policy_result.policy_document )) policies[policy_name] = _policy role_sls = [] role_sls.append({"name": name}) role_sls.append({"policies": policies}) role_sls.append({'policy_document': salt.utils.json.loads(_unquote(role.assume_role_policy_document))}) role_sls.append({"path": role.path}) results["manage role " + name] = {"boto_iam_role.present": role_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def _get_policy_arn(name, region=None, key=None, keyid=None, profile=None): if name.startswith('arn:aws:iam:'): return name account_id = get_account_id( region=region, key=key, keyid=keyid, profile=profile ) return 'arn:aws:iam::{0}:policy/{1}'.format(account_id, name) def policy_exists(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return True except boto.exception.BotoServerError: return False def get_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return ret.get('get_policy_response', {}).get('get_policy_result', {}) except boto.exception.BotoServerError: return None def create_policy(policy_name, policy_document, path=None, description=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in 'path', 'description': if locals()[arg] is not None: params[arg] = locals()[arg] if policy_exists(policy_name, region, key, keyid, profile): return True try: conn.create_policy(policy_name, policy_document, **params) log.info('Created IAM policy %s.', policy_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s.', policy_name) return False return True def delete_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_exists(policy_arn, region, key, keyid, profile): return True try: conn.delete_policy(policy_arn) log.info('Deleted %s policy.', policy_name) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete %s policy: %s.', policy_name, aws.get('message')) return False return True def list_policies(region=None, key=None, keyid=None, profile=None): ''' List policies. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policies ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: policies = [] for ret in __utils__['boto.paged_call'](conn.list_policies): policies.append(ret.get('list_policies_response', {}).get('list_policies_result', {}).get('policies')) return policies except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to list policy versions.' log.error(msg) return [] def policy_version_exists(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.get_policy_version(policy_arn, version_id) return True except boto.exception.BotoServerError: return False def get_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy_version(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile), version_id) retval = ret.get('get_policy_version_response', {}).get('get_policy_version_result', {}).get('policy_version', {}) retval['document'] = _unquote(retval.get('document')) return {'policy_version': retval} except boto.exception.BotoServerError: return None def create_policy_version(policy_name, policy_document, set_as_default=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy version. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy_version mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in ('set_as_default',): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.create_policy_version(policy_arn, policy_document, **params) vid = ret.get('create_policy_version_response', {}).get('create_policy_version_result', {}).get('policy_version', {}).get('version_id') log.info('Created IAM policy %s version %s.', policy_name, vid) return {'created': True, 'version_id': vid} except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s version %s.', policy_name, vid) return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Delete a policy version. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_version_exists(policy_arn, version_id, region, key, keyid, profile): return True try: conn.delete_policy_version(policy_arn, version_id) log.info('Deleted IAM policy %s version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete IAM policy %s version %s: %s', policy_name, version_id, aws.get('message')) return False return True def list_policy_versions(policy_name, region=None, key=None, keyid=None, profile=None): ''' List versions of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policy_versions mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.list_policy_versions(policy_arn) return ret.get('list_policy_versions_response', {}).get('list_policy_versions_result', {}).get('versions') except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list versions for IAM policy %s.', policy_name) return [] def set_default_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Set the default version of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.set_default_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.set_default_policy_version(policy_arn, version_id) log.info('Set %s policy to version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to set %s policy to version %s: %s', policy_name, version_id, aws.get('message')) return False return True def attach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_user_policy(policy_arn, user_name) log.info('Attached policy %s to IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach %s policy to IAM user %s.', policy_name, user_name) return False return True def detach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_user_policy(policy_arn, user_name) log.info('Detached %s policy from IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach %s policy from IAM user %s.', policy_name, user_name) return False return True def attach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_group_policy(policy_arn, group_name) log.info('Attached policy %s to IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM group %s.', policy_name, group_name) return False return True def detach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_group_policy(policy_arn, group_name) log.info('Detached policy %s from IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM group %s.', policy_name, group_name) return False return True def attach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_role_policy(policy_arn, role_name) log.info('Attached policy %s to IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM role %s.', policy_name, role_name) return False return True def detach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_role_policy(policy_arn, role_name) log.info('Detached policy %s from IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM role %s.', policy_name, role_name) return False return True def list_entities_for_policy(policy_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities that a policy is attached to. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 params = {} for arg in ('path_prefix', 'entity_filter'): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) while retries: try: allret = { 'policy_groups': [], 'policy_users': [], 'policy_roles': [], } for ret in __utils__['boto.paged_call'](conn.list_entities_for_policy, policy_arn=policy_arn, **params): for k, v in six.iteritems(allret): v.extend(ret.get('list_entities_for_policy_response', {}).get('list_entities_for_policy_result', {}).get(k)) return allret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('Failed to list entities for IAM policy %s: %s', policy_name, e.message) return {} return {} def list_attached_user_policies(user_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given user. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'UserName': user_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedUserPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_user_policies_response', {}).get('list_attached_user_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM user %s.', user_name) return [] def list_attached_group_policies(group_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given group. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'GroupName': group_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedGroupPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_group_policies_response', {}).get('list_attached_group_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM group %s.', group_name) return [] def list_attached_role_policies(role_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'RoleName': role_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedRolePolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_role_policies_response', {}).get('list_attached_role_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM role %s.', role_name) return [] def create_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Create SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.create_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_saml_provider(saml_metadata_document, name) log.info('Successfully created %s SAML provider.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to create SAML provider %s.', name) return False def delete_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Delete SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.delete_saml_provider my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return True conn.delete_saml_provider(saml_provider_arn) log.info('Successfully deleted SAML provider %s.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete SAML provider %s.', name) return False def list_saml_providers(region=None, key=None, keyid=None, profile=None): ''' List SAML providers. CLI Example: .. code-block:: bash salt myminion boto_iam.list_saml_providers ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: providers = [] info = conn.list_saml_providers() for arn in info['list_saml_providers_response']['list_saml_providers_result']['saml_provider_list']: providers.append(arn['arn'].rsplit('/', 1)[1]) return providers except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get list of SAML providers.') return False def get_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider document. CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider arn ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: provider = conn.get_saml_provider(name) return provider['get_saml_provider_response']['get_saml_provider_result']['saml_metadata_document'] except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get SAML provider document %s.', name) return False def update_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Update SAML provider. CLI Example: .. code-block:: bash salt myminion boto_iam.update_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return False if conn.update_saml_provider(name, saml_metadata_document): return True return False except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to update SAML provider %s.', name) return False
saltstack/salt
salt/modules/boto_iam.py
delete_saml_provider
python
def delete_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Delete SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.delete_saml_provider my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return True conn.delete_saml_provider(saml_provider_arn) log.info('Successfully deleted SAML provider %s.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete SAML provider %s.', name) return False
Delete SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.delete_saml_provider my_saml_provider_name
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iam.py#L2307-L2330
[ "def get_saml_provider_arn(name, region=None, key=None, keyid=None, profile=None):\n '''\n Get SAML provider\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_iam.get_saml_provider_arn my_saml_provider_name\n '''\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n try:\n response = conn.list_saml_providers()\n for saml_provider in response.list_saml_providers_response.list_saml_providers_result.saml_provider_list:\n if saml_provider['arn'].endswith(':saml-provider/' + name):\n return saml_provider['arn']\n return False\n except boto.exception.BotoServerError as e:\n aws = __utils__['boto.get_error'](e)\n log.debug(aws)\n log.error('Failed to get ARN of SAML provider %s.', name)\n return False\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon IAM .. versionadded:: 2014.7.0 :configuration: This module accepts explicit iam 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 iam.keyid: GKTADJGHEIQSXMKKRBJ08H iam.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs iam.region: 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: boto ''' # keep lint from choking on _get_conn and _cache_id #pylint: disable=E0602 # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import salt libs from salt.ext import six import salt.utils.compat import salt.utils.json import salt.utils.odict as odict import salt.utils.versions from salt.exceptions import SaltInvocationError # Import third party libs # pylint: disable=unused-import from salt.ext.six.moves.urllib.parse import unquote as _unquote # pylint: disable=no-name-in-module try: import boto import boto.iam import boto3 import botocore logging.getLogger('boto').setLevel(logging.CRITICAL) logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=unused-import log = logging.getLogger(__name__) def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'iam', pack=__salt__) def instance_profile_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an instance profile exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: # Boto weirdly returns an exception here if an instance profile doesn't # exist. conn.get_instance_profile(name) return True except boto.exception.BotoServerError: return False def create_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Create an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.create_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if instance_profile_exists(name, region, key, keyid, profile): return True try: # This call returns an instance profile if successful and an exception # if not. It's annoying. conn.create_instance_profile(name) log.info('Created %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create %s instance profile.', name) return False return True def delete_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Delete an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not instance_profile_exists(name, region, key, keyid, profile): return True try: conn.delete_instance_profile(name) log.info('Deleted %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s instance profile.', name) return False return True def role_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an IAM role exists. CLI Example: .. code-block:: bash salt myminion boto_iam.role_exists myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_role(name) return True except boto.exception.BotoServerError: return False def describe_role(name, region=None, key=None, keyid=None, profile=None): ''' Get information for a role. CLI Example: .. code-block:: bash salt myminion boto_iam.describe_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_role(name) if not info: return False role = info.get_role_response.get_role_result.role role['assume_role_policy_document'] = salt.utils.json.loads(_unquote( role.assume_role_policy_document )) # If Sid wasn't defined by the user, boto will still return a Sid in # each policy. To properly check idempotently, let's remove the Sid # from the return if it's not actually set. for policy_key, policy in role['assume_role_policy_document'].items(): if policy_key == 'Statement': for val in policy: if 'Sid' in val and not val['Sid']: del val['Sid'] return role except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get %s information.', name) return False def create_user(user_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_user myuser ''' if not path: path = '/' if get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_user(user_name, path) log.info('Created IAM user : %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM user %s.', user_name) return False def get_all_access_keys(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all access keys from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_access_keys myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.get_all_access_keys(user_name, marker, max_items) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get access keys for IAM user %s.', user_name) return six.text_type(e) def create_access_key(user_name, region=None, key=None, keyid=None, profile=None): ''' Create access key id for a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.create_access_key(user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create access key.') return six.text_type(e) def delete_access_key(access_key_id, user_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete access key id from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_access_key(access_key_id, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete access key id %s.', access_key_id) return six.text_type(e) def delete_user(user_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user myuser ''' if not get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.delete_user(user_name) log.info('Deleted IAM user : %s .', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM user %s', user_name) return six.text_type(e) def get_user(user_name=None, region=None, key=None, keyid=None, profile=None): ''' Get user information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user(user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM user %s info.', user_name) return False def create_group(group_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_group group ''' if not path: path = '/' if get_group(group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_group(group_name, path) log.info('Created IAM group : %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM group %s.', group_name) return False def get_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group(group_name, max_items=1) if not info: return False return info['get_group_response']['get_group_result']['group'] except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_group_members(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: marker = None truncated = True users = [] while truncated: info = conn.get_group(group_name, marker=marker, max_items=1000) if not info: return False truncated = bool(info['get_group_response']['get_group_result']['is_truncated']) if truncated and 'marker' in info['get_group_response']['get_group_result']: marker = info['get_group_response']['get_group_result']['marker'] else: marker = None truncated = False users += info['get_group_response']['get_group_result']['users'] return users except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get members for IAM group %s.', group_name) return False def add_user_to_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Add user to group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.add_user_to_group myuser mygroup ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('Username : %s does not exist.', user_name) return False if user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.add_user_to_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add IAM user %s to group %s.', user_name, group_name) return False def user_exists_in_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Check if user exists in group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.user_exists_in_group myuser mygroup ''' # TODO this should probably use boto.iam.get_groups_for_user users = get_group_members( group_name=group_name, region=region, key=key, keyid=keyid, profile=profile ) if users: for _user in users: if user_name == _user['user_name']: log.debug('IAM user %s is already in IAM group %s.', user_name, group_name) return True return False def remove_user_from_group(group_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Remove user from group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.remove_user_from_group mygroup myuser ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist.', user_name) return False if not user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.remove_user_from_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove IAM user %s from group %s', user_name, group_name) return False def put_group_policy(group_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_group_policy mygroup policyname policyrules ''' group = get_group(group_name, region=region, key=key, keyid=keyid, profile=profile) if not group: log.error('Group %s does not exist', group_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_group_policy(group_name, policy_name, policy_json) if created: log.info('Created policy for IAM group %s.', group_name) return True log.error('Could not create policy for IAM group %s', group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy for IAM group %s', group_name) return False def delete_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group_policy mygroup mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_group_policy( group_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_group_policy(group_name, policy_name) log.info('Successfully deleted policy %s for IAM group %s.', policy_name, group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM group %s.', policy_name, group_name) return False def get_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group_policy mygroup policyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group_policy(group_name, policy_name) log.debug('info for group policy is : %s', info) if not info: return False info = info.get_group_policy_response.get_group_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_all_groups(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM group details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_groups ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _groups = conn.get_all_groups(path_prefix=path_prefix) groups = _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) while marker: _groups = conn.get_all_groups(path_prefix=path_prefix, marker=marker) groups = groups + _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) return groups def get_all_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.get_all_instance_profiles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) marker = False profiles = [] while marker is not None: marker = marker if marker else None p = conn.list_instance_profiles(path_prefix=path_prefix, marker=marker) res = p.list_instance_profiles_response.list_instance_profiles_result profiles += res.instance_profiles marker = getattr(res, 'marker', None) return profiles def list_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' List all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.list_instance_profiles ''' p = get_all_instance_profiles(path_prefix, region, key, keyid, profile) return [i['instance_profile_name'] for i in p] def get_all_group_policies(group_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a group. CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_group_policies mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False try: response = conn.get_all_group_policies(group_name) _list = response.list_group_policies_response.list_group_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def delete_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _group = get_group( group_name, region, key, keyid, profile ) if not _group: return True try: conn.delete_group(group_name) log.info('Successfully deleted IAM group %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM group %s.', group_name) return False def create_login_profile(user_name, password, region=None, key=None, keyid=None, profile=None): ''' Creates a login profile for the specified user, give the user the ability to access AWS services and the AWS Management Console. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_login_profile user_name password ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.create_login_profile(user_name, password) log.info('Created profile for IAM user %s.', user_name) return info except boto.exception.BotoServerError as e: log.debug(e) if 'Conflict' in e: log.info('Profile already exists for IAM user %s.', user_name) return 'Conflict' log.error('Failed to update profile for IAM user %s.', user_name) return False def delete_login_profile(user_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a login profile for the specified user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_login_profile user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.delete_login_profile(user_name) log.info('Deleted login profile for IAM user %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Login profile already deleted for IAM user %s.', user_name) return True log.error('Failed to delete login profile for IAM user %s.', user_name) return False def get_all_mfa_devices(user_name, region=None, key=None, keyid=None, profile=None): ''' Get all MFA devices associated with an IAM user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_mfa_devices user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: result = conn.get_all_mfa_devices(user_name) devices = result['list_mfa_devices_response']['list_mfa_devices_result']['mfa_devices'] return devices except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Could not find IAM user %s.', user_name) return [] log.error('Failed to get all MFA devices for IAM user %s.', user_name) return False def deactivate_mfa_device(user_name, serial, region=None, key=None, keyid=None, profile=None): ''' Deactivates the specified MFA device and removes it from association with the user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.deactivate_mfa_device user_name serial_num ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.deactivate_mfa_device(user_name, serial) log.info('Deactivated MFA device %s for IAM user %s.', serial, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('MFA device %s not associated with IAM user %s.', serial, user_name) return True log.error('Failed to deactivate MFA device %s for IAM user %s.', serial, user_name) return False def delete_virtual_mfa_device(serial, region=None, key=None, keyid=None, profile=None): ''' Deletes the specified virtual MFA device. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_virtual_mfa_device serial_num ''' conn = __utils__['boto3.get_connection_func']('iam')() try: conn.delete_virtual_mfa_device(SerialNumber=serial) log.info('Deleted virtual MFA device %s.', serial) return True except botocore.exceptions.ClientError as e: log.debug(e) if 'NoSuchEntity' in six.text_type(e): log.info('Virtual MFA device %s not found.', serial) return True log.error('Failed to delete virtual MFA device %s.', serial) return False def update_account_password_policy(allow_users_to_change_password=None, hard_expiry=None, max_password_age=None, minimum_password_length=None, password_reuse_prevention=None, require_lowercase_characters=None, require_numbers=None, require_symbols=None, require_uppercase_characters=None, region=None, key=None, keyid=None, profile=None): ''' Update the password policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_account_password_policy True ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.update_account_password_policy(allow_users_to_change_password, hard_expiry, max_password_age, minimum_password_length, password_reuse_prevention, require_lowercase_characters, require_numbers, require_symbols, require_uppercase_characters) log.info('The password policy has been updated.') return True except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy' log.error(msg) return False def get_account_policy(region=None, key=None, keyid=None, profile=None): ''' Get account policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_account_password_policy() return info.get_account_password_policy_response.get_account_password_policy_result.password_policy except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy.' log.error(msg) return False def create_role(name, policy_document=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Create an instance role. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if role_exists(name, region, key, keyid, profile): return True if not policy_document: policy_document = None try: conn.create_role(name, assume_role_policy_document=policy_document, path=path) log.info('Created IAM role %s.', name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to create IAM role %s.', name) return False def delete_role(name, region=None, key=None, keyid=None, profile=None): ''' Delete an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(name, region, key, keyid, profile): return True try: conn.delete_role(name) log.info('Deleted %s IAM role.', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s IAM role.', name) return False def profile_associated(role_name, profile_name, region, key, keyid, profile): ''' Check to see if an instance profile is associated with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.profile_associated myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # The IAM module of boto doesn't return objects. Instead you need to grab # values through its properties. Sigh. try: profiles = conn.list_instance_profiles_for_role(role_name) except boto.exception.BotoServerError as e: log.debug(e) return False profiles = profiles.list_instance_profiles_for_role_response profiles = profiles.list_instance_profiles_for_role_result profiles = profiles.instance_profiles for profile in profiles: if profile.instance_profile_name == profile_name: return True return False def associate_profile_to_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Associate an instance profile with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.associate_profile_to_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if associated: return True else: try: conn.add_role_to_instance_profile(profile_name, role_name) log.info('Added %s instance profile to IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add %s instance profile to IAM role %s', profile_name, role_name) return False def disassociate_profile_from_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Disassociate an instance profile from an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.disassociate_profile_from_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if not associated: return True else: try: conn.remove_role_from_instance_profile(profile_name, role_name) log.info('Removed %s instance profile from IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove %s instance profile from IAM role %s.', profile_name, role_name) return False def list_role_policies(role_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_role_policies myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_role_policies(role_name) _list = response.list_role_policies_response.list_role_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def get_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.get_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: _policy = conn.get_role_policy(role_name, policy_name) # I _hate_ you for not giving me an object boto. _policy = _policy.get_role_policy_response.policy_document # Policy is url encoded _policy = _unquote(_policy) _policy = salt.utils.json.loads(_policy, object_pairs_hook=odict.OrderedDict) return _policy except boto.exception.BotoServerError: return {} def create_role_policy(role_name, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Create or modify a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role_policy myirole mypolicy '{"MyPolicy": "Statement": [{"Action": ["sqs:*"], "Effect": "Allow", "Resource": ["arn:aws:sqs:*:*:*"], "Sid": "MyPolicySqs1"}]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) mode = 'create' if _policy: if _policy == policy: return True mode = 'modify' if isinstance(policy, six.string_types): policy = salt.utils.json.loads(policy, object_pairs_hook=odict.OrderedDict) try: _policy = salt.utils.json.dumps(policy) conn.put_role_policy(role_name, policy_name, _policy) if mode == 'create': msg = 'Successfully added policy %s to IAM role %s.' else: msg = 'Successfully modified policy %s for IAM role %s.' log.info(msg, policy_name, role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to %s policy %s for IAM role %s.', mode, policy_name, role_name) return False def delete_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) if not _policy: return True try: conn.delete_role_policy(role_name, policy_name) log.info('Successfully deleted policy %s for IAM role %s.', policy_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM role %s.', policy_name, role_name) return False def update_assume_role_policy(role_name, policy_document, region=None, key=None, keyid=None, profile=None): ''' Update an assume role policy for a role. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_assume_role_policy myrole '{"Statement":"..."}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(policy_document, six.string_types): policy_document = salt.utils.json.loads(policy_document, object_pairs_hook=odict.OrderedDict) try: _policy_document = salt.utils.json.dumps(policy_document) conn.update_assume_role_policy(role_name, _policy_document) log.info('Successfully updated assume role policy for IAM role %s.', role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to update assume role policy for IAM role %s.', role_name) return False def build_policy(region=None, key=None, keyid=None, profile=None): ''' Build a default assume role policy. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.build_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if hasattr(conn, 'build_policy'): policy = salt.utils.json.loads(conn.build_policy()) elif hasattr(conn, '_build_policy'): policy = salt.utils.json.loads(conn._build_policy()) else: return {} # The format we get from build_policy isn't going to be what we get back # from AWS for the exact same policy. AWS converts single item list values # into strings, so let's do the same here. for key, policy_val in policy.items(): for statement in policy_val: if (isinstance(statement['Action'], list) and len(statement['Action']) == 1): statement['Action'] = statement['Action'][0] if (isinstance(statement['Principal']['Service'], list) and len(statement['Principal']['Service']) == 1): statement['Principal']['Service'] = statement['Principal']['Service'][0] # build_policy doesn't add a version field, which AWS is going to set to a # default value, when we get it back, so let's set it. policy['Version'] = '2008-10-17' return policy def get_account_id(region=None, key=None, keyid=None, profile=None): ''' Get a the AWS account id associated with the used credentials. CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_id ''' cache_key = 'boto_iam.account_id' if cache_key not in __context__: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_user() # The get_user call returns an user ARN: # arn:aws:iam::027050522557:user/salt-test arn = ret['get_user_response']['get_user_result']['user']['arn'] account_id = arn.split(':')[4] except boto.exception.BotoServerError: # If call failed, then let's try to get the ARN from the metadata timeout = boto.config.getfloat( 'Boto', 'metadata_service_timeout', 1.0 ) attempts = boto.config.getint( 'Boto', 'metadata_service_num_attempts', 1 ) identity = boto.utils.get_instance_identity( timeout=timeout, num_retries=attempts ) try: account_id = identity['document']['accountId'] except KeyError: log.error('Failed to get account id from instance_identity in' ' boto_iam.get_account_id.') __context__[cache_key] = account_id return __context__[cache_key] def get_all_roles(path_prefix=None, region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM role details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_roles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _roles = conn.list_roles(path_prefix=path_prefix) roles = _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) while marker: _roles = conn.list_roles(path_prefix=path_prefix, marker=marker) roles = roles + _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) return roles def get_all_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM user details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_users ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _users = conn.get_all_users(path_prefix=path_prefix) users = _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) while marker: _users = conn.get_all_users(path_prefix=path_prefix, marker=marker) users = users + _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) return users def get_all_user_policies(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all user policies. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_user_policies myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_all_user_policies(user_name, marker, max_items) if not info: return False _list = info.list_user_policies_response.list_user_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policies for user %s.', user_name) return False def get_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user_policy myuser mypolicyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user_policy(user_name, policy_name) log.debug('Info for IAM user %s policy %s: %s.', user_name, policy_name, info) if not info: return False info = info.get_user_policy_response.get_user_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policy %s for IAM user %s.', policy_name, user_name) return False def put_user_policy(user_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_user_policy myuser policyname policyrules ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_user_policy(user_name, policy_name, policy_json) if created: log.info('Created policy %s for IAM user %s.', policy_name, user_name) return True log.error('Could not create policy %s for IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy %s for IAM user %s.', policy_name, user_name) return False def delete_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user_policy myuser mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_user_policy( user_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_user_policy(user_name, policy_name) log.info('Successfully deleted policy %s for IAM user %s.', policy_name, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM user %s.', policy_name, user_name) return False def upload_server_cert(cert_name, cert_body, private_key, cert_chain=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Upload a certificate to Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.upload_server_cert mycert_name crt priv_key :param cert_name: The name for the server certificate. Do not include the path in this value. :param cert_body: The contents of the public key certificate in PEM-encoded format. :param private_key: The contents of the private key in PEM-encoded format. :param cert_chain: The contents of the certificate chain. This is typically a concatenation of the PEM-encoded public key certificates of the chain. :param path: The path for the server certificate. :param region: The name of the region to connect to. :param key: The key to be used in order to connect :param keyid: The keyid to be used in order to connect :param profile: The profile that contains a dict of region, key, keyid :return: True / False ''' exists = get_server_certificate(cert_name, region, key, keyid, profile) if exists: return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.upload_server_cert(cert_name, cert_body, private_key, cert_chain) log.info('Created certificate %s.', cert_name) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to failed to create certificate %s.', cert_name) return False def list_server_certificates(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Lists the server certificates stored in IAM that have the specified path prefix. .. versionadded:: ??? :param path_prefix: The path prefix for filtering the results. For example: /company/servercerts would get all server certificates for which the path starts with /company/servercerts . This parameter is optional. If it is not included, it defaults to a slash (/), listing all server certificates. This parameter allows (per its regex pattern) a string of characters consisting of either a forward slash (/) by itself or a string that must begin and end with forward slashes. In addition, it can contain any ASCII character from the ! (u0021) through the DEL character (u007F), including most punctuation characters, digits, and upper and lowercased letters. CLI Example: .. code-block:: bash salt myminion boto_iam.list_server_certificates path_prefix=/somepath/ ''' retries = 10 sleep = 6 conn = __utils__['boto3.get_connection']('iam', region=region, key=key, keyid=keyid, profile=profile) Items = [] while retries: try: log.debug('Garnering list of IAM Server Certificates') IsTruncated = True while IsTruncated: kwargs = {'PathPrefix': path_prefix} ret = conn.list_server_certificates(**kwargs) Items += ret.get('ServerCertificateMetadataList', []) IsTruncated = ret.get('IsTruncated') kwargs.update({'Marker': ret.get('Marker')}) return Items except botocore.exceptions.ParamValidationError as err: raise SaltInvocationError(str(err)) except botocore.exceptions.ClientError as err: if retries and jmespath.search('Error.Code', err.response) == 'Throttling': retries -= 1 log.debug('Throttled by AWS API, retrying in %s seconds...', sleep) time.sleep(sleep) continue log.error('Failed to list IAM Server Certificates: %s', err.message) return None def get_server_certificate(cert_name, region=None, key=None, keyid=None, profile=None): ''' Returns certificate information from Amazon .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_server_certificate mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_server_certificate(cert_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get certificate %s information.', cert_name) return False def delete_server_cert(cert_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a certificate from Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_server_cert mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_server_cert(cert_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete certificate %s.', cert_name) return False def export_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM user details. Produces results that can be used to create an sls file. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.export_users --out=txt | sed "s/local: //" > iam_users.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() users = get_all_users(path_prefix, region, key, keyid, profile) for user in users: name = user.user_name _policies = conn.get_all_user_policies(name, max_items=100) _policies = _policies.list_user_policies_response.list_user_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_user_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_user_policy_response.get_user_policy_result.policy_document )) policies[policy_name] = _policy user_sls = [] user_sls.append({"name": name}) user_sls.append({"policies": policies}) user_sls.append({"path": user.path}) results["manage user " + name] = {"boto_iam.user_present": user_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def export_roles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM role details. Produces results that can be used to create an sls file. CLI Example: salt-call boto_iam.export_roles --out=txt | sed "s/local: //" > iam_roles.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() roles = get_all_roles(path_prefix, region, key, keyid, profile) for role in roles: name = role.role_name _policies = conn.list_role_policies(name, max_items=100) _policies = _policies.list_role_policies_response.list_role_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_role_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_role_policy_response.get_role_policy_result.policy_document )) policies[policy_name] = _policy role_sls = [] role_sls.append({"name": name}) role_sls.append({"policies": policies}) role_sls.append({'policy_document': salt.utils.json.loads(_unquote(role.assume_role_policy_document))}) role_sls.append({"path": role.path}) results["manage role " + name] = {"boto_iam_role.present": role_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def _get_policy_arn(name, region=None, key=None, keyid=None, profile=None): if name.startswith('arn:aws:iam:'): return name account_id = get_account_id( region=region, key=key, keyid=keyid, profile=profile ) return 'arn:aws:iam::{0}:policy/{1}'.format(account_id, name) def policy_exists(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return True except boto.exception.BotoServerError: return False def get_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return ret.get('get_policy_response', {}).get('get_policy_result', {}) except boto.exception.BotoServerError: return None def create_policy(policy_name, policy_document, path=None, description=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in 'path', 'description': if locals()[arg] is not None: params[arg] = locals()[arg] if policy_exists(policy_name, region, key, keyid, profile): return True try: conn.create_policy(policy_name, policy_document, **params) log.info('Created IAM policy %s.', policy_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s.', policy_name) return False return True def delete_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_exists(policy_arn, region, key, keyid, profile): return True try: conn.delete_policy(policy_arn) log.info('Deleted %s policy.', policy_name) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete %s policy: %s.', policy_name, aws.get('message')) return False return True def list_policies(region=None, key=None, keyid=None, profile=None): ''' List policies. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policies ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: policies = [] for ret in __utils__['boto.paged_call'](conn.list_policies): policies.append(ret.get('list_policies_response', {}).get('list_policies_result', {}).get('policies')) return policies except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to list policy versions.' log.error(msg) return [] def policy_version_exists(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.get_policy_version(policy_arn, version_id) return True except boto.exception.BotoServerError: return False def get_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy_version(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile), version_id) retval = ret.get('get_policy_version_response', {}).get('get_policy_version_result', {}).get('policy_version', {}) retval['document'] = _unquote(retval.get('document')) return {'policy_version': retval} except boto.exception.BotoServerError: return None def create_policy_version(policy_name, policy_document, set_as_default=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy version. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy_version mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in ('set_as_default',): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.create_policy_version(policy_arn, policy_document, **params) vid = ret.get('create_policy_version_response', {}).get('create_policy_version_result', {}).get('policy_version', {}).get('version_id') log.info('Created IAM policy %s version %s.', policy_name, vid) return {'created': True, 'version_id': vid} except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s version %s.', policy_name, vid) return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Delete a policy version. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_version_exists(policy_arn, version_id, region, key, keyid, profile): return True try: conn.delete_policy_version(policy_arn, version_id) log.info('Deleted IAM policy %s version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete IAM policy %s version %s: %s', policy_name, version_id, aws.get('message')) return False return True def list_policy_versions(policy_name, region=None, key=None, keyid=None, profile=None): ''' List versions of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policy_versions mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.list_policy_versions(policy_arn) return ret.get('list_policy_versions_response', {}).get('list_policy_versions_result', {}).get('versions') except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list versions for IAM policy %s.', policy_name) return [] def set_default_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Set the default version of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.set_default_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.set_default_policy_version(policy_arn, version_id) log.info('Set %s policy to version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to set %s policy to version %s: %s', policy_name, version_id, aws.get('message')) return False return True def attach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_user_policy(policy_arn, user_name) log.info('Attached policy %s to IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach %s policy to IAM user %s.', policy_name, user_name) return False return True def detach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_user_policy(policy_arn, user_name) log.info('Detached %s policy from IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach %s policy from IAM user %s.', policy_name, user_name) return False return True def attach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_group_policy(policy_arn, group_name) log.info('Attached policy %s to IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM group %s.', policy_name, group_name) return False return True def detach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_group_policy(policy_arn, group_name) log.info('Detached policy %s from IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM group %s.', policy_name, group_name) return False return True def attach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_role_policy(policy_arn, role_name) log.info('Attached policy %s to IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM role %s.', policy_name, role_name) return False return True def detach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_role_policy(policy_arn, role_name) log.info('Detached policy %s from IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM role %s.', policy_name, role_name) return False return True def list_entities_for_policy(policy_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities that a policy is attached to. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 params = {} for arg in ('path_prefix', 'entity_filter'): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) while retries: try: allret = { 'policy_groups': [], 'policy_users': [], 'policy_roles': [], } for ret in __utils__['boto.paged_call'](conn.list_entities_for_policy, policy_arn=policy_arn, **params): for k, v in six.iteritems(allret): v.extend(ret.get('list_entities_for_policy_response', {}).get('list_entities_for_policy_result', {}).get(k)) return allret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('Failed to list entities for IAM policy %s: %s', policy_name, e.message) return {} return {} def list_attached_user_policies(user_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given user. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'UserName': user_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedUserPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_user_policies_response', {}).get('list_attached_user_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM user %s.', user_name) return [] def list_attached_group_policies(group_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given group. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'GroupName': group_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedGroupPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_group_policies_response', {}).get('list_attached_group_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM group %s.', group_name) return [] def list_attached_role_policies(role_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'RoleName': role_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedRolePolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_role_policies_response', {}).get('list_attached_role_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM role %s.', role_name) return [] def create_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Create SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.create_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_saml_provider(saml_metadata_document, name) log.info('Successfully created %s SAML provider.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to create SAML provider %s.', name) return False def get_saml_provider_arn(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider_arn my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_saml_providers() for saml_provider in response.list_saml_providers_response.list_saml_providers_result.saml_provider_list: if saml_provider['arn'].endswith(':saml-provider/' + name): return saml_provider['arn'] return False except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to get ARN of SAML provider %s.', name) return False def list_saml_providers(region=None, key=None, keyid=None, profile=None): ''' List SAML providers. CLI Example: .. code-block:: bash salt myminion boto_iam.list_saml_providers ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: providers = [] info = conn.list_saml_providers() for arn in info['list_saml_providers_response']['list_saml_providers_result']['saml_provider_list']: providers.append(arn['arn'].rsplit('/', 1)[1]) return providers except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get list of SAML providers.') return False def get_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider document. CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider arn ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: provider = conn.get_saml_provider(name) return provider['get_saml_provider_response']['get_saml_provider_result']['saml_metadata_document'] except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get SAML provider document %s.', name) return False def update_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Update SAML provider. CLI Example: .. code-block:: bash salt myminion boto_iam.update_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return False if conn.update_saml_provider(name, saml_metadata_document): return True return False except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to update SAML provider %s.', name) return False
saltstack/salt
salt/modules/boto_iam.py
list_saml_providers
python
def list_saml_providers(region=None, key=None, keyid=None, profile=None): ''' List SAML providers. CLI Example: .. code-block:: bash salt myminion boto_iam.list_saml_providers ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: providers = [] info = conn.list_saml_providers() for arn in info['list_saml_providers_response']['list_saml_providers_result']['saml_provider_list']: providers.append(arn['arn'].rsplit('/', 1)[1]) return providers except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get list of SAML providers.') return False
List SAML providers. CLI Example: .. code-block:: bash salt myminion boto_iam.list_saml_providers
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iam.py#L2333-L2353
null
# -*- coding: utf-8 -*- ''' Connection module for Amazon IAM .. versionadded:: 2014.7.0 :configuration: This module accepts explicit iam 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 iam.keyid: GKTADJGHEIQSXMKKRBJ08H iam.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs iam.region: 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: boto ''' # keep lint from choking on _get_conn and _cache_id #pylint: disable=E0602 # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import salt libs from salt.ext import six import salt.utils.compat import salt.utils.json import salt.utils.odict as odict import salt.utils.versions from salt.exceptions import SaltInvocationError # Import third party libs # pylint: disable=unused-import from salt.ext.six.moves.urllib.parse import unquote as _unquote # pylint: disable=no-name-in-module try: import boto import boto.iam import boto3 import botocore logging.getLogger('boto').setLevel(logging.CRITICAL) logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=unused-import log = logging.getLogger(__name__) def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'iam', pack=__salt__) def instance_profile_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an instance profile exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: # Boto weirdly returns an exception here if an instance profile doesn't # exist. conn.get_instance_profile(name) return True except boto.exception.BotoServerError: return False def create_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Create an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.create_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if instance_profile_exists(name, region, key, keyid, profile): return True try: # This call returns an instance profile if successful and an exception # if not. It's annoying. conn.create_instance_profile(name) log.info('Created %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create %s instance profile.', name) return False return True def delete_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Delete an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not instance_profile_exists(name, region, key, keyid, profile): return True try: conn.delete_instance_profile(name) log.info('Deleted %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s instance profile.', name) return False return True def role_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an IAM role exists. CLI Example: .. code-block:: bash salt myminion boto_iam.role_exists myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_role(name) return True except boto.exception.BotoServerError: return False def describe_role(name, region=None, key=None, keyid=None, profile=None): ''' Get information for a role. CLI Example: .. code-block:: bash salt myminion boto_iam.describe_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_role(name) if not info: return False role = info.get_role_response.get_role_result.role role['assume_role_policy_document'] = salt.utils.json.loads(_unquote( role.assume_role_policy_document )) # If Sid wasn't defined by the user, boto will still return a Sid in # each policy. To properly check idempotently, let's remove the Sid # from the return if it's not actually set. for policy_key, policy in role['assume_role_policy_document'].items(): if policy_key == 'Statement': for val in policy: if 'Sid' in val and not val['Sid']: del val['Sid'] return role except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get %s information.', name) return False def create_user(user_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_user myuser ''' if not path: path = '/' if get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_user(user_name, path) log.info('Created IAM user : %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM user %s.', user_name) return False def get_all_access_keys(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all access keys from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_access_keys myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.get_all_access_keys(user_name, marker, max_items) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get access keys for IAM user %s.', user_name) return six.text_type(e) def create_access_key(user_name, region=None, key=None, keyid=None, profile=None): ''' Create access key id for a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.create_access_key(user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create access key.') return six.text_type(e) def delete_access_key(access_key_id, user_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete access key id from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_access_key(access_key_id, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete access key id %s.', access_key_id) return six.text_type(e) def delete_user(user_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user myuser ''' if not get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.delete_user(user_name) log.info('Deleted IAM user : %s .', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM user %s', user_name) return six.text_type(e) def get_user(user_name=None, region=None, key=None, keyid=None, profile=None): ''' Get user information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user(user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM user %s info.', user_name) return False def create_group(group_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_group group ''' if not path: path = '/' if get_group(group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_group(group_name, path) log.info('Created IAM group : %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM group %s.', group_name) return False def get_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group(group_name, max_items=1) if not info: return False return info['get_group_response']['get_group_result']['group'] except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_group_members(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: marker = None truncated = True users = [] while truncated: info = conn.get_group(group_name, marker=marker, max_items=1000) if not info: return False truncated = bool(info['get_group_response']['get_group_result']['is_truncated']) if truncated and 'marker' in info['get_group_response']['get_group_result']: marker = info['get_group_response']['get_group_result']['marker'] else: marker = None truncated = False users += info['get_group_response']['get_group_result']['users'] return users except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get members for IAM group %s.', group_name) return False def add_user_to_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Add user to group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.add_user_to_group myuser mygroup ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('Username : %s does not exist.', user_name) return False if user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.add_user_to_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add IAM user %s to group %s.', user_name, group_name) return False def user_exists_in_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Check if user exists in group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.user_exists_in_group myuser mygroup ''' # TODO this should probably use boto.iam.get_groups_for_user users = get_group_members( group_name=group_name, region=region, key=key, keyid=keyid, profile=profile ) if users: for _user in users: if user_name == _user['user_name']: log.debug('IAM user %s is already in IAM group %s.', user_name, group_name) return True return False def remove_user_from_group(group_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Remove user from group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.remove_user_from_group mygroup myuser ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist.', user_name) return False if not user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.remove_user_from_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove IAM user %s from group %s', user_name, group_name) return False def put_group_policy(group_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_group_policy mygroup policyname policyrules ''' group = get_group(group_name, region=region, key=key, keyid=keyid, profile=profile) if not group: log.error('Group %s does not exist', group_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_group_policy(group_name, policy_name, policy_json) if created: log.info('Created policy for IAM group %s.', group_name) return True log.error('Could not create policy for IAM group %s', group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy for IAM group %s', group_name) return False def delete_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group_policy mygroup mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_group_policy( group_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_group_policy(group_name, policy_name) log.info('Successfully deleted policy %s for IAM group %s.', policy_name, group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM group %s.', policy_name, group_name) return False def get_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group_policy mygroup policyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group_policy(group_name, policy_name) log.debug('info for group policy is : %s', info) if not info: return False info = info.get_group_policy_response.get_group_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_all_groups(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM group details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_groups ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _groups = conn.get_all_groups(path_prefix=path_prefix) groups = _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) while marker: _groups = conn.get_all_groups(path_prefix=path_prefix, marker=marker) groups = groups + _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) return groups def get_all_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.get_all_instance_profiles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) marker = False profiles = [] while marker is not None: marker = marker if marker else None p = conn.list_instance_profiles(path_prefix=path_prefix, marker=marker) res = p.list_instance_profiles_response.list_instance_profiles_result profiles += res.instance_profiles marker = getattr(res, 'marker', None) return profiles def list_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' List all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.list_instance_profiles ''' p = get_all_instance_profiles(path_prefix, region, key, keyid, profile) return [i['instance_profile_name'] for i in p] def get_all_group_policies(group_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a group. CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_group_policies mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False try: response = conn.get_all_group_policies(group_name) _list = response.list_group_policies_response.list_group_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def delete_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _group = get_group( group_name, region, key, keyid, profile ) if not _group: return True try: conn.delete_group(group_name) log.info('Successfully deleted IAM group %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM group %s.', group_name) return False def create_login_profile(user_name, password, region=None, key=None, keyid=None, profile=None): ''' Creates a login profile for the specified user, give the user the ability to access AWS services and the AWS Management Console. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_login_profile user_name password ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.create_login_profile(user_name, password) log.info('Created profile for IAM user %s.', user_name) return info except boto.exception.BotoServerError as e: log.debug(e) if 'Conflict' in e: log.info('Profile already exists for IAM user %s.', user_name) return 'Conflict' log.error('Failed to update profile for IAM user %s.', user_name) return False def delete_login_profile(user_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a login profile for the specified user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_login_profile user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.delete_login_profile(user_name) log.info('Deleted login profile for IAM user %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Login profile already deleted for IAM user %s.', user_name) return True log.error('Failed to delete login profile for IAM user %s.', user_name) return False def get_all_mfa_devices(user_name, region=None, key=None, keyid=None, profile=None): ''' Get all MFA devices associated with an IAM user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_mfa_devices user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: result = conn.get_all_mfa_devices(user_name) devices = result['list_mfa_devices_response']['list_mfa_devices_result']['mfa_devices'] return devices except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Could not find IAM user %s.', user_name) return [] log.error('Failed to get all MFA devices for IAM user %s.', user_name) return False def deactivate_mfa_device(user_name, serial, region=None, key=None, keyid=None, profile=None): ''' Deactivates the specified MFA device and removes it from association with the user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.deactivate_mfa_device user_name serial_num ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.deactivate_mfa_device(user_name, serial) log.info('Deactivated MFA device %s for IAM user %s.', serial, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('MFA device %s not associated with IAM user %s.', serial, user_name) return True log.error('Failed to deactivate MFA device %s for IAM user %s.', serial, user_name) return False def delete_virtual_mfa_device(serial, region=None, key=None, keyid=None, profile=None): ''' Deletes the specified virtual MFA device. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_virtual_mfa_device serial_num ''' conn = __utils__['boto3.get_connection_func']('iam')() try: conn.delete_virtual_mfa_device(SerialNumber=serial) log.info('Deleted virtual MFA device %s.', serial) return True except botocore.exceptions.ClientError as e: log.debug(e) if 'NoSuchEntity' in six.text_type(e): log.info('Virtual MFA device %s not found.', serial) return True log.error('Failed to delete virtual MFA device %s.', serial) return False def update_account_password_policy(allow_users_to_change_password=None, hard_expiry=None, max_password_age=None, minimum_password_length=None, password_reuse_prevention=None, require_lowercase_characters=None, require_numbers=None, require_symbols=None, require_uppercase_characters=None, region=None, key=None, keyid=None, profile=None): ''' Update the password policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_account_password_policy True ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.update_account_password_policy(allow_users_to_change_password, hard_expiry, max_password_age, minimum_password_length, password_reuse_prevention, require_lowercase_characters, require_numbers, require_symbols, require_uppercase_characters) log.info('The password policy has been updated.') return True except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy' log.error(msg) return False def get_account_policy(region=None, key=None, keyid=None, profile=None): ''' Get account policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_account_password_policy() return info.get_account_password_policy_response.get_account_password_policy_result.password_policy except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy.' log.error(msg) return False def create_role(name, policy_document=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Create an instance role. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if role_exists(name, region, key, keyid, profile): return True if not policy_document: policy_document = None try: conn.create_role(name, assume_role_policy_document=policy_document, path=path) log.info('Created IAM role %s.', name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to create IAM role %s.', name) return False def delete_role(name, region=None, key=None, keyid=None, profile=None): ''' Delete an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(name, region, key, keyid, profile): return True try: conn.delete_role(name) log.info('Deleted %s IAM role.', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s IAM role.', name) return False def profile_associated(role_name, profile_name, region, key, keyid, profile): ''' Check to see if an instance profile is associated with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.profile_associated myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # The IAM module of boto doesn't return objects. Instead you need to grab # values through its properties. Sigh. try: profiles = conn.list_instance_profiles_for_role(role_name) except boto.exception.BotoServerError as e: log.debug(e) return False profiles = profiles.list_instance_profiles_for_role_response profiles = profiles.list_instance_profiles_for_role_result profiles = profiles.instance_profiles for profile in profiles: if profile.instance_profile_name == profile_name: return True return False def associate_profile_to_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Associate an instance profile with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.associate_profile_to_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if associated: return True else: try: conn.add_role_to_instance_profile(profile_name, role_name) log.info('Added %s instance profile to IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add %s instance profile to IAM role %s', profile_name, role_name) return False def disassociate_profile_from_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Disassociate an instance profile from an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.disassociate_profile_from_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if not associated: return True else: try: conn.remove_role_from_instance_profile(profile_name, role_name) log.info('Removed %s instance profile from IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove %s instance profile from IAM role %s.', profile_name, role_name) return False def list_role_policies(role_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_role_policies myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_role_policies(role_name) _list = response.list_role_policies_response.list_role_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def get_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.get_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: _policy = conn.get_role_policy(role_name, policy_name) # I _hate_ you for not giving me an object boto. _policy = _policy.get_role_policy_response.policy_document # Policy is url encoded _policy = _unquote(_policy) _policy = salt.utils.json.loads(_policy, object_pairs_hook=odict.OrderedDict) return _policy except boto.exception.BotoServerError: return {} def create_role_policy(role_name, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Create or modify a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role_policy myirole mypolicy '{"MyPolicy": "Statement": [{"Action": ["sqs:*"], "Effect": "Allow", "Resource": ["arn:aws:sqs:*:*:*"], "Sid": "MyPolicySqs1"}]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) mode = 'create' if _policy: if _policy == policy: return True mode = 'modify' if isinstance(policy, six.string_types): policy = salt.utils.json.loads(policy, object_pairs_hook=odict.OrderedDict) try: _policy = salt.utils.json.dumps(policy) conn.put_role_policy(role_name, policy_name, _policy) if mode == 'create': msg = 'Successfully added policy %s to IAM role %s.' else: msg = 'Successfully modified policy %s for IAM role %s.' log.info(msg, policy_name, role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to %s policy %s for IAM role %s.', mode, policy_name, role_name) return False def delete_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) if not _policy: return True try: conn.delete_role_policy(role_name, policy_name) log.info('Successfully deleted policy %s for IAM role %s.', policy_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM role %s.', policy_name, role_name) return False def update_assume_role_policy(role_name, policy_document, region=None, key=None, keyid=None, profile=None): ''' Update an assume role policy for a role. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_assume_role_policy myrole '{"Statement":"..."}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(policy_document, six.string_types): policy_document = salt.utils.json.loads(policy_document, object_pairs_hook=odict.OrderedDict) try: _policy_document = salt.utils.json.dumps(policy_document) conn.update_assume_role_policy(role_name, _policy_document) log.info('Successfully updated assume role policy for IAM role %s.', role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to update assume role policy for IAM role %s.', role_name) return False def build_policy(region=None, key=None, keyid=None, profile=None): ''' Build a default assume role policy. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.build_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if hasattr(conn, 'build_policy'): policy = salt.utils.json.loads(conn.build_policy()) elif hasattr(conn, '_build_policy'): policy = salt.utils.json.loads(conn._build_policy()) else: return {} # The format we get from build_policy isn't going to be what we get back # from AWS for the exact same policy. AWS converts single item list values # into strings, so let's do the same here. for key, policy_val in policy.items(): for statement in policy_val: if (isinstance(statement['Action'], list) and len(statement['Action']) == 1): statement['Action'] = statement['Action'][0] if (isinstance(statement['Principal']['Service'], list) and len(statement['Principal']['Service']) == 1): statement['Principal']['Service'] = statement['Principal']['Service'][0] # build_policy doesn't add a version field, which AWS is going to set to a # default value, when we get it back, so let's set it. policy['Version'] = '2008-10-17' return policy def get_account_id(region=None, key=None, keyid=None, profile=None): ''' Get a the AWS account id associated with the used credentials. CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_id ''' cache_key = 'boto_iam.account_id' if cache_key not in __context__: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_user() # The get_user call returns an user ARN: # arn:aws:iam::027050522557:user/salt-test arn = ret['get_user_response']['get_user_result']['user']['arn'] account_id = arn.split(':')[4] except boto.exception.BotoServerError: # If call failed, then let's try to get the ARN from the metadata timeout = boto.config.getfloat( 'Boto', 'metadata_service_timeout', 1.0 ) attempts = boto.config.getint( 'Boto', 'metadata_service_num_attempts', 1 ) identity = boto.utils.get_instance_identity( timeout=timeout, num_retries=attempts ) try: account_id = identity['document']['accountId'] except KeyError: log.error('Failed to get account id from instance_identity in' ' boto_iam.get_account_id.') __context__[cache_key] = account_id return __context__[cache_key] def get_all_roles(path_prefix=None, region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM role details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_roles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _roles = conn.list_roles(path_prefix=path_prefix) roles = _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) while marker: _roles = conn.list_roles(path_prefix=path_prefix, marker=marker) roles = roles + _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) return roles def get_all_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM user details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_users ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _users = conn.get_all_users(path_prefix=path_prefix) users = _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) while marker: _users = conn.get_all_users(path_prefix=path_prefix, marker=marker) users = users + _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) return users def get_all_user_policies(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all user policies. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_user_policies myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_all_user_policies(user_name, marker, max_items) if not info: return False _list = info.list_user_policies_response.list_user_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policies for user %s.', user_name) return False def get_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user_policy myuser mypolicyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user_policy(user_name, policy_name) log.debug('Info for IAM user %s policy %s: %s.', user_name, policy_name, info) if not info: return False info = info.get_user_policy_response.get_user_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policy %s for IAM user %s.', policy_name, user_name) return False def put_user_policy(user_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_user_policy myuser policyname policyrules ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_user_policy(user_name, policy_name, policy_json) if created: log.info('Created policy %s for IAM user %s.', policy_name, user_name) return True log.error('Could not create policy %s for IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy %s for IAM user %s.', policy_name, user_name) return False def delete_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user_policy myuser mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_user_policy( user_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_user_policy(user_name, policy_name) log.info('Successfully deleted policy %s for IAM user %s.', policy_name, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM user %s.', policy_name, user_name) return False def upload_server_cert(cert_name, cert_body, private_key, cert_chain=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Upload a certificate to Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.upload_server_cert mycert_name crt priv_key :param cert_name: The name for the server certificate. Do not include the path in this value. :param cert_body: The contents of the public key certificate in PEM-encoded format. :param private_key: The contents of the private key in PEM-encoded format. :param cert_chain: The contents of the certificate chain. This is typically a concatenation of the PEM-encoded public key certificates of the chain. :param path: The path for the server certificate. :param region: The name of the region to connect to. :param key: The key to be used in order to connect :param keyid: The keyid to be used in order to connect :param profile: The profile that contains a dict of region, key, keyid :return: True / False ''' exists = get_server_certificate(cert_name, region, key, keyid, profile) if exists: return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.upload_server_cert(cert_name, cert_body, private_key, cert_chain) log.info('Created certificate %s.', cert_name) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to failed to create certificate %s.', cert_name) return False def list_server_certificates(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Lists the server certificates stored in IAM that have the specified path prefix. .. versionadded:: ??? :param path_prefix: The path prefix for filtering the results. For example: /company/servercerts would get all server certificates for which the path starts with /company/servercerts . This parameter is optional. If it is not included, it defaults to a slash (/), listing all server certificates. This parameter allows (per its regex pattern) a string of characters consisting of either a forward slash (/) by itself or a string that must begin and end with forward slashes. In addition, it can contain any ASCII character from the ! (u0021) through the DEL character (u007F), including most punctuation characters, digits, and upper and lowercased letters. CLI Example: .. code-block:: bash salt myminion boto_iam.list_server_certificates path_prefix=/somepath/ ''' retries = 10 sleep = 6 conn = __utils__['boto3.get_connection']('iam', region=region, key=key, keyid=keyid, profile=profile) Items = [] while retries: try: log.debug('Garnering list of IAM Server Certificates') IsTruncated = True while IsTruncated: kwargs = {'PathPrefix': path_prefix} ret = conn.list_server_certificates(**kwargs) Items += ret.get('ServerCertificateMetadataList', []) IsTruncated = ret.get('IsTruncated') kwargs.update({'Marker': ret.get('Marker')}) return Items except botocore.exceptions.ParamValidationError as err: raise SaltInvocationError(str(err)) except botocore.exceptions.ClientError as err: if retries and jmespath.search('Error.Code', err.response) == 'Throttling': retries -= 1 log.debug('Throttled by AWS API, retrying in %s seconds...', sleep) time.sleep(sleep) continue log.error('Failed to list IAM Server Certificates: %s', err.message) return None def get_server_certificate(cert_name, region=None, key=None, keyid=None, profile=None): ''' Returns certificate information from Amazon .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_server_certificate mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_server_certificate(cert_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get certificate %s information.', cert_name) return False def delete_server_cert(cert_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a certificate from Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_server_cert mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_server_cert(cert_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete certificate %s.', cert_name) return False def export_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM user details. Produces results that can be used to create an sls file. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.export_users --out=txt | sed "s/local: //" > iam_users.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() users = get_all_users(path_prefix, region, key, keyid, profile) for user in users: name = user.user_name _policies = conn.get_all_user_policies(name, max_items=100) _policies = _policies.list_user_policies_response.list_user_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_user_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_user_policy_response.get_user_policy_result.policy_document )) policies[policy_name] = _policy user_sls = [] user_sls.append({"name": name}) user_sls.append({"policies": policies}) user_sls.append({"path": user.path}) results["manage user " + name] = {"boto_iam.user_present": user_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def export_roles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM role details. Produces results that can be used to create an sls file. CLI Example: salt-call boto_iam.export_roles --out=txt | sed "s/local: //" > iam_roles.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() roles = get_all_roles(path_prefix, region, key, keyid, profile) for role in roles: name = role.role_name _policies = conn.list_role_policies(name, max_items=100) _policies = _policies.list_role_policies_response.list_role_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_role_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_role_policy_response.get_role_policy_result.policy_document )) policies[policy_name] = _policy role_sls = [] role_sls.append({"name": name}) role_sls.append({"policies": policies}) role_sls.append({'policy_document': salt.utils.json.loads(_unquote(role.assume_role_policy_document))}) role_sls.append({"path": role.path}) results["manage role " + name] = {"boto_iam_role.present": role_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def _get_policy_arn(name, region=None, key=None, keyid=None, profile=None): if name.startswith('arn:aws:iam:'): return name account_id = get_account_id( region=region, key=key, keyid=keyid, profile=profile ) return 'arn:aws:iam::{0}:policy/{1}'.format(account_id, name) def policy_exists(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return True except boto.exception.BotoServerError: return False def get_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return ret.get('get_policy_response', {}).get('get_policy_result', {}) except boto.exception.BotoServerError: return None def create_policy(policy_name, policy_document, path=None, description=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in 'path', 'description': if locals()[arg] is not None: params[arg] = locals()[arg] if policy_exists(policy_name, region, key, keyid, profile): return True try: conn.create_policy(policy_name, policy_document, **params) log.info('Created IAM policy %s.', policy_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s.', policy_name) return False return True def delete_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_exists(policy_arn, region, key, keyid, profile): return True try: conn.delete_policy(policy_arn) log.info('Deleted %s policy.', policy_name) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete %s policy: %s.', policy_name, aws.get('message')) return False return True def list_policies(region=None, key=None, keyid=None, profile=None): ''' List policies. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policies ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: policies = [] for ret in __utils__['boto.paged_call'](conn.list_policies): policies.append(ret.get('list_policies_response', {}).get('list_policies_result', {}).get('policies')) return policies except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to list policy versions.' log.error(msg) return [] def policy_version_exists(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.get_policy_version(policy_arn, version_id) return True except boto.exception.BotoServerError: return False def get_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy_version(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile), version_id) retval = ret.get('get_policy_version_response', {}).get('get_policy_version_result', {}).get('policy_version', {}) retval['document'] = _unquote(retval.get('document')) return {'policy_version': retval} except boto.exception.BotoServerError: return None def create_policy_version(policy_name, policy_document, set_as_default=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy version. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy_version mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in ('set_as_default',): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.create_policy_version(policy_arn, policy_document, **params) vid = ret.get('create_policy_version_response', {}).get('create_policy_version_result', {}).get('policy_version', {}).get('version_id') log.info('Created IAM policy %s version %s.', policy_name, vid) return {'created': True, 'version_id': vid} except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s version %s.', policy_name, vid) return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Delete a policy version. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_version_exists(policy_arn, version_id, region, key, keyid, profile): return True try: conn.delete_policy_version(policy_arn, version_id) log.info('Deleted IAM policy %s version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete IAM policy %s version %s: %s', policy_name, version_id, aws.get('message')) return False return True def list_policy_versions(policy_name, region=None, key=None, keyid=None, profile=None): ''' List versions of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policy_versions mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.list_policy_versions(policy_arn) return ret.get('list_policy_versions_response', {}).get('list_policy_versions_result', {}).get('versions') except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list versions for IAM policy %s.', policy_name) return [] def set_default_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Set the default version of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.set_default_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.set_default_policy_version(policy_arn, version_id) log.info('Set %s policy to version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to set %s policy to version %s: %s', policy_name, version_id, aws.get('message')) return False return True def attach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_user_policy(policy_arn, user_name) log.info('Attached policy %s to IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach %s policy to IAM user %s.', policy_name, user_name) return False return True def detach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_user_policy(policy_arn, user_name) log.info('Detached %s policy from IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach %s policy from IAM user %s.', policy_name, user_name) return False return True def attach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_group_policy(policy_arn, group_name) log.info('Attached policy %s to IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM group %s.', policy_name, group_name) return False return True def detach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_group_policy(policy_arn, group_name) log.info('Detached policy %s from IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM group %s.', policy_name, group_name) return False return True def attach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_role_policy(policy_arn, role_name) log.info('Attached policy %s to IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM role %s.', policy_name, role_name) return False return True def detach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_role_policy(policy_arn, role_name) log.info('Detached policy %s from IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM role %s.', policy_name, role_name) return False return True def list_entities_for_policy(policy_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities that a policy is attached to. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 params = {} for arg in ('path_prefix', 'entity_filter'): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) while retries: try: allret = { 'policy_groups': [], 'policy_users': [], 'policy_roles': [], } for ret in __utils__['boto.paged_call'](conn.list_entities_for_policy, policy_arn=policy_arn, **params): for k, v in six.iteritems(allret): v.extend(ret.get('list_entities_for_policy_response', {}).get('list_entities_for_policy_result', {}).get(k)) return allret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('Failed to list entities for IAM policy %s: %s', policy_name, e.message) return {} return {} def list_attached_user_policies(user_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given user. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'UserName': user_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedUserPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_user_policies_response', {}).get('list_attached_user_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM user %s.', user_name) return [] def list_attached_group_policies(group_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given group. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'GroupName': group_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedGroupPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_group_policies_response', {}).get('list_attached_group_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM group %s.', group_name) return [] def list_attached_role_policies(role_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'RoleName': role_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedRolePolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_role_policies_response', {}).get('list_attached_role_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM role %s.', role_name) return [] def create_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Create SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.create_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_saml_provider(saml_metadata_document, name) log.info('Successfully created %s SAML provider.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to create SAML provider %s.', name) return False def get_saml_provider_arn(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider_arn my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_saml_providers() for saml_provider in response.list_saml_providers_response.list_saml_providers_result.saml_provider_list: if saml_provider['arn'].endswith(':saml-provider/' + name): return saml_provider['arn'] return False except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to get ARN of SAML provider %s.', name) return False def delete_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Delete SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.delete_saml_provider my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return True conn.delete_saml_provider(saml_provider_arn) log.info('Successfully deleted SAML provider %s.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete SAML provider %s.', name) return False def get_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider document. CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider arn ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: provider = conn.get_saml_provider(name) return provider['get_saml_provider_response']['get_saml_provider_result']['saml_metadata_document'] except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get SAML provider document %s.', name) return False def update_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Update SAML provider. CLI Example: .. code-block:: bash salt myminion boto_iam.update_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return False if conn.update_saml_provider(name, saml_metadata_document): return True return False except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to update SAML provider %s.', name) return False
saltstack/salt
salt/modules/boto_iam.py
get_saml_provider
python
def get_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider document. CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider arn ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: provider = conn.get_saml_provider(name) return provider['get_saml_provider_response']['get_saml_provider_result']['saml_metadata_document'] except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get SAML provider document %s.', name) return False
Get SAML provider document. CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider arn
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iam.py#L2356-L2373
null
# -*- coding: utf-8 -*- ''' Connection module for Amazon IAM .. versionadded:: 2014.7.0 :configuration: This module accepts explicit iam 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 iam.keyid: GKTADJGHEIQSXMKKRBJ08H iam.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs iam.region: 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: boto ''' # keep lint from choking on _get_conn and _cache_id #pylint: disable=E0602 # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import time # Import salt libs from salt.ext import six import salt.utils.compat import salt.utils.json import salt.utils.odict as odict import salt.utils.versions from salt.exceptions import SaltInvocationError # Import third party libs # pylint: disable=unused-import from salt.ext.six.moves.urllib.parse import unquote as _unquote # pylint: disable=no-name-in-module try: import boto import boto.iam import boto3 import botocore logging.getLogger('boto').setLevel(logging.CRITICAL) logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False # pylint: enable=unused-import log = logging.getLogger(__name__) def __virtual__(): ''' Only load if boto libraries exist. ''' return salt.utils.versions.check_boto_reqs( check_boto3=False ) def __init__(opts): salt.utils.compat.pack_dunder(__name__) if HAS_BOTO: __utils__['boto.assign_funcs'](__name__, 'iam', pack=__salt__) def instance_profile_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an instance profile exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: # Boto weirdly returns an exception here if an instance profile doesn't # exist. conn.get_instance_profile(name) return True except boto.exception.BotoServerError: return False def create_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Create an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.create_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if instance_profile_exists(name, region, key, keyid, profile): return True try: # This call returns an instance profile if successful and an exception # if not. It's annoying. conn.create_instance_profile(name) log.info('Created %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create %s instance profile.', name) return False return True def delete_instance_profile(name, region=None, key=None, keyid=None, profile=None): ''' Delete an instance profile. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_instance_profile myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not instance_profile_exists(name, region, key, keyid, profile): return True try: conn.delete_instance_profile(name) log.info('Deleted %s instance profile.', name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s instance profile.', name) return False return True def role_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an IAM role exists. CLI Example: .. code-block:: bash salt myminion boto_iam.role_exists myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_role(name) return True except boto.exception.BotoServerError: return False def describe_role(name, region=None, key=None, keyid=None, profile=None): ''' Get information for a role. CLI Example: .. code-block:: bash salt myminion boto_iam.describe_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_role(name) if not info: return False role = info.get_role_response.get_role_result.role role['assume_role_policy_document'] = salt.utils.json.loads(_unquote( role.assume_role_policy_document )) # If Sid wasn't defined by the user, boto will still return a Sid in # each policy. To properly check idempotently, let's remove the Sid # from the return if it's not actually set. for policy_key, policy in role['assume_role_policy_document'].items(): if policy_key == 'Statement': for val in policy: if 'Sid' in val and not val['Sid']: del val['Sid'] return role except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get %s information.', name) return False def create_user(user_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_user myuser ''' if not path: path = '/' if get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_user(user_name, path) log.info('Created IAM user : %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM user %s.', user_name) return False def get_all_access_keys(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all access keys from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_access_keys myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.get_all_access_keys(user_name, marker, max_items) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get access keys for IAM user %s.', user_name) return six.text_type(e) def create_access_key(user_name, region=None, key=None, keyid=None, profile=None): ''' Create access key id for a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.create_access_key(user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create access key.') return six.text_type(e) def delete_access_key(access_key_id, user_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete access key id from a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_access_key myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_access_key(access_key_id, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete access key id %s.', access_key_id) return six.text_type(e) def delete_user(user_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user myuser ''' if not get_user(user_name, region, key, keyid, profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.delete_user(user_name) log.info('Deleted IAM user : %s .', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM user %s', user_name) return six.text_type(e) def get_user(user_name=None, region=None, key=None, keyid=None, profile=None): ''' Get user information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user(user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM user %s info.', user_name) return False def create_group(group_name, path=None, region=None, key=None, keyid=None, profile=None): ''' Create a group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_group group ''' if not path: path = '/' if get_group(group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_group(group_name, path) log.info('Created IAM group : %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM group %s.', group_name) return False def get_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group(group_name, max_items=1) if not info: return False return info['get_group_response']['get_group_result']['group'] except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_group_members(group_name, region=None, key=None, keyid=None, profile=None): ''' Get group information. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: marker = None truncated = True users = [] while truncated: info = conn.get_group(group_name, marker=marker, max_items=1000) if not info: return False truncated = bool(info['get_group_response']['get_group_result']['is_truncated']) if truncated and 'marker' in info['get_group_response']['get_group_result']: marker = info['get_group_response']['get_group_result']['marker'] else: marker = None truncated = False users += info['get_group_response']['get_group_result']['users'] return users except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get members for IAM group %s.', group_name) return False def add_user_to_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Add user to group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.add_user_to_group myuser mygroup ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('Username : %s does not exist.', user_name) return False if user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.add_user_to_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add IAM user %s to group %s.', user_name, group_name) return False def user_exists_in_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Check if user exists in group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.user_exists_in_group myuser mygroup ''' # TODO this should probably use boto.iam.get_groups_for_user users = get_group_members( group_name=group_name, region=region, key=key, keyid=keyid, profile=profile ) if users: for _user in users: if user_name == _user['user_name']: log.debug('IAM user %s is already in IAM group %s.', user_name, group_name) return True return False def remove_user_from_group(group_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Remove user from group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.remove_user_from_group mygroup myuser ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist.', user_name) return False if not user_exists_in_group(user_name, group_name, region=region, key=key, keyid=keyid, profile=profile): return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.remove_user_from_group(group_name, user_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove IAM user %s from group %s', user_name, group_name) return False def put_group_policy(group_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_group_policy mygroup policyname policyrules ''' group = get_group(group_name, region=region, key=key, keyid=keyid, profile=profile) if not group: log.error('Group %s does not exist', group_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_group_policy(group_name, policy_name, policy_json) if created: log.info('Created policy for IAM group %s.', group_name) return True log.error('Could not create policy for IAM group %s', group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy for IAM group %s', group_name) return False def delete_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group_policy mygroup mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_group_policy( group_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_group_policy(group_name, policy_name) log.info('Successfully deleted policy %s for IAM group %s.', policy_name, group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM group %s.', policy_name, group_name) return False def get_group_policy(group_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_group_policy mygroup policyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_group_policy(group_name, policy_name) log.debug('info for group policy is : %s', info) if not info: return False info = info.get_group_policy_response.get_group_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get IAM group %s info.', group_name) return False def get_all_groups(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM group details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_groups ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _groups = conn.get_all_groups(path_prefix=path_prefix) groups = _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) while marker: _groups = conn.get_all_groups(path_prefix=path_prefix, marker=marker) groups = groups + _groups.list_groups_response.list_groups_result.groups marker = getattr( _groups.list_groups_response.list_groups_result, 'marker', None ) return groups def get_all_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.get_all_instance_profiles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) marker = False profiles = [] while marker is not None: marker = marker if marker else None p = conn.list_instance_profiles(path_prefix=path_prefix, marker=marker) res = p.list_instance_profiles_response.list_instance_profiles_result profiles += res.instance_profiles marker = getattr(res, 'marker', None) return profiles def list_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' List all IAM instance profiles, starting at the optional path. .. versionadded:: 2016.11.0 CLI Example: salt-call boto_iam.list_instance_profiles ''' p = get_all_instance_profiles(path_prefix, region, key, keyid, profile) return [i['instance_profile_name'] for i in p] def get_all_group_policies(group_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a group. CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_group_policies mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False try: response = conn.get_all_group_policies(group_name) _list = response.list_group_policies_response.list_group_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def delete_group(group_name, region=None, key=None, keyid=None, profile=None): ''' Delete a group policy. CLI Example:: .. code-block:: bash salt myminion boto_iam.delete_group mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _group = get_group( group_name, region, key, keyid, profile ) if not _group: return True try: conn.delete_group(group_name) log.info('Successfully deleted IAM group %s.', group_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete IAM group %s.', group_name) return False def create_login_profile(user_name, password, region=None, key=None, keyid=None, profile=None): ''' Creates a login profile for the specified user, give the user the ability to access AWS services and the AWS Management Console. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.create_login_profile user_name password ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.create_login_profile(user_name, password) log.info('Created profile for IAM user %s.', user_name) return info except boto.exception.BotoServerError as e: log.debug(e) if 'Conflict' in e: log.info('Profile already exists for IAM user %s.', user_name) return 'Conflict' log.error('Failed to update profile for IAM user %s.', user_name) return False def delete_login_profile(user_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a login profile for the specified user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_login_profile user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.delete_login_profile(user_name) log.info('Deleted login profile for IAM user %s.', user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Login profile already deleted for IAM user %s.', user_name) return True log.error('Failed to delete login profile for IAM user %s.', user_name) return False def get_all_mfa_devices(user_name, region=None, key=None, keyid=None, profile=None): ''' Get all MFA devices associated with an IAM user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_mfa_devices user_name ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: result = conn.get_all_mfa_devices(user_name) devices = result['list_mfa_devices_response']['list_mfa_devices_result']['mfa_devices'] return devices except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('Could not find IAM user %s.', user_name) return [] log.error('Failed to get all MFA devices for IAM user %s.', user_name) return False def deactivate_mfa_device(user_name, serial, region=None, key=None, keyid=None, profile=None): ''' Deactivates the specified MFA device and removes it from association with the user. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_iam.deactivate_mfa_device user_name serial_num ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.deactivate_mfa_device(user_name, serial) log.info('Deactivated MFA device %s for IAM user %s.', serial, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) if 'Not Found' in e: log.info('MFA device %s not associated with IAM user %s.', serial, user_name) return True log.error('Failed to deactivate MFA device %s for IAM user %s.', serial, user_name) return False def delete_virtual_mfa_device(serial, region=None, key=None, keyid=None, profile=None): ''' Deletes the specified virtual MFA device. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_virtual_mfa_device serial_num ''' conn = __utils__['boto3.get_connection_func']('iam')() try: conn.delete_virtual_mfa_device(SerialNumber=serial) log.info('Deleted virtual MFA device %s.', serial) return True except botocore.exceptions.ClientError as e: log.debug(e) if 'NoSuchEntity' in six.text_type(e): log.info('Virtual MFA device %s not found.', serial) return True log.error('Failed to delete virtual MFA device %s.', serial) return False def update_account_password_policy(allow_users_to_change_password=None, hard_expiry=None, max_password_age=None, minimum_password_length=None, password_reuse_prevention=None, require_lowercase_characters=None, require_numbers=None, require_symbols=None, require_uppercase_characters=None, region=None, key=None, keyid=None, profile=None): ''' Update the password policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_account_password_policy True ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.update_account_password_policy(allow_users_to_change_password, hard_expiry, max_password_age, minimum_password_length, password_reuse_prevention, require_lowercase_characters, require_numbers, require_symbols, require_uppercase_characters) log.info('The password policy has been updated.') return True except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy' log.error(msg) return False def get_account_policy(region=None, key=None, keyid=None, profile=None): ''' Get account policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_account_password_policy() return info.get_account_password_policy_response.get_account_password_policy_result.password_policy except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to update the password policy.' log.error(msg) return False def create_role(name, policy_document=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Create an instance role. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if role_exists(name, region, key, keyid, profile): return True if not policy_document: policy_document = None try: conn.create_role(name, assume_role_policy_document=policy_document, path=path) log.info('Created IAM role %s.', name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to create IAM role %s.', name) return False def delete_role(name, region=None, key=None, keyid=None, profile=None): ''' Delete an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(name, region, key, keyid, profile): return True try: conn.delete_role(name) log.info('Deleted %s IAM role.', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete %s IAM role.', name) return False def profile_associated(role_name, profile_name, region, key, keyid, profile): ''' Check to see if an instance profile is associated with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.profile_associated myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # The IAM module of boto doesn't return objects. Instead you need to grab # values through its properties. Sigh. try: profiles = conn.list_instance_profiles_for_role(role_name) except boto.exception.BotoServerError as e: log.debug(e) return False profiles = profiles.list_instance_profiles_for_role_response profiles = profiles.list_instance_profiles_for_role_result profiles = profiles.instance_profiles for profile in profiles: if profile.instance_profile_name == profile_name: return True return False def associate_profile_to_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Associate an instance profile with an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.associate_profile_to_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if associated: return True else: try: conn.add_role_to_instance_profile(profile_name, role_name) log.info('Added %s instance profile to IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to add %s instance profile to IAM role %s', profile_name, role_name) return False def disassociate_profile_from_role(profile_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Disassociate an instance profile from an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.disassociate_profile_from_role myirole myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(role_name, region, key, keyid, profile): log.error('IAM role %s does not exist.', role_name) return False if not instance_profile_exists(profile_name, region, key, keyid, profile): log.error('Instance profile %s does not exist.', profile_name) return False associated = profile_associated(role_name, profile_name, region, key, keyid, profile) if not associated: return True else: try: conn.remove_role_from_instance_profile(profile_name, role_name) log.info('Removed %s instance profile from IAM role %s.', profile_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to remove %s instance profile from IAM role %s.', profile_name, role_name) return False def list_role_policies(role_name, region=None, key=None, keyid=None, profile=None): ''' Get a list of policy names from a role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_role_policies myirole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_role_policies(role_name) _list = response.list_role_policies_response.list_role_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) return [] def get_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.get_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: _policy = conn.get_role_policy(role_name, policy_name) # I _hate_ you for not giving me an object boto. _policy = _policy.get_role_policy_response.policy_document # Policy is url encoded _policy = _unquote(_policy) _policy = salt.utils.json.loads(_policy, object_pairs_hook=odict.OrderedDict) return _policy except boto.exception.BotoServerError: return {} def create_role_policy(role_name, policy_name, policy, region=None, key=None, keyid=None, profile=None): ''' Create or modify a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.create_role_policy myirole mypolicy '{"MyPolicy": "Statement": [{"Action": ["sqs:*"], "Effect": "Allow", "Resource": ["arn:aws:sqs:*:*:*"], "Sid": "MyPolicySqs1"}]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) mode = 'create' if _policy: if _policy == policy: return True mode = 'modify' if isinstance(policy, six.string_types): policy = salt.utils.json.loads(policy, object_pairs_hook=odict.OrderedDict) try: _policy = salt.utils.json.dumps(policy) conn.put_role_policy(role_name, policy_name, _policy) if mode == 'create': msg = 'Successfully added policy %s to IAM role %s.' else: msg = 'Successfully modified policy %s for IAM role %s.' log.info(msg, policy_name, role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to %s policy %s for IAM role %s.', mode, policy_name, role_name) return False def delete_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile) if not _policy: return True try: conn.delete_role_policy(role_name, policy_name) log.info('Successfully deleted policy %s for IAM role %s.', policy_name, role_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM role %s.', policy_name, role_name) return False def update_assume_role_policy(role_name, policy_document, region=None, key=None, keyid=None, profile=None): ''' Update an assume role policy for a role. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.update_assume_role_policy myrole '{"Statement":"..."}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(policy_document, six.string_types): policy_document = salt.utils.json.loads(policy_document, object_pairs_hook=odict.OrderedDict) try: _policy_document = salt.utils.json.dumps(policy_document) conn.update_assume_role_policy(role_name, _policy_document) log.info('Successfully updated assume role policy for IAM role %s.', role_name) return True except boto.exception.BotoServerError as e: log.error(e) log.error('Failed to update assume role policy for IAM role %s.', role_name) return False def build_policy(region=None, key=None, keyid=None, profile=None): ''' Build a default assume role policy. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.build_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if hasattr(conn, 'build_policy'): policy = salt.utils.json.loads(conn.build_policy()) elif hasattr(conn, '_build_policy'): policy = salt.utils.json.loads(conn._build_policy()) else: return {} # The format we get from build_policy isn't going to be what we get back # from AWS for the exact same policy. AWS converts single item list values # into strings, so let's do the same here. for key, policy_val in policy.items(): for statement in policy_val: if (isinstance(statement['Action'], list) and len(statement['Action']) == 1): statement['Action'] = statement['Action'][0] if (isinstance(statement['Principal']['Service'], list) and len(statement['Principal']['Service']) == 1): statement['Principal']['Service'] = statement['Principal']['Service'][0] # build_policy doesn't add a version field, which AWS is going to set to a # default value, when we get it back, so let's set it. policy['Version'] = '2008-10-17' return policy def get_account_id(region=None, key=None, keyid=None, profile=None): ''' Get a the AWS account id associated with the used credentials. CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_id ''' cache_key = 'boto_iam.account_id' if cache_key not in __context__: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_user() # The get_user call returns an user ARN: # arn:aws:iam::027050522557:user/salt-test arn = ret['get_user_response']['get_user_result']['user']['arn'] account_id = arn.split(':')[4] except boto.exception.BotoServerError: # If call failed, then let's try to get the ARN from the metadata timeout = boto.config.getfloat( 'Boto', 'metadata_service_timeout', 1.0 ) attempts = boto.config.getint( 'Boto', 'metadata_service_num_attempts', 1 ) identity = boto.utils.get_instance_identity( timeout=timeout, num_retries=attempts ) try: account_id = identity['document']['accountId'] except KeyError: log.error('Failed to get account id from instance_identity in' ' boto_iam.get_account_id.') __context__[cache_key] = account_id return __context__[cache_key] def get_all_roles(path_prefix=None, region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM role details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_roles ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _roles = conn.list_roles(path_prefix=path_prefix) roles = _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) while marker: _roles = conn.list_roles(path_prefix=path_prefix, marker=marker) roles = roles + _roles.list_roles_response.list_roles_result.roles marker = getattr( _roles.list_roles_response.list_roles_result, 'marker', None ) return roles def get_all_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get and return all IAM user details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_users ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _users = conn.get_all_users(path_prefix=path_prefix) users = _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) while marker: _users = conn.get_all_users(path_prefix=path_prefix, marker=marker) users = users + _users.list_users_response.list_users_result.users marker = getattr( _users.list_users_response.list_users_result, 'marker', None ) return users def get_all_user_policies(user_name, marker=None, max_items=None, region=None, key=None, keyid=None, profile=None): ''' Get all user policies. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_all_user_policies myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_all_user_policies(user_name, marker, max_items) if not info: return False _list = info.list_user_policies_response.list_user_policies_result return _list.policy_names except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policies for user %s.', user_name) return False def get_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Retrieves the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_user_policy myuser mypolicyname ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_user_policy(user_name, policy_name) log.debug('Info for IAM user %s policy %s: %s.', user_name, policy_name, info) if not info: return False info = info.get_user_policy_response.get_user_policy_result.policy_document info = _unquote(info) info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get policy %s for IAM user %s.', policy_name, user_name) return False def put_user_policy(user_name, policy_name, policy_json, region=None, key=None, keyid=None, profile=None): ''' Adds or updates the specified policy document for the specified user. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.put_user_policy myuser policyname policyrules ''' user = get_user(user_name, region, key, keyid, profile) if not user: log.error('IAM user %s does not exist', user_name) return False conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if not isinstance(policy_json, six.string_types): policy_json = salt.utils.json.dumps(policy_json) created = conn.put_user_policy(user_name, policy_name, policy_json) if created: log.info('Created policy %s for IAM user %s.', policy_name, user_name) return True log.error('Could not create policy %s for IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create policy %s for IAM user %s.', policy_name, user_name) return False def delete_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a user policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_user_policy myuser mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return False _policy = get_user_policy( user_name, policy_name, region, key, keyid, profile ) if not _policy: return True try: conn.delete_user_policy(user_name, policy_name) log.info('Successfully deleted policy %s for IAM user %s.', policy_name, user_name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete policy %s for IAM user %s.', policy_name, user_name) return False def upload_server_cert(cert_name, cert_body, private_key, cert_chain=None, path=None, region=None, key=None, keyid=None, profile=None): ''' Upload a certificate to Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.upload_server_cert mycert_name crt priv_key :param cert_name: The name for the server certificate. Do not include the path in this value. :param cert_body: The contents of the public key certificate in PEM-encoded format. :param private_key: The contents of the private key in PEM-encoded format. :param cert_chain: The contents of the certificate chain. This is typically a concatenation of the PEM-encoded public key certificates of the chain. :param path: The path for the server certificate. :param region: The name of the region to connect to. :param key: The key to be used in order to connect :param keyid: The keyid to be used in order to connect :param profile: The profile that contains a dict of region, key, keyid :return: True / False ''' exists = get_server_certificate(cert_name, region, key, keyid, profile) if exists: return True conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.upload_server_cert(cert_name, cert_body, private_key, cert_chain) log.info('Created certificate %s.', cert_name) return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to failed to create certificate %s.', cert_name) return False def list_server_certificates(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Lists the server certificates stored in IAM that have the specified path prefix. .. versionadded:: ??? :param path_prefix: The path prefix for filtering the results. For example: /company/servercerts would get all server certificates for which the path starts with /company/servercerts . This parameter is optional. If it is not included, it defaults to a slash (/), listing all server certificates. This parameter allows (per its regex pattern) a string of characters consisting of either a forward slash (/) by itself or a string that must begin and end with forward slashes. In addition, it can contain any ASCII character from the ! (u0021) through the DEL character (u007F), including most punctuation characters, digits, and upper and lowercased letters. CLI Example: .. code-block:: bash salt myminion boto_iam.list_server_certificates path_prefix=/somepath/ ''' retries = 10 sleep = 6 conn = __utils__['boto3.get_connection']('iam', region=region, key=key, keyid=keyid, profile=profile) Items = [] while retries: try: log.debug('Garnering list of IAM Server Certificates') IsTruncated = True while IsTruncated: kwargs = {'PathPrefix': path_prefix} ret = conn.list_server_certificates(**kwargs) Items += ret.get('ServerCertificateMetadataList', []) IsTruncated = ret.get('IsTruncated') kwargs.update({'Marker': ret.get('Marker')}) return Items except botocore.exceptions.ParamValidationError as err: raise SaltInvocationError(str(err)) except botocore.exceptions.ClientError as err: if retries and jmespath.search('Error.Code', err.response) == 'Throttling': retries -= 1 log.debug('Throttled by AWS API, retrying in %s seconds...', sleep) time.sleep(sleep) continue log.error('Failed to list IAM Server Certificates: %s', err.message) return None def get_server_certificate(cert_name, region=None, key=None, keyid=None, profile=None): ''' Returns certificate information from Amazon .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_server_certificate mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: info = conn.get_server_certificate(cert_name) if not info: return False return info except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to get certificate %s information.', cert_name) return False def delete_server_cert(cert_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a certificate from Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_server_cert mycert_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.delete_server_cert(cert_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to delete certificate %s.', cert_name) return False def export_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM user details. Produces results that can be used to create an sls file. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.export_users --out=txt | sed "s/local: //" > iam_users.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() users = get_all_users(path_prefix, region, key, keyid, profile) for user in users: name = user.user_name _policies = conn.get_all_user_policies(name, max_items=100) _policies = _policies.list_user_policies_response.list_user_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_user_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_user_policy_response.get_user_policy_result.policy_document )) policies[policy_name] = _policy user_sls = [] user_sls.append({"name": name}) user_sls.append({"policies": policies}) user_sls.append({"path": user.path}) results["manage user " + name] = {"boto_iam.user_present": user_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def export_roles(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM role details. Produces results that can be used to create an sls file. CLI Example: salt-call boto_iam.export_roles --out=txt | sed "s/local: //" > iam_roles.sls ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None results = odict.OrderedDict() roles = get_all_roles(path_prefix, region, key, keyid, profile) for role in roles: name = role.role_name _policies = conn.list_role_policies(name, max_items=100) _policies = _policies.list_role_policies_response.list_role_policies_result.policy_names policies = {} for policy_name in _policies: _policy = conn.get_role_policy(name, policy_name) _policy = salt.utils.json.loads(_unquote( _policy.get_role_policy_response.get_role_policy_result.policy_document )) policies[policy_name] = _policy role_sls = [] role_sls.append({"name": name}) role_sls.append({"policies": policies}) role_sls.append({'policy_document': salt.utils.json.loads(_unquote(role.assume_role_policy_document))}) role_sls.append({"path": role.path}) results["manage role " + name] = {"boto_iam_role.present": role_sls} return __utils__['yaml.safe_dump']( results, default_flow_style=False, indent=2) def _get_policy_arn(name, region=None, key=None, keyid=None, profile=None): if name.startswith('arn:aws:iam:'): return name account_id = get_account_id( region=region, key=key, keyid=keyid, profile=profile ) return 'arn:aws:iam::{0}:policy/{1}'.format(account_id, name) def policy_exists(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return True except boto.exception.BotoServerError: return False def get_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile)) return ret.get('get_policy_response', {}).get('get_policy_result', {}) except boto.exception.BotoServerError: return None def create_policy(policy_name, policy_document, path=None, description=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in 'path', 'description': if locals()[arg] is not None: params[arg] = locals()[arg] if policy_exists(policy_name, region, key, keyid, profile): return True try: conn.create_policy(policy_name, policy_document, **params) log.info('Created IAM policy %s.', policy_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s.', policy_name) return False return True def delete_policy(policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_exists(policy_arn, region, key, keyid, profile): return True try: conn.delete_policy(policy_arn) log.info('Deleted %s policy.', policy_name) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete %s policy: %s.', policy_name, aws.get('message')) return False return True def list_policies(region=None, key=None, keyid=None, profile=None): ''' List policies. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policies ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: policies = [] for ret in __utils__['boto.paged_call'](conn.list_policies): policies.append(ret.get('list_policies_response', {}).get('list_policies_result', {}).get('policies')) return policies except boto.exception.BotoServerError as e: log.debug(e) msg = 'Failed to list policy versions.' log.error(msg) return [] def policy_version_exists(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.get_policy_version(policy_arn, version_id) return True except boto.exception.BotoServerError: return False def get_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy_version(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile), version_id) retval = ret.get('get_policy_version_response', {}).get('get_policy_version_result', {}).get('policy_version', {}) retval['document'] = _unquote(retval.get('document')) return {'policy_version': retval} except boto.exception.BotoServerError: return None def create_policy_version(policy_name, policy_document, set_as_default=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy version. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy_version mypolicy '{"Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["s3:Get*", "s3:List*"], "Resource": ["arn:aws:s3:::my-bucket/shared/*"]},]}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not isinstance(policy_document, six.string_types): policy_document = salt.utils.json.dumps(policy_document) params = {} for arg in ('set_as_default',): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.create_policy_version(policy_arn, policy_document, **params) vid = ret.get('create_policy_version_response', {}).get('create_policy_version_result', {}).get('policy_version', {}).get('version_id') log.info('Created IAM policy %s version %s.', policy_name, vid) return {'created': True, 'version_id': vid} except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to create IAM policy %s version %s.', policy_name, vid) return {'created': False, 'error': __utils__['boto.get_error'](e)} def delete_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Delete a policy version. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) if not policy_version_exists(policy_arn, version_id, region, key, keyid, profile): return True try: conn.delete_policy_version(policy_arn, version_id) log.info('Deleted IAM policy %s version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete IAM policy %s version %s: %s', policy_name, version_id, aws.get('message')) return False return True def list_policy_versions(policy_name, region=None, key=None, keyid=None, profile=None): ''' List versions of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policy_versions mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: ret = conn.list_policy_versions(policy_arn) return ret.get('list_policy_versions_response', {}).get('list_policy_versions_result', {}).get('versions') except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list versions for IAM policy %s.', policy_name) return [] def set_default_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Set the default version of a policy. CLI Example: .. code-block:: bash salt myminion boto_iam.set_default_policy_version mypolicy v1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.set_default_policy_version(policy_arn, version_id) log.info('Set %s policy to version %s.', policy_name, version_id) except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to set %s policy to version %s: %s', policy_name, version_id, aws.get('message')) return False return True def attach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_user_policy(policy_arn, user_name) log.info('Attached policy %s to IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach %s policy to IAM user %s.', policy_name, user_name) return False return True def detach_user_policy(policy_name, user_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a user. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_user_policy mypolicy myuser ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_user_policy(policy_arn, user_name) log.info('Detached %s policy from IAM user %s.', policy_name, user_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach %s policy from IAM user %s.', policy_name, user_name) return False return True def attach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_group_policy(policy_arn, group_name) log.info('Attached policy %s to IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM group %s.', policy_name, group_name) return False return True def detach_group_policy(policy_name, group_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a group. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_group_policy mypolicy mygroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_group_policy(policy_arn, group_name) log.info('Detached policy %s from IAM group %s.', policy_name, group_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM group %s.', policy_name, group_name) return False return True def attach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Attach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.attach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.attach_role_policy(policy_arn, role_name) log.info('Attached policy %s to IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to attach policy %s to IAM role %s.', policy_name, role_name) return False return True def detach_role_policy(policy_name, role_name, region=None, key=None, keyid=None, profile=None): ''' Detach a managed policy to a role. CLI Example: .. code-block:: bash salt myminion boto_iam.detach_role_policy mypolicy myrole ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) try: conn.detach_role_policy(policy_arn, role_name) log.info('Detached policy %s from IAM role %s.', policy_name, role_name) except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to detach policy %s from IAM role %s.', policy_name, role_name) return False return True def list_entities_for_policy(policy_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities that a policy is attached to. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 params = {} for arg in ('path_prefix', 'entity_filter'): if locals()[arg] is not None: params[arg] = locals()[arg] policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile) while retries: try: allret = { 'policy_groups': [], 'policy_users': [], 'policy_roles': [], } for ret in __utils__['boto.paged_call'](conn.list_entities_for_policy, policy_arn=policy_arn, **params): for k, v in six.iteritems(allret): v.extend(ret.get('list_entities_for_policy_response', {}).get('list_entities_for_policy_result', {}).get(k)) return allret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('Failed to list entities for IAM policy %s: %s', policy_name, e.message) return {} return {} def list_attached_user_policies(user_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given user. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'UserName': user_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedUserPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_user_policies_response', {}).get('list_attached_user_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM user %s.', user_name) return [] def list_attached_group_policies(group_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given group. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'GroupName': group_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedGroupPolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_group_policies_response', {}).get('list_attached_group_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM group %s.', group_name) return [] def list_attached_role_policies(role_name, path_prefix=None, entity_filter=None, region=None, key=None, keyid=None, profile=None): ''' List entities attached to the given role. CLI Example: .. code-block:: bash salt myminion boto_iam.list_entities_for_policy mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) params = {'RoleName': role_name} if path_prefix is not None: params['PathPrefix'] = path_prefix policies = [] try: # Using conn.get_response is a bit of a hack, but it avoids having to # rewrite this whole module based on boto3 for ret in __utils__['boto.paged_call'](conn.get_response, 'ListAttachedRolePolicies', params, list_marker='AttachedPolicies'): policies.extend(ret.get('list_attached_role_policies_response', {}).get('list_attached_role_policies_result', {} ).get('attached_policies', [])) return policies except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to list attached policies for IAM role %s.', role_name) return [] def create_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Create SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.create_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.create_saml_provider(saml_metadata_document, name) log.info('Successfully created %s SAML provider.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to create SAML provider %s.', name) return False def get_saml_provider_arn(name, region=None, key=None, keyid=None, profile=None): ''' Get SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.get_saml_provider_arn my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: response = conn.list_saml_providers() for saml_provider in response.list_saml_providers_response.list_saml_providers_result.saml_provider_list: if saml_provider['arn'].endswith(':saml-provider/' + name): return saml_provider['arn'] return False except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to get ARN of SAML provider %s.', name) return False def delete_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Delete SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.delete_saml_provider my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return True conn.delete_saml_provider(saml_provider_arn) log.info('Successfully deleted SAML provider %s.', name) return True except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) log.error('Failed to delete SAML provider %s.', name) return False def list_saml_providers(region=None, key=None, keyid=None, profile=None): ''' List SAML providers. CLI Example: .. code-block:: bash salt myminion boto_iam.list_saml_providers ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: providers = [] info = conn.list_saml_providers() for arn in info['list_saml_providers_response']['list_saml_providers_result']['saml_provider_list']: providers.append(arn['arn'].rsplit('/', 1)[1]) return providers except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to get list of SAML providers.') return False def update_saml_provider(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' Update SAML provider. CLI Example: .. code-block:: bash salt myminion boto_iam.update_saml_provider my_saml_provider_name saml_metadata_document ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: saml_provider_arn = get_saml_provider_arn(name, region=region, key=key, keyid=keyid, profile=profile) if not saml_provider_arn: log.info('SAML provider %s not found.', name) return False if conn.update_saml_provider(name, saml_metadata_document): return True return False except boto.exception.BotoServerError as e: log.debug(__utils__['boto.get_error'](e)) log.error('Failed to update SAML provider %s.', name) return False
saltstack/salt
salt/beacons/adb.py
validate
python
def validate(config): ''' Validate the beacon configuration ''' # Configuration for adb beacon should be a dictionary with states array if not isinstance(config, list): log.info('Configuration for adb beacon must be a list.') return False, ('Configuration for adb beacon must be a list.') _config = {} list(map(_config.update, config)) if 'states' not in _config: log.info('Configuration for adb beacon must include a states array.') return False, ('Configuration for adb beacon must include a states array.') else: if not isinstance(_config['states'], list): log.info('Configuration for adb beacon must include a states array.') return False, ('Configuration for adb beacon must include a states array.') else: states = ['offline', 'bootloader', 'device', 'host', 'recovery', 'no permissions', 'sideload', 'unauthorized', 'unknown', 'missing'] if any(s not in states for s in _config['states']): log.info('Need a one of the following adb ' 'states: %s', ', '.join(states)) return False, ('Need a one of the following adb ' 'states: {0}'.format(', '.join(states))) return True, 'Valid beacon configuration'
Validate the beacon configuration
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/beacons/adb.py#L32-L60
null
# -*- coding: utf-8 -*- ''' Beacon to emit adb device state changes for Android devices .. versionadded:: 2016.3.0 ''' # Import Python libs from __future__ import absolute_import, unicode_literals import logging # Salt libs import salt.utils.path from salt.ext.six.moves import map log = logging.getLogger(__name__) __virtualname__ = 'adb' last_state = {} last_state_extra = {'value': False, 'no_devices': False} def __virtual__(): which_result = salt.utils.path.which('adb') if which_result is None: return False else: return __virtualname__ def beacon(config): ''' Emit the status of all devices returned by adb Specify the device states that should emit an event, there will be an event for each device with the event type and device specified. .. code-block:: yaml beacons: adb: - states: - offline - unauthorized - missing - no_devices_event: True - battery_low: 25 ''' log.trace('adb beacon starting') ret = [] _config = {} list(map(_config.update, config)) out = __salt__['cmd.run']('adb devices', runas=_config.get('user', None)) lines = out.split('\n')[1:] last_state_devices = list(last_state.keys()) found_devices = [] for line in lines: try: device, state = line.split('\t') found_devices.append(device) if device not in last_state_devices or \ ('state' in last_state[device] and last_state[device]['state'] != state): if state in _config['states']: ret.append({'device': device, 'state': state, 'tag': state}) last_state[device] = {'state': state} if 'battery_low' in _config: val = last_state.get(device, {}) cmd = 'adb -s {0} shell cat /sys/class/power_supply/*/capacity'.format(device) battery_levels = __salt__['cmd.run'](cmd, runas=_config.get('user', None)).split('\n') for l in battery_levels: battery_level = int(l) if 0 < battery_level < 100: if 'battery' not in val or battery_level != val['battery']: if ('battery' not in val or val['battery'] > _config['battery_low']) and \ battery_level <= _config['battery_low']: ret.append({'device': device, 'battery_level': battery_level, 'tag': 'battery_low'}) if device not in last_state: last_state[device] = {} last_state[device].update({'battery': battery_level}) except ValueError: continue # Find missing devices and remove them / send an event for device in last_state_devices: if device not in found_devices: if 'missing' in _config['states']: ret.append({'device': device, 'state': 'missing', 'tag': 'missing'}) del last_state[device] # Maybe send an event if we don't have any devices if 'no_devices_event' in _config and _config['no_devices_event'] is True: if not found_devices and not last_state_extra['no_devices']: ret.append({'tag': 'no_devices'}) # Did we have no devices listed this time around? last_state_extra['no_devices'] = not found_devices return ret
saltstack/salt
salt/beacons/adb.py
beacon
python
def beacon(config): ''' Emit the status of all devices returned by adb Specify the device states that should emit an event, there will be an event for each device with the event type and device specified. .. code-block:: yaml beacons: adb: - states: - offline - unauthorized - missing - no_devices_event: True - battery_low: 25 ''' log.trace('adb beacon starting') ret = [] _config = {} list(map(_config.update, config)) out = __salt__['cmd.run']('adb devices', runas=_config.get('user', None)) lines = out.split('\n')[1:] last_state_devices = list(last_state.keys()) found_devices = [] for line in lines: try: device, state = line.split('\t') found_devices.append(device) if device not in last_state_devices or \ ('state' in last_state[device] and last_state[device]['state'] != state): if state in _config['states']: ret.append({'device': device, 'state': state, 'tag': state}) last_state[device] = {'state': state} if 'battery_low' in _config: val = last_state.get(device, {}) cmd = 'adb -s {0} shell cat /sys/class/power_supply/*/capacity'.format(device) battery_levels = __salt__['cmd.run'](cmd, runas=_config.get('user', None)).split('\n') for l in battery_levels: battery_level = int(l) if 0 < battery_level < 100: if 'battery' not in val or battery_level != val['battery']: if ('battery' not in val or val['battery'] > _config['battery_low']) and \ battery_level <= _config['battery_low']: ret.append({'device': device, 'battery_level': battery_level, 'tag': 'battery_low'}) if device not in last_state: last_state[device] = {} last_state[device].update({'battery': battery_level}) except ValueError: continue # Find missing devices and remove them / send an event for device in last_state_devices: if device not in found_devices: if 'missing' in _config['states']: ret.append({'device': device, 'state': 'missing', 'tag': 'missing'}) del last_state[device] # Maybe send an event if we don't have any devices if 'no_devices_event' in _config and _config['no_devices_event'] is True: if not found_devices and not last_state_extra['no_devices']: ret.append({'tag': 'no_devices'}) # Did we have no devices listed this time around? last_state_extra['no_devices'] = not found_devices return ret
Emit the status of all devices returned by adb Specify the device states that should emit an event, there will be an event for each device with the event type and device specified. .. code-block:: yaml beacons: adb: - states: - offline - unauthorized - missing - no_devices_event: True - battery_low: 25
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/beacons/adb.py#L63-L144
null
# -*- coding: utf-8 -*- ''' Beacon to emit adb device state changes for Android devices .. versionadded:: 2016.3.0 ''' # Import Python libs from __future__ import absolute_import, unicode_literals import logging # Salt libs import salt.utils.path from salt.ext.six.moves import map log = logging.getLogger(__name__) __virtualname__ = 'adb' last_state = {} last_state_extra = {'value': False, 'no_devices': False} def __virtual__(): which_result = salt.utils.path.which('adb') if which_result is None: return False else: return __virtualname__ def validate(config): ''' Validate the beacon configuration ''' # Configuration for adb beacon should be a dictionary with states array if not isinstance(config, list): log.info('Configuration for adb beacon must be a list.') return False, ('Configuration for adb beacon must be a list.') _config = {} list(map(_config.update, config)) if 'states' not in _config: log.info('Configuration for adb beacon must include a states array.') return False, ('Configuration for adb beacon must include a states array.') else: if not isinstance(_config['states'], list): log.info('Configuration for adb beacon must include a states array.') return False, ('Configuration for adb beacon must include a states array.') else: states = ['offline', 'bootloader', 'device', 'host', 'recovery', 'no permissions', 'sideload', 'unauthorized', 'unknown', 'missing'] if any(s not in states for s in _config['states']): log.info('Need a one of the following adb ' 'states: %s', ', '.join(states)) return False, ('Need a one of the following adb ' 'states: {0}'.format(', '.join(states))) return True, 'Valid beacon configuration'
saltstack/salt
salt/thorium/reg.py
set_
python
def set_(name, add, match): ''' Add a value to the named set USAGE: .. code-block:: yaml foo: reg.set: - add: bar - match: my/custom/event ''' ret = {'name': name, 'changes': {}, 'comment': '', 'result': True} if name not in __reg__: __reg__[name] = {} __reg__[name]['val'] = set() for event in __events__: if salt.utils.stringutils.expr_match(event['tag'], match): try: val = event['data']['data'].get(add) except KeyError: val = event['data'].get(add) if val is None: val = 'None' ret['changes'][add] = val __reg__[name]['val'].add(val) return ret
Add a value to the named set USAGE: .. code-block:: yaml foo: reg.set: - add: bar - match: my/custom/event
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/thorium/reg.py#L17-L47
[ "def expr_match(line, expr):\n '''\n Checks whether or not the passed value matches the specified expression.\n Tries to match expr first as a glob using fnmatch.fnmatch(), and then tries\n to match expr as a regular expression. Originally designed to match minion\n IDs for whitelists/blacklists.\n\n Note that this also does exact matches, as fnmatch.fnmatch() will return\n ``True`` when no glob characters are used and the string is an exact match:\n\n .. code-block:: python\n\n >>> fnmatch.fnmatch('foo', 'foo')\n True\n '''\n try:\n if fnmatch.fnmatch(line, expr):\n return True\n try:\n if re.match(r'\\A{0}\\Z'.format(expr), line):\n return True\n except re.error:\n pass\n except TypeError:\n log.exception('Value %r or expression %r is not a string', line, expr)\n return False\n" ]
# -*- coding: utf-8 -*- ''' Used to manage the thorium register. The thorium register is where compound values are stored and computed, such as averages etc. ''' # import python libs from __future__ import absolute_import, division, print_function, unicode_literals import salt.utils.stringutils __func_alias__ = { 'set_': 'set', 'list_': 'list', } def list_(name, add, match, stamp=False, prune=0): ''' Add the specified values to the named list If ``stamp`` is True, then the timestamp from the event will also be added if ``prune`` is set to an integer higher than ``0``, then only the last ``prune`` values will be kept in the list. USAGE: .. code-block:: yaml foo: reg.list: - add: bar - match: my/custom/event - stamp: True ''' ret = {'name': name, 'changes': {}, 'comment': '', 'result': True} if not isinstance(add, list): add = add.split(',') if name not in __reg__: __reg__[name] = {} __reg__[name]['val'] = [] for event in __events__: try: event_data = event['data']['data'] except KeyError: event_data = event['data'] if salt.utils.stringutils.expr_match(event['tag'], match): item = {} for key in add: if key in event_data: item[key] = event_data[key] if stamp is True: item['time'] = event['data']['_stamp'] __reg__[name]['val'].append(item) if prune > 0: __reg__[name]['val'] = __reg__[name]['val'][:prune] return ret def mean(name, add, match): ''' Accept a numeric value from the matched events and store a running average of the values in the given register. If the specified value is not numeric it will be skipped USAGE: .. code-block:: yaml foo: reg.mean: - add: data_field - match: my/custom/event ''' ret = {'name': name, 'changes': {}, 'comment': '', 'result': True} if name not in __reg__: __reg__[name] = {} __reg__[name]['val'] = 0 __reg__[name]['total'] = 0 __reg__[name]['count'] = 0 for event in __events__: try: event_data = event['data']['data'] except KeyError: event_data = event['data'] if salt.utils.stringutils.expr_match(event['tag'], match): if add in event_data: try: comp = int(event_data) except ValueError: continue __reg__[name]['total'] += comp __reg__[name]['count'] += 1 __reg__[name]['val'] = __reg__[name]['total'] / __reg__[name]['count'] return ret def clear(name): ''' Clear the namespace from the register USAGE: .. code-block:: yaml clearns: reg.clear: - name: myregister ''' ret = {'name': name, 'changes': {}, 'comment': '', 'result': True} if name in __reg__: __reg__[name].clear() return ret def delete(name): ''' Delete the namespace from the register USAGE: .. code-block:: yaml deletens: reg.delete: - name: myregister ''' ret = {'name': name, 'changes': {}, 'comment': '', 'result': True} if name in __reg__: del __reg__[name] return ret
saltstack/salt
salt/thorium/reg.py
list_
python
def list_(name, add, match, stamp=False, prune=0): ''' Add the specified values to the named list If ``stamp`` is True, then the timestamp from the event will also be added if ``prune`` is set to an integer higher than ``0``, then only the last ``prune`` values will be kept in the list. USAGE: .. code-block:: yaml foo: reg.list: - add: bar - match: my/custom/event - stamp: True ''' ret = {'name': name, 'changes': {}, 'comment': '', 'result': True} if not isinstance(add, list): add = add.split(',') if name not in __reg__: __reg__[name] = {} __reg__[name]['val'] = [] for event in __events__: try: event_data = event['data']['data'] except KeyError: event_data = event['data'] if salt.utils.stringutils.expr_match(event['tag'], match): item = {} for key in add: if key in event_data: item[key] = event_data[key] if stamp is True: item['time'] = event['data']['_stamp'] __reg__[name]['val'].append(item) if prune > 0: __reg__[name]['val'] = __reg__[name]['val'][:prune] return ret
Add the specified values to the named list If ``stamp`` is True, then the timestamp from the event will also be added if ``prune`` is set to an integer higher than ``0``, then only the last ``prune`` values will be kept in the list. USAGE: .. code-block:: yaml foo: reg.list: - add: bar - match: my/custom/event - stamp: True
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/thorium/reg.py#L50-L92
[ "def expr_match(line, expr):\n '''\n Checks whether or not the passed value matches the specified expression.\n Tries to match expr first as a glob using fnmatch.fnmatch(), and then tries\n to match expr as a regular expression. Originally designed to match minion\n IDs for whitelists/blacklists.\n\n Note that this also does exact matches, as fnmatch.fnmatch() will return\n ``True`` when no glob characters are used and the string is an exact match:\n\n .. code-block:: python\n\n >>> fnmatch.fnmatch('foo', 'foo')\n True\n '''\n try:\n if fnmatch.fnmatch(line, expr):\n return True\n try:\n if re.match(r'\\A{0}\\Z'.format(expr), line):\n return True\n except re.error:\n pass\n except TypeError:\n log.exception('Value %r or expression %r is not a string', line, expr)\n return False\n" ]
# -*- coding: utf-8 -*- ''' Used to manage the thorium register. The thorium register is where compound values are stored and computed, such as averages etc. ''' # import python libs from __future__ import absolute_import, division, print_function, unicode_literals import salt.utils.stringutils __func_alias__ = { 'set_': 'set', 'list_': 'list', } def set_(name, add, match): ''' Add a value to the named set USAGE: .. code-block:: yaml foo: reg.set: - add: bar - match: my/custom/event ''' ret = {'name': name, 'changes': {}, 'comment': '', 'result': True} if name not in __reg__: __reg__[name] = {} __reg__[name]['val'] = set() for event in __events__: if salt.utils.stringutils.expr_match(event['tag'], match): try: val = event['data']['data'].get(add) except KeyError: val = event['data'].get(add) if val is None: val = 'None' ret['changes'][add] = val __reg__[name]['val'].add(val) return ret def mean(name, add, match): ''' Accept a numeric value from the matched events and store a running average of the values in the given register. If the specified value is not numeric it will be skipped USAGE: .. code-block:: yaml foo: reg.mean: - add: data_field - match: my/custom/event ''' ret = {'name': name, 'changes': {}, 'comment': '', 'result': True} if name not in __reg__: __reg__[name] = {} __reg__[name]['val'] = 0 __reg__[name]['total'] = 0 __reg__[name]['count'] = 0 for event in __events__: try: event_data = event['data']['data'] except KeyError: event_data = event['data'] if salt.utils.stringutils.expr_match(event['tag'], match): if add in event_data: try: comp = int(event_data) except ValueError: continue __reg__[name]['total'] += comp __reg__[name]['count'] += 1 __reg__[name]['val'] = __reg__[name]['total'] / __reg__[name]['count'] return ret def clear(name): ''' Clear the namespace from the register USAGE: .. code-block:: yaml clearns: reg.clear: - name: myregister ''' ret = {'name': name, 'changes': {}, 'comment': '', 'result': True} if name in __reg__: __reg__[name].clear() return ret def delete(name): ''' Delete the namespace from the register USAGE: .. code-block:: yaml deletens: reg.delete: - name: myregister ''' ret = {'name': name, 'changes': {}, 'comment': '', 'result': True} if name in __reg__: del __reg__[name] return ret
saltstack/salt
salt/thorium/reg.py
mean
python
def mean(name, add, match): ''' Accept a numeric value from the matched events and store a running average of the values in the given register. If the specified value is not numeric it will be skipped USAGE: .. code-block:: yaml foo: reg.mean: - add: data_field - match: my/custom/event ''' ret = {'name': name, 'changes': {}, 'comment': '', 'result': True} if name not in __reg__: __reg__[name] = {} __reg__[name]['val'] = 0 __reg__[name]['total'] = 0 __reg__[name]['count'] = 0 for event in __events__: try: event_data = event['data']['data'] except KeyError: event_data = event['data'] if salt.utils.stringutils.expr_match(event['tag'], match): if add in event_data: try: comp = int(event_data) except ValueError: continue __reg__[name]['total'] += comp __reg__[name]['count'] += 1 __reg__[name]['val'] = __reg__[name]['total'] / __reg__[name]['count'] return ret
Accept a numeric value from the matched events and store a running average of the values in the given register. If the specified value is not numeric it will be skipped USAGE: .. code-block:: yaml foo: reg.mean: - add: data_field - match: my/custom/event
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/thorium/reg.py#L95-L133
[ "def expr_match(line, expr):\n '''\n Checks whether or not the passed value matches the specified expression.\n Tries to match expr first as a glob using fnmatch.fnmatch(), and then tries\n to match expr as a regular expression. Originally designed to match minion\n IDs for whitelists/blacklists.\n\n Note that this also does exact matches, as fnmatch.fnmatch() will return\n ``True`` when no glob characters are used and the string is an exact match:\n\n .. code-block:: python\n\n >>> fnmatch.fnmatch('foo', 'foo')\n True\n '''\n try:\n if fnmatch.fnmatch(line, expr):\n return True\n try:\n if re.match(r'\\A{0}\\Z'.format(expr), line):\n return True\n except re.error:\n pass\n except TypeError:\n log.exception('Value %r or expression %r is not a string', line, expr)\n return False\n" ]
# -*- coding: utf-8 -*- ''' Used to manage the thorium register. The thorium register is where compound values are stored and computed, such as averages etc. ''' # import python libs from __future__ import absolute_import, division, print_function, unicode_literals import salt.utils.stringutils __func_alias__ = { 'set_': 'set', 'list_': 'list', } def set_(name, add, match): ''' Add a value to the named set USAGE: .. code-block:: yaml foo: reg.set: - add: bar - match: my/custom/event ''' ret = {'name': name, 'changes': {}, 'comment': '', 'result': True} if name not in __reg__: __reg__[name] = {} __reg__[name]['val'] = set() for event in __events__: if salt.utils.stringutils.expr_match(event['tag'], match): try: val = event['data']['data'].get(add) except KeyError: val = event['data'].get(add) if val is None: val = 'None' ret['changes'][add] = val __reg__[name]['val'].add(val) return ret def list_(name, add, match, stamp=False, prune=0): ''' Add the specified values to the named list If ``stamp`` is True, then the timestamp from the event will also be added if ``prune`` is set to an integer higher than ``0``, then only the last ``prune`` values will be kept in the list. USAGE: .. code-block:: yaml foo: reg.list: - add: bar - match: my/custom/event - stamp: True ''' ret = {'name': name, 'changes': {}, 'comment': '', 'result': True} if not isinstance(add, list): add = add.split(',') if name not in __reg__: __reg__[name] = {} __reg__[name]['val'] = [] for event in __events__: try: event_data = event['data']['data'] except KeyError: event_data = event['data'] if salt.utils.stringutils.expr_match(event['tag'], match): item = {} for key in add: if key in event_data: item[key] = event_data[key] if stamp is True: item['time'] = event['data']['_stamp'] __reg__[name]['val'].append(item) if prune > 0: __reg__[name]['val'] = __reg__[name]['val'][:prune] return ret def clear(name): ''' Clear the namespace from the register USAGE: .. code-block:: yaml clearns: reg.clear: - name: myregister ''' ret = {'name': name, 'changes': {}, 'comment': '', 'result': True} if name in __reg__: __reg__[name].clear() return ret def delete(name): ''' Delete the namespace from the register USAGE: .. code-block:: yaml deletens: reg.delete: - name: myregister ''' ret = {'name': name, 'changes': {}, 'comment': '', 'result': True} if name in __reg__: del __reg__[name] return ret
saltstack/salt
salt/thorium/reg.py
clear
python
def clear(name): ''' Clear the namespace from the register USAGE: .. code-block:: yaml clearns: reg.clear: - name: myregister ''' ret = {'name': name, 'changes': {}, 'comment': '', 'result': True} if name in __reg__: __reg__[name].clear() return ret
Clear the namespace from the register USAGE: .. code-block:: yaml clearns: reg.clear: - name: myregister
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/thorium/reg.py#L136-L154
null
# -*- coding: utf-8 -*- ''' Used to manage the thorium register. The thorium register is where compound values are stored and computed, such as averages etc. ''' # import python libs from __future__ import absolute_import, division, print_function, unicode_literals import salt.utils.stringutils __func_alias__ = { 'set_': 'set', 'list_': 'list', } def set_(name, add, match): ''' Add a value to the named set USAGE: .. code-block:: yaml foo: reg.set: - add: bar - match: my/custom/event ''' ret = {'name': name, 'changes': {}, 'comment': '', 'result': True} if name not in __reg__: __reg__[name] = {} __reg__[name]['val'] = set() for event in __events__: if salt.utils.stringutils.expr_match(event['tag'], match): try: val = event['data']['data'].get(add) except KeyError: val = event['data'].get(add) if val is None: val = 'None' ret['changes'][add] = val __reg__[name]['val'].add(val) return ret def list_(name, add, match, stamp=False, prune=0): ''' Add the specified values to the named list If ``stamp`` is True, then the timestamp from the event will also be added if ``prune`` is set to an integer higher than ``0``, then only the last ``prune`` values will be kept in the list. USAGE: .. code-block:: yaml foo: reg.list: - add: bar - match: my/custom/event - stamp: True ''' ret = {'name': name, 'changes': {}, 'comment': '', 'result': True} if not isinstance(add, list): add = add.split(',') if name not in __reg__: __reg__[name] = {} __reg__[name]['val'] = [] for event in __events__: try: event_data = event['data']['data'] except KeyError: event_data = event['data'] if salt.utils.stringutils.expr_match(event['tag'], match): item = {} for key in add: if key in event_data: item[key] = event_data[key] if stamp is True: item['time'] = event['data']['_stamp'] __reg__[name]['val'].append(item) if prune > 0: __reg__[name]['val'] = __reg__[name]['val'][:prune] return ret def mean(name, add, match): ''' Accept a numeric value from the matched events and store a running average of the values in the given register. If the specified value is not numeric it will be skipped USAGE: .. code-block:: yaml foo: reg.mean: - add: data_field - match: my/custom/event ''' ret = {'name': name, 'changes': {}, 'comment': '', 'result': True} if name not in __reg__: __reg__[name] = {} __reg__[name]['val'] = 0 __reg__[name]['total'] = 0 __reg__[name]['count'] = 0 for event in __events__: try: event_data = event['data']['data'] except KeyError: event_data = event['data'] if salt.utils.stringutils.expr_match(event['tag'], match): if add in event_data: try: comp = int(event_data) except ValueError: continue __reg__[name]['total'] += comp __reg__[name]['count'] += 1 __reg__[name]['val'] = __reg__[name]['total'] / __reg__[name]['count'] return ret def delete(name): ''' Delete the namespace from the register USAGE: .. code-block:: yaml deletens: reg.delete: - name: myregister ''' ret = {'name': name, 'changes': {}, 'comment': '', 'result': True} if name in __reg__: del __reg__[name] return ret
saltstack/salt
salt/thorium/reg.py
delete
python
def delete(name): ''' Delete the namespace from the register USAGE: .. code-block:: yaml deletens: reg.delete: - name: myregister ''' ret = {'name': name, 'changes': {}, 'comment': '', 'result': True} if name in __reg__: del __reg__[name] return ret
Delete the namespace from the register USAGE: .. code-block:: yaml deletens: reg.delete: - name: myregister
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/thorium/reg.py#L157-L175
null
# -*- coding: utf-8 -*- ''' Used to manage the thorium register. The thorium register is where compound values are stored and computed, such as averages etc. ''' # import python libs from __future__ import absolute_import, division, print_function, unicode_literals import salt.utils.stringutils __func_alias__ = { 'set_': 'set', 'list_': 'list', } def set_(name, add, match): ''' Add a value to the named set USAGE: .. code-block:: yaml foo: reg.set: - add: bar - match: my/custom/event ''' ret = {'name': name, 'changes': {}, 'comment': '', 'result': True} if name not in __reg__: __reg__[name] = {} __reg__[name]['val'] = set() for event in __events__: if salt.utils.stringutils.expr_match(event['tag'], match): try: val = event['data']['data'].get(add) except KeyError: val = event['data'].get(add) if val is None: val = 'None' ret['changes'][add] = val __reg__[name]['val'].add(val) return ret def list_(name, add, match, stamp=False, prune=0): ''' Add the specified values to the named list If ``stamp`` is True, then the timestamp from the event will also be added if ``prune`` is set to an integer higher than ``0``, then only the last ``prune`` values will be kept in the list. USAGE: .. code-block:: yaml foo: reg.list: - add: bar - match: my/custom/event - stamp: True ''' ret = {'name': name, 'changes': {}, 'comment': '', 'result': True} if not isinstance(add, list): add = add.split(',') if name not in __reg__: __reg__[name] = {} __reg__[name]['val'] = [] for event in __events__: try: event_data = event['data']['data'] except KeyError: event_data = event['data'] if salt.utils.stringutils.expr_match(event['tag'], match): item = {} for key in add: if key in event_data: item[key] = event_data[key] if stamp is True: item['time'] = event['data']['_stamp'] __reg__[name]['val'].append(item) if prune > 0: __reg__[name]['val'] = __reg__[name]['val'][:prune] return ret def mean(name, add, match): ''' Accept a numeric value from the matched events and store a running average of the values in the given register. If the specified value is not numeric it will be skipped USAGE: .. code-block:: yaml foo: reg.mean: - add: data_field - match: my/custom/event ''' ret = {'name': name, 'changes': {}, 'comment': '', 'result': True} if name not in __reg__: __reg__[name] = {} __reg__[name]['val'] = 0 __reg__[name]['total'] = 0 __reg__[name]['count'] = 0 for event in __events__: try: event_data = event['data']['data'] except KeyError: event_data = event['data'] if salt.utils.stringutils.expr_match(event['tag'], match): if add in event_data: try: comp = int(event_data) except ValueError: continue __reg__[name]['total'] += comp __reg__[name]['count'] += 1 __reg__[name]['val'] = __reg__[name]['total'] / __reg__[name]['count'] return ret def clear(name): ''' Clear the namespace from the register USAGE: .. code-block:: yaml clearns: reg.clear: - name: myregister ''' ret = {'name': name, 'changes': {}, 'comment': '', 'result': True} if name in __reg__: __reg__[name].clear() return ret
saltstack/salt
salt/states/etcd_mod.py
set_
python
def set_(name, value, profile=None, **kwargs): ''' Set a key in etcd name The etcd key name, for example: ``/foo/bar/baz``. value The value the key should contain. profile Optional, defaults to ``None``. Sets the etcd profile to use which has been defined in the Salt Master config. .. code-block:: yaml my_etd_config: etcd.host: 127.0.0.1 etcd.port: 4001 ''' created = False rtn = { 'name': name, 'comment': 'Key contains correct value', 'result': True, 'changes': {} } current = __salt__['etcd.get'](name, profile=profile, **kwargs) if not current: created = True result = __salt__['etcd.set'](name, value, profile=profile, **kwargs) if result and result != current: if created: rtn['comment'] = 'New key created' else: rtn['comment'] = 'Key value updated' rtn['changes'] = { name: value } return rtn
Set a key in etcd name The etcd key name, for example: ``/foo/bar/baz``. value The value the key should contain. profile Optional, defaults to ``None``. Sets the etcd profile to use which has been defined in the Salt Master config. .. code-block:: yaml my_etd_config: etcd.host: 127.0.0.1 etcd.port: 4001
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/etcd_mod.py#L147-L192
null
# -*- coding: utf-8 -*- ''' Manage etcd Keys ================ .. versionadded:: 2015.8.0 :depends: - python-etcd This state module supports setting and removing keys from etcd. Configuration ------------- To work with an etcd server you must configure an etcd profile. The etcd config can be set in either the Salt Minion configuration file or in pillar: .. code-block:: yaml my_etd_config: etcd.host: 127.0.0.1 etcd.port: 4001 It is technically possible to configure etcd without using a profile, but this is not considered to be a best practice, especially when multiple etcd servers or clusters are available. .. code-block:: yaml etcd.host: 127.0.0.1 etcd.port: 4001 .. note:: The etcd configuration can also be set in the Salt Master config file, but in order to use any etcd configurations defined in the Salt Master config, the :conf_master:`pillar_opts` must be set to ``True``. Be aware that setting ``pillar_opts`` to ``True`` has security implications as this makes all master configuration settings available in all minion's pillars. Etcd profile configuration can be overridden using following arguments: ``host``, ``port``, ``username``, ``password``, ``ca``, ``client_key`` and ``client_cert``. .. code-block:: yaml my-value: etcd.set: - name: /path/to/key - value: value - host: 127.0.0.1 - port: 2379 - username: user - password: pass Available Functions ------------------- - ``set`` This will set a value to a key in etcd. Changes will be returned if the key has been created or the value of the key has been updated. This means you can watch these states for changes. .. code-block:: yaml /foo/bar/baz: etcd.set: - value: foo - profile: my_etcd_config - ``wait_set`` Performs the same functionality as ``set`` but only if a watch requisite is ``True``. .. code-block:: yaml /some/file.txt: file.managed: - source: salt://file.txt /foo/bar/baz: etcd.wait_set: - value: foo - profile: my_etcd_config - watch: - file: /some/file.txt - ``rm`` This will delete a key from etcd. If the key exists then changes will be returned and thus you can watch for changes on the state, if the key does not exist then no changes will occur. .. code-block:: yaml /foo/bar/baz: etcd.rm: - profile: my_etcd_config - ``wait_rm`` Performs the same functionality as ``rm`` but only if a watch requisite is ``True``. .. code-block:: yaml /some/file.txt: file.managed: - source: salt://file.txt /foo/bar/baz: etcd.wait_rm: - profile: my_etcd_config - watch: - file: /some/file.txt ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals # Define the module's virtual name __virtualname__ = 'etcd' # Function aliases __func_alias__ = { 'set_': 'set', } # Import third party libs try: import salt.utils.etcd_util # pylint: disable=W0611 HAS_ETCD = True except ImportError: HAS_ETCD = False def __virtual__(): ''' Only return if python-etcd is installed ''' return __virtualname__ if HAS_ETCD else False def wait_set(name, value, profile=None, **kwargs): ''' Set a key in etcd only if the watch statement calls it. This function is also aliased as ``wait_set``. name The etcd key name, for example: ``/foo/bar/baz``. value The value the key should contain. profile The etcd profile to use that has been configured on the Salt Master, this is optional and defaults to ``None``. .. code-block:: yaml my_etd_config: etcd.host: 127.0.0.1 etcd.port: 4001 ''' return { 'name': name, 'changes': {}, 'result': True, 'comment': '' } def directory(name, profile=None, **kwargs): ''' Create a directory in etcd. name The etcd directory name, for example: ``/foo/bar/baz``. profile Optional, defaults to ``None``. Sets the etcd profile to use which has been defined in the Salt Master config. .. code-block:: yaml my_etd_config: etcd.host: 127.0.0.1 etcd.port: 4001 ''' created = False rtn = { 'name': name, 'comment': 'Directory exists', 'result': True, 'changes': {} } current = __salt__['etcd.get'](name, profile=profile, recurse=True, **kwargs) if not current: created = True result = __salt__['etcd.set'](name, None, directory=True, profile=profile, **kwargs) if result and result != current: if created: rtn['comment'] = 'New directory created' rtn['changes'] = { name: 'Created' } return rtn def rm(name, recurse=False, profile=None, **kwargs): ''' Deletes a key from etcd name The etcd key name to remove, for example ``/foo/bar/baz``. recurse Optional, defaults to ``False``. If ``True`` performs a recursive delete. profile Optional, defaults to ``None``. Sets the etcd profile to use which has been defined in the Salt Master config. .. code-block:: yaml my_etd_config: etcd.host: 127.0.0.1 etcd.port: 4001 ''' rtn = { 'name': name, 'result': True, 'changes': {} } if not __salt__['etcd.get'](name, profile=profile, **kwargs): rtn['comment'] = 'Key does not exist' return rtn if __salt__['etcd.rm'](name, recurse=recurse, profile=profile, **kwargs): rtn['comment'] = 'Key removed' rtn['changes'] = { name: 'Deleted' } else: rtn['comment'] = 'Unable to remove key' return rtn def wait_rm(name, recurse=False, profile=None, **kwargs): ''' Deletes a key from etcd only if the watch statement calls it. This function is also aliased as ``wait_rm``. name The etcd key name to remove, for example ``/foo/bar/baz``. recurse Optional, defaults to ``False``. If ``True`` performs a recursive delete, see: https://python-etcd.readthedocs.io/en/latest/#delete-a-key. profile Optional, defaults to ``None``. Sets the etcd profile to use which has been defined in the Salt Master config. .. code-block:: yaml my_etd_config: etcd.host: 127.0.0.1 etcd.port: 4001 ''' return { 'name': name, 'changes': {}, 'result': True, 'comment': '' } def mod_watch(name, **kwargs): ''' The etcd watcher, called to invoke the watch command. When called, execute a etcd function based on a watch call requisite. .. note:: This state exists to support special handling of the ``watch`` :ref:`requisite <requisites>`. It should not be called directly. Parameters for this function should be set by the state being triggered. ''' # Watch to set etcd key if kwargs.get('sfun') in ['wait_set_key', 'wait_set']: return set_( name, kwargs.get('value'), kwargs.get('profile')) # Watch to rm etcd key if kwargs.get('sfun') in ['wait_rm_key', 'wait_rm']: return rm( name, kwargs.get('profile')) return { 'name': name, 'changes': {}, 'comment': 'etcd.{0[sfun]} does not work with the watch requisite, ' 'please use etcd.wait_set or etcd.wait_rm'.format(kwargs), 'result': False }
saltstack/salt
salt/states/etcd_mod.py
directory
python
def directory(name, profile=None, **kwargs): ''' Create a directory in etcd. name The etcd directory name, for example: ``/foo/bar/baz``. profile Optional, defaults to ``None``. Sets the etcd profile to use which has been defined in the Salt Master config. .. code-block:: yaml my_etd_config: etcd.host: 127.0.0.1 etcd.port: 4001 ''' created = False rtn = { 'name': name, 'comment': 'Directory exists', 'result': True, 'changes': {} } current = __salt__['etcd.get'](name, profile=profile, recurse=True, **kwargs) if not current: created = True result = __salt__['etcd.set'](name, None, directory=True, profile=profile, **kwargs) if result and result != current: if created: rtn['comment'] = 'New directory created' rtn['changes'] = { name: 'Created' } return rtn
Create a directory in etcd. name The etcd directory name, for example: ``/foo/bar/baz``. profile Optional, defaults to ``None``. Sets the etcd profile to use which has been defined in the Salt Master config. .. code-block:: yaml my_etd_config: etcd.host: 127.0.0.1 etcd.port: 4001
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/etcd_mod.py#L224-L263
null
# -*- coding: utf-8 -*- ''' Manage etcd Keys ================ .. versionadded:: 2015.8.0 :depends: - python-etcd This state module supports setting and removing keys from etcd. Configuration ------------- To work with an etcd server you must configure an etcd profile. The etcd config can be set in either the Salt Minion configuration file or in pillar: .. code-block:: yaml my_etd_config: etcd.host: 127.0.0.1 etcd.port: 4001 It is technically possible to configure etcd without using a profile, but this is not considered to be a best practice, especially when multiple etcd servers or clusters are available. .. code-block:: yaml etcd.host: 127.0.0.1 etcd.port: 4001 .. note:: The etcd configuration can also be set in the Salt Master config file, but in order to use any etcd configurations defined in the Salt Master config, the :conf_master:`pillar_opts` must be set to ``True``. Be aware that setting ``pillar_opts`` to ``True`` has security implications as this makes all master configuration settings available in all minion's pillars. Etcd profile configuration can be overridden using following arguments: ``host``, ``port``, ``username``, ``password``, ``ca``, ``client_key`` and ``client_cert``. .. code-block:: yaml my-value: etcd.set: - name: /path/to/key - value: value - host: 127.0.0.1 - port: 2379 - username: user - password: pass Available Functions ------------------- - ``set`` This will set a value to a key in etcd. Changes will be returned if the key has been created or the value of the key has been updated. This means you can watch these states for changes. .. code-block:: yaml /foo/bar/baz: etcd.set: - value: foo - profile: my_etcd_config - ``wait_set`` Performs the same functionality as ``set`` but only if a watch requisite is ``True``. .. code-block:: yaml /some/file.txt: file.managed: - source: salt://file.txt /foo/bar/baz: etcd.wait_set: - value: foo - profile: my_etcd_config - watch: - file: /some/file.txt - ``rm`` This will delete a key from etcd. If the key exists then changes will be returned and thus you can watch for changes on the state, if the key does not exist then no changes will occur. .. code-block:: yaml /foo/bar/baz: etcd.rm: - profile: my_etcd_config - ``wait_rm`` Performs the same functionality as ``rm`` but only if a watch requisite is ``True``. .. code-block:: yaml /some/file.txt: file.managed: - source: salt://file.txt /foo/bar/baz: etcd.wait_rm: - profile: my_etcd_config - watch: - file: /some/file.txt ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals # Define the module's virtual name __virtualname__ = 'etcd' # Function aliases __func_alias__ = { 'set_': 'set', } # Import third party libs try: import salt.utils.etcd_util # pylint: disable=W0611 HAS_ETCD = True except ImportError: HAS_ETCD = False def __virtual__(): ''' Only return if python-etcd is installed ''' return __virtualname__ if HAS_ETCD else False def set_(name, value, profile=None, **kwargs): ''' Set a key in etcd name The etcd key name, for example: ``/foo/bar/baz``. value The value the key should contain. profile Optional, defaults to ``None``. Sets the etcd profile to use which has been defined in the Salt Master config. .. code-block:: yaml my_etd_config: etcd.host: 127.0.0.1 etcd.port: 4001 ''' created = False rtn = { 'name': name, 'comment': 'Key contains correct value', 'result': True, 'changes': {} } current = __salt__['etcd.get'](name, profile=profile, **kwargs) if not current: created = True result = __salt__['etcd.set'](name, value, profile=profile, **kwargs) if result and result != current: if created: rtn['comment'] = 'New key created' else: rtn['comment'] = 'Key value updated' rtn['changes'] = { name: value } return rtn def wait_set(name, value, profile=None, **kwargs): ''' Set a key in etcd only if the watch statement calls it. This function is also aliased as ``wait_set``. name The etcd key name, for example: ``/foo/bar/baz``. value The value the key should contain. profile The etcd profile to use that has been configured on the Salt Master, this is optional and defaults to ``None``. .. code-block:: yaml my_etd_config: etcd.host: 127.0.0.1 etcd.port: 4001 ''' return { 'name': name, 'changes': {}, 'result': True, 'comment': '' } def rm(name, recurse=False, profile=None, **kwargs): ''' Deletes a key from etcd name The etcd key name to remove, for example ``/foo/bar/baz``. recurse Optional, defaults to ``False``. If ``True`` performs a recursive delete. profile Optional, defaults to ``None``. Sets the etcd profile to use which has been defined in the Salt Master config. .. code-block:: yaml my_etd_config: etcd.host: 127.0.0.1 etcd.port: 4001 ''' rtn = { 'name': name, 'result': True, 'changes': {} } if not __salt__['etcd.get'](name, profile=profile, **kwargs): rtn['comment'] = 'Key does not exist' return rtn if __salt__['etcd.rm'](name, recurse=recurse, profile=profile, **kwargs): rtn['comment'] = 'Key removed' rtn['changes'] = { name: 'Deleted' } else: rtn['comment'] = 'Unable to remove key' return rtn def wait_rm(name, recurse=False, profile=None, **kwargs): ''' Deletes a key from etcd only if the watch statement calls it. This function is also aliased as ``wait_rm``. name The etcd key name to remove, for example ``/foo/bar/baz``. recurse Optional, defaults to ``False``. If ``True`` performs a recursive delete, see: https://python-etcd.readthedocs.io/en/latest/#delete-a-key. profile Optional, defaults to ``None``. Sets the etcd profile to use which has been defined in the Salt Master config. .. code-block:: yaml my_etd_config: etcd.host: 127.0.0.1 etcd.port: 4001 ''' return { 'name': name, 'changes': {}, 'result': True, 'comment': '' } def mod_watch(name, **kwargs): ''' The etcd watcher, called to invoke the watch command. When called, execute a etcd function based on a watch call requisite. .. note:: This state exists to support special handling of the ``watch`` :ref:`requisite <requisites>`. It should not be called directly. Parameters for this function should be set by the state being triggered. ''' # Watch to set etcd key if kwargs.get('sfun') in ['wait_set_key', 'wait_set']: return set_( name, kwargs.get('value'), kwargs.get('profile')) # Watch to rm etcd key if kwargs.get('sfun') in ['wait_rm_key', 'wait_rm']: return rm( name, kwargs.get('profile')) return { 'name': name, 'changes': {}, 'comment': 'etcd.{0[sfun]} does not work with the watch requisite, ' 'please use etcd.wait_set or etcd.wait_rm'.format(kwargs), 'result': False }
saltstack/salt
salt/states/etcd_mod.py
rm
python
def rm(name, recurse=False, profile=None, **kwargs): ''' Deletes a key from etcd name The etcd key name to remove, for example ``/foo/bar/baz``. recurse Optional, defaults to ``False``. If ``True`` performs a recursive delete. profile Optional, defaults to ``None``. Sets the etcd profile to use which has been defined in the Salt Master config. .. code-block:: yaml my_etd_config: etcd.host: 127.0.0.1 etcd.port: 4001 ''' rtn = { 'name': name, 'result': True, 'changes': {} } if not __salt__['etcd.get'](name, profile=profile, **kwargs): rtn['comment'] = 'Key does not exist' return rtn if __salt__['etcd.rm'](name, recurse=recurse, profile=profile, **kwargs): rtn['comment'] = 'Key removed' rtn['changes'] = { name: 'Deleted' } else: rtn['comment'] = 'Unable to remove key' return rtn
Deletes a key from etcd name The etcd key name to remove, for example ``/foo/bar/baz``. recurse Optional, defaults to ``False``. If ``True`` performs a recursive delete. profile Optional, defaults to ``None``. Sets the etcd profile to use which has been defined in the Salt Master config. .. code-block:: yaml my_etd_config: etcd.host: 127.0.0.1 etcd.port: 4001
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/etcd_mod.py#L266-L305
null
# -*- coding: utf-8 -*- ''' Manage etcd Keys ================ .. versionadded:: 2015.8.0 :depends: - python-etcd This state module supports setting and removing keys from etcd. Configuration ------------- To work with an etcd server you must configure an etcd profile. The etcd config can be set in either the Salt Minion configuration file or in pillar: .. code-block:: yaml my_etd_config: etcd.host: 127.0.0.1 etcd.port: 4001 It is technically possible to configure etcd without using a profile, but this is not considered to be a best practice, especially when multiple etcd servers or clusters are available. .. code-block:: yaml etcd.host: 127.0.0.1 etcd.port: 4001 .. note:: The etcd configuration can also be set in the Salt Master config file, but in order to use any etcd configurations defined in the Salt Master config, the :conf_master:`pillar_opts` must be set to ``True``. Be aware that setting ``pillar_opts`` to ``True`` has security implications as this makes all master configuration settings available in all minion's pillars. Etcd profile configuration can be overridden using following arguments: ``host``, ``port``, ``username``, ``password``, ``ca``, ``client_key`` and ``client_cert``. .. code-block:: yaml my-value: etcd.set: - name: /path/to/key - value: value - host: 127.0.0.1 - port: 2379 - username: user - password: pass Available Functions ------------------- - ``set`` This will set a value to a key in etcd. Changes will be returned if the key has been created or the value of the key has been updated. This means you can watch these states for changes. .. code-block:: yaml /foo/bar/baz: etcd.set: - value: foo - profile: my_etcd_config - ``wait_set`` Performs the same functionality as ``set`` but only if a watch requisite is ``True``. .. code-block:: yaml /some/file.txt: file.managed: - source: salt://file.txt /foo/bar/baz: etcd.wait_set: - value: foo - profile: my_etcd_config - watch: - file: /some/file.txt - ``rm`` This will delete a key from etcd. If the key exists then changes will be returned and thus you can watch for changes on the state, if the key does not exist then no changes will occur. .. code-block:: yaml /foo/bar/baz: etcd.rm: - profile: my_etcd_config - ``wait_rm`` Performs the same functionality as ``rm`` but only if a watch requisite is ``True``. .. code-block:: yaml /some/file.txt: file.managed: - source: salt://file.txt /foo/bar/baz: etcd.wait_rm: - profile: my_etcd_config - watch: - file: /some/file.txt ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals # Define the module's virtual name __virtualname__ = 'etcd' # Function aliases __func_alias__ = { 'set_': 'set', } # Import third party libs try: import salt.utils.etcd_util # pylint: disable=W0611 HAS_ETCD = True except ImportError: HAS_ETCD = False def __virtual__(): ''' Only return if python-etcd is installed ''' return __virtualname__ if HAS_ETCD else False def set_(name, value, profile=None, **kwargs): ''' Set a key in etcd name The etcd key name, for example: ``/foo/bar/baz``. value The value the key should contain. profile Optional, defaults to ``None``. Sets the etcd profile to use which has been defined in the Salt Master config. .. code-block:: yaml my_etd_config: etcd.host: 127.0.0.1 etcd.port: 4001 ''' created = False rtn = { 'name': name, 'comment': 'Key contains correct value', 'result': True, 'changes': {} } current = __salt__['etcd.get'](name, profile=profile, **kwargs) if not current: created = True result = __salt__['etcd.set'](name, value, profile=profile, **kwargs) if result and result != current: if created: rtn['comment'] = 'New key created' else: rtn['comment'] = 'Key value updated' rtn['changes'] = { name: value } return rtn def wait_set(name, value, profile=None, **kwargs): ''' Set a key in etcd only if the watch statement calls it. This function is also aliased as ``wait_set``. name The etcd key name, for example: ``/foo/bar/baz``. value The value the key should contain. profile The etcd profile to use that has been configured on the Salt Master, this is optional and defaults to ``None``. .. code-block:: yaml my_etd_config: etcd.host: 127.0.0.1 etcd.port: 4001 ''' return { 'name': name, 'changes': {}, 'result': True, 'comment': '' } def directory(name, profile=None, **kwargs): ''' Create a directory in etcd. name The etcd directory name, for example: ``/foo/bar/baz``. profile Optional, defaults to ``None``. Sets the etcd profile to use which has been defined in the Salt Master config. .. code-block:: yaml my_etd_config: etcd.host: 127.0.0.1 etcd.port: 4001 ''' created = False rtn = { 'name': name, 'comment': 'Directory exists', 'result': True, 'changes': {} } current = __salt__['etcd.get'](name, profile=profile, recurse=True, **kwargs) if not current: created = True result = __salt__['etcd.set'](name, None, directory=True, profile=profile, **kwargs) if result and result != current: if created: rtn['comment'] = 'New directory created' rtn['changes'] = { name: 'Created' } return rtn def wait_rm(name, recurse=False, profile=None, **kwargs): ''' Deletes a key from etcd only if the watch statement calls it. This function is also aliased as ``wait_rm``. name The etcd key name to remove, for example ``/foo/bar/baz``. recurse Optional, defaults to ``False``. If ``True`` performs a recursive delete, see: https://python-etcd.readthedocs.io/en/latest/#delete-a-key. profile Optional, defaults to ``None``. Sets the etcd profile to use which has been defined in the Salt Master config. .. code-block:: yaml my_etd_config: etcd.host: 127.0.0.1 etcd.port: 4001 ''' return { 'name': name, 'changes': {}, 'result': True, 'comment': '' } def mod_watch(name, **kwargs): ''' The etcd watcher, called to invoke the watch command. When called, execute a etcd function based on a watch call requisite. .. note:: This state exists to support special handling of the ``watch`` :ref:`requisite <requisites>`. It should not be called directly. Parameters for this function should be set by the state being triggered. ''' # Watch to set etcd key if kwargs.get('sfun') in ['wait_set_key', 'wait_set']: return set_( name, kwargs.get('value'), kwargs.get('profile')) # Watch to rm etcd key if kwargs.get('sfun') in ['wait_rm_key', 'wait_rm']: return rm( name, kwargs.get('profile')) return { 'name': name, 'changes': {}, 'comment': 'etcd.{0[sfun]} does not work with the watch requisite, ' 'please use etcd.wait_set or etcd.wait_rm'.format(kwargs), 'result': False }
saltstack/salt
salt/states/etcd_mod.py
mod_watch
python
def mod_watch(name, **kwargs): ''' The etcd watcher, called to invoke the watch command. When called, execute a etcd function based on a watch call requisite. .. note:: This state exists to support special handling of the ``watch`` :ref:`requisite <requisites>`. It should not be called directly. Parameters for this function should be set by the state being triggered. ''' # Watch to set etcd key if kwargs.get('sfun') in ['wait_set_key', 'wait_set']: return set_( name, kwargs.get('value'), kwargs.get('profile')) # Watch to rm etcd key if kwargs.get('sfun') in ['wait_rm_key', 'wait_rm']: return rm( name, kwargs.get('profile')) return { 'name': name, 'changes': {}, 'comment': 'etcd.{0[sfun]} does not work with the watch requisite, ' 'please use etcd.wait_set or etcd.wait_rm'.format(kwargs), 'result': False }
The etcd watcher, called to invoke the watch command. When called, execute a etcd function based on a watch call requisite. .. note:: This state exists to support special handling of the ``watch`` :ref:`requisite <requisites>`. It should not be called directly. Parameters for this function should be set by the state being triggered.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/etcd_mod.py#L337-L368
[ "def rm(name, recurse=False, profile=None, **kwargs):\n '''\n Deletes a key from etcd\n\n name\n The etcd key name to remove, for example ``/foo/bar/baz``.\n\n recurse\n Optional, defaults to ``False``. If ``True`` performs a recursive delete.\n\n profile\n Optional, defaults to ``None``. Sets the etcd profile to use which has\n been defined in the Salt Master config.\n\n .. code-block:: yaml\n\n my_etd_config:\n etcd.host: 127.0.0.1\n etcd.port: 4001\n '''\n\n rtn = {\n 'name': name,\n 'result': True,\n 'changes': {}\n }\n\n if not __salt__['etcd.get'](name, profile=profile, **kwargs):\n rtn['comment'] = 'Key does not exist'\n return rtn\n\n if __salt__['etcd.rm'](name, recurse=recurse, profile=profile, **kwargs):\n rtn['comment'] = 'Key removed'\n rtn['changes'] = {\n name: 'Deleted'\n }\n else:\n rtn['comment'] = 'Unable to remove key'\n\n return rtn\n", "def set_(name, value, profile=None, **kwargs):\n '''\n Set a key in etcd\n\n name\n The etcd key name, for example: ``/foo/bar/baz``.\n value\n The value the key should contain.\n\n profile\n Optional, defaults to ``None``. Sets the etcd profile to use which has\n been defined in the Salt Master config.\n\n .. code-block:: yaml\n\n my_etd_config:\n etcd.host: 127.0.0.1\n etcd.port: 4001\n\n '''\n\n created = False\n\n rtn = {\n 'name': name,\n 'comment': 'Key contains correct value',\n 'result': True,\n 'changes': {}\n }\n\n current = __salt__['etcd.get'](name, profile=profile, **kwargs)\n if not current:\n created = True\n\n result = __salt__['etcd.set'](name, value, profile=profile, **kwargs)\n\n if result and result != current:\n if created:\n rtn['comment'] = 'New key created'\n else:\n rtn['comment'] = 'Key value updated'\n rtn['changes'] = {\n name: value\n }\n\n return rtn\n" ]
# -*- coding: utf-8 -*- ''' Manage etcd Keys ================ .. versionadded:: 2015.8.0 :depends: - python-etcd This state module supports setting and removing keys from etcd. Configuration ------------- To work with an etcd server you must configure an etcd profile. The etcd config can be set in either the Salt Minion configuration file or in pillar: .. code-block:: yaml my_etd_config: etcd.host: 127.0.0.1 etcd.port: 4001 It is technically possible to configure etcd without using a profile, but this is not considered to be a best practice, especially when multiple etcd servers or clusters are available. .. code-block:: yaml etcd.host: 127.0.0.1 etcd.port: 4001 .. note:: The etcd configuration can also be set in the Salt Master config file, but in order to use any etcd configurations defined in the Salt Master config, the :conf_master:`pillar_opts` must be set to ``True``. Be aware that setting ``pillar_opts`` to ``True`` has security implications as this makes all master configuration settings available in all minion's pillars. Etcd profile configuration can be overridden using following arguments: ``host``, ``port``, ``username``, ``password``, ``ca``, ``client_key`` and ``client_cert``. .. code-block:: yaml my-value: etcd.set: - name: /path/to/key - value: value - host: 127.0.0.1 - port: 2379 - username: user - password: pass Available Functions ------------------- - ``set`` This will set a value to a key in etcd. Changes will be returned if the key has been created or the value of the key has been updated. This means you can watch these states for changes. .. code-block:: yaml /foo/bar/baz: etcd.set: - value: foo - profile: my_etcd_config - ``wait_set`` Performs the same functionality as ``set`` but only if a watch requisite is ``True``. .. code-block:: yaml /some/file.txt: file.managed: - source: salt://file.txt /foo/bar/baz: etcd.wait_set: - value: foo - profile: my_etcd_config - watch: - file: /some/file.txt - ``rm`` This will delete a key from etcd. If the key exists then changes will be returned and thus you can watch for changes on the state, if the key does not exist then no changes will occur. .. code-block:: yaml /foo/bar/baz: etcd.rm: - profile: my_etcd_config - ``wait_rm`` Performs the same functionality as ``rm`` but only if a watch requisite is ``True``. .. code-block:: yaml /some/file.txt: file.managed: - source: salt://file.txt /foo/bar/baz: etcd.wait_rm: - profile: my_etcd_config - watch: - file: /some/file.txt ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals # Define the module's virtual name __virtualname__ = 'etcd' # Function aliases __func_alias__ = { 'set_': 'set', } # Import third party libs try: import salt.utils.etcd_util # pylint: disable=W0611 HAS_ETCD = True except ImportError: HAS_ETCD = False def __virtual__(): ''' Only return if python-etcd is installed ''' return __virtualname__ if HAS_ETCD else False def set_(name, value, profile=None, **kwargs): ''' Set a key in etcd name The etcd key name, for example: ``/foo/bar/baz``. value The value the key should contain. profile Optional, defaults to ``None``. Sets the etcd profile to use which has been defined in the Salt Master config. .. code-block:: yaml my_etd_config: etcd.host: 127.0.0.1 etcd.port: 4001 ''' created = False rtn = { 'name': name, 'comment': 'Key contains correct value', 'result': True, 'changes': {} } current = __salt__['etcd.get'](name, profile=profile, **kwargs) if not current: created = True result = __salt__['etcd.set'](name, value, profile=profile, **kwargs) if result and result != current: if created: rtn['comment'] = 'New key created' else: rtn['comment'] = 'Key value updated' rtn['changes'] = { name: value } return rtn def wait_set(name, value, profile=None, **kwargs): ''' Set a key in etcd only if the watch statement calls it. This function is also aliased as ``wait_set``. name The etcd key name, for example: ``/foo/bar/baz``. value The value the key should contain. profile The etcd profile to use that has been configured on the Salt Master, this is optional and defaults to ``None``. .. code-block:: yaml my_etd_config: etcd.host: 127.0.0.1 etcd.port: 4001 ''' return { 'name': name, 'changes': {}, 'result': True, 'comment': '' } def directory(name, profile=None, **kwargs): ''' Create a directory in etcd. name The etcd directory name, for example: ``/foo/bar/baz``. profile Optional, defaults to ``None``. Sets the etcd profile to use which has been defined in the Salt Master config. .. code-block:: yaml my_etd_config: etcd.host: 127.0.0.1 etcd.port: 4001 ''' created = False rtn = { 'name': name, 'comment': 'Directory exists', 'result': True, 'changes': {} } current = __salt__['etcd.get'](name, profile=profile, recurse=True, **kwargs) if not current: created = True result = __salt__['etcd.set'](name, None, directory=True, profile=profile, **kwargs) if result and result != current: if created: rtn['comment'] = 'New directory created' rtn['changes'] = { name: 'Created' } return rtn def rm(name, recurse=False, profile=None, **kwargs): ''' Deletes a key from etcd name The etcd key name to remove, for example ``/foo/bar/baz``. recurse Optional, defaults to ``False``. If ``True`` performs a recursive delete. profile Optional, defaults to ``None``. Sets the etcd profile to use which has been defined in the Salt Master config. .. code-block:: yaml my_etd_config: etcd.host: 127.0.0.1 etcd.port: 4001 ''' rtn = { 'name': name, 'result': True, 'changes': {} } if not __salt__['etcd.get'](name, profile=profile, **kwargs): rtn['comment'] = 'Key does not exist' return rtn if __salt__['etcd.rm'](name, recurse=recurse, profile=profile, **kwargs): rtn['comment'] = 'Key removed' rtn['changes'] = { name: 'Deleted' } else: rtn['comment'] = 'Unable to remove key' return rtn def wait_rm(name, recurse=False, profile=None, **kwargs): ''' Deletes a key from etcd only if the watch statement calls it. This function is also aliased as ``wait_rm``. name The etcd key name to remove, for example ``/foo/bar/baz``. recurse Optional, defaults to ``False``. If ``True`` performs a recursive delete, see: https://python-etcd.readthedocs.io/en/latest/#delete-a-key. profile Optional, defaults to ``None``. Sets the etcd profile to use which has been defined in the Salt Master config. .. code-block:: yaml my_etd_config: etcd.host: 127.0.0.1 etcd.port: 4001 ''' return { 'name': name, 'changes': {}, 'result': True, 'comment': '' }